aboutsummaryrefslogtreecommitdiffstats
path: root/models-base/src
diff options
context:
space:
mode:
authorJim Hahn <jrh3@att.com>2020-12-17 12:07:14 -0500
committerJim Hahn <jrh3@att.com>2020-12-17 18:52:46 -0500
commit6345dce40405740dc09176c45dae03baeb939b8e (patch)
tree07804a2f9e2dfd1083975c79059346a9cf778b1d /models-base/src
parent4c4946e339942863e73e20726dd95aaacfcfb5a6 (diff)
Use ValidationResult for models v2.0
Policy models uses PfValidationXxx classes which are totally unrelated to ValidationResult in policy common. This precludes the use of various utility methods and annotations for doing validation. Modified policy models to use ValidationResult instead. This approach uses function calls, though a future approach could make use of annotations instead. Issue-ID: POLICY-2648 Change-Id: I9760f1dc46902ab6bef7f440f3caf5e951660a5d Signed-off-by: Jim Hahn <jrh3@att.com>
Diffstat (limited to 'models-base/src')
-rw-r--r--models-base/src/main/java/org/onap/policy/models/base/PfConcept.java13
-rw-r--r--models-base/src/main/java/org/onap/policy/models/base/PfConceptContainer.java49
-rw-r--r--models-base/src/main/java/org/onap/policy/models/base/PfKeyImpl.java22
-rw-r--r--models-base/src/main/java/org/onap/policy/models/base/PfKeyUse.java15
-rw-r--r--models-base/src/main/java/org/onap/policy/models/base/PfModel.java100
-rw-r--r--models-base/src/main/java/org/onap/policy/models/base/PfReferenceKey.java38
-rw-r--r--models-base/src/main/java/org/onap/policy/models/base/PfValidationMessage.java104
-rw-r--r--models-base/src/main/java/org/onap/policy/models/base/PfValidationResult.java146
-rw-r--r--models-base/src/main/java/org/onap/policy/models/base/Validated.java377
-rw-r--r--models-base/src/test/java/org/onap/policy/models/base/PfConceptContainerTest.java25
-rw-r--r--models-base/src/test/java/org/onap/policy/models/base/PfKeyImplTest.java37
-rw-r--r--models-base/src/test/java/org/onap/policy/models/base/PfKeyUseTest.java10
-rw-r--r--models-base/src/test/java/org/onap/policy/models/base/PfModelTest.java34
-rw-r--r--models-base/src/test/java/org/onap/policy/models/base/PfReferenceKeyTest.java42
-rw-r--r--models-base/src/test/java/org/onap/policy/models/base/ValidatedTest.java645
-rw-r--r--models-base/src/test/java/org/onap/policy/models/base/ValidationTest.java133
-rw-r--r--models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfConcept.java24
-rw-r--r--models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfKey.java6
-rw-r--r--models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfModel.java12
19 files changed, 735 insertions, 1097 deletions
diff --git a/models-base/src/main/java/org/onap/policy/models/base/PfConcept.java b/models-base/src/main/java/org/onap/policy/models/base/PfConcept.java
index 5273bd39e..394eb89f2 100644
--- a/models-base/src/main/java/org/onap/policy/models/base/PfConcept.java
+++ b/models-base/src/main/java/org/onap/policy/models/base/PfConcept.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
- * 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.
@@ -30,7 +30,7 @@ import lombok.NonNull;
* and interfaces on all concepts that are sub-classes of this class.
*/
-public abstract class PfConcept implements Serializable, Comparable<PfConcept> {
+public abstract class PfConcept extends Validated implements Serializable, Comparable<PfConcept> {
private static final long serialVersionUID = -7434939557282697490L;
/**
@@ -65,15 +65,6 @@ public abstract class PfConcept implements Serializable, Comparable<PfConcept> {
public abstract List<PfKey> getKeys();
/**
- * Validate that this concept is structurally correct.
- *
- * @param result the parameter in which the result of the validation will be returned
- * @return the validation result that was passed in in the @{link result} field with the result of this validation
- * added
- */
- public abstract PfValidationResult validate(@NonNull final PfValidationResult result);
-
- /**
* Clean this concept, tidy up any superfluous information such as leading and trailing white space.
*/
public abstract void clean();
diff --git a/models-base/src/main/java/org/onap/policy/models/base/PfConceptContainer.java b/models-base/src/main/java/org/onap/policy/models/base/PfConceptContainer.java
index 863a3ef02..484632f7c 100644
--- a/models-base/src/main/java/org/onap/policy/models/base/PfConceptContainer.java
+++ b/models-base/src/main/java/org/onap/policy/models/base/PfConceptContainer.java
@@ -45,7 +45,8 @@ import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NonNull;
import org.apache.commons.lang3.StringUtils;
-import org.onap.policy.models.base.PfValidationResult.ValidationResult;
+import org.onap.policy.common.parameters.BeanValidationResult;
+import org.onap.policy.common.parameters.ValidationResult;
// @formatter:off
/**
@@ -241,19 +242,11 @@ public class PfConceptContainer<C extends PfConcept, A extends PfNameVersion> ex
}
@Override
- public PfValidationResult validate(@NonNull final PfValidationResult resultIn) {
- PfValidationResult result = resultIn;
+ public BeanValidationResult validate(@NonNull String fieldName) {
+ BeanValidationResult result = new BeanValidationResult(fieldName, this);
- if (key.equals(PfConceptKey.getNullKey())) {
- result.addValidationMessage(
- new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key is a null key"));
- }
-
- result = key.validate(result);
-
- if (!conceptMap.isEmpty()) {
- result = validateConceptMap(result);
- }
+ result.addResult(validateKeyNotNull("key", key));
+ result.addResult(validateConceptMap());
return result;
}
@@ -261,29 +254,31 @@ public class PfConceptContainer<C extends PfConcept, A extends PfNameVersion> ex
/**
* Validate the concept map of the container.
*
- * @param resultIn the incoming validation results so far
- * @return the validation results with the results of this validation added
+ * @return the validation result
*/
- private PfValidationResult validateConceptMap(final PfValidationResult resultIn) {
- PfValidationResult result = resultIn;
+ private ValidationResult validateConceptMap() {
+ BeanValidationResult result = new BeanValidationResult("conceptMap", conceptMap);
for (final Entry<PfConceptKey, C> conceptEntry : conceptMap.entrySet()) {
+ BeanValidationResult result2 = null;
+
if (conceptEntry.getKey().equals(PfConceptKey.getNullKey())) {
- result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID,
- "key on concept entry " + conceptEntry.getKey() + " may not be the null key"));
+ addResult(result, "key on concept entry", conceptEntry.getKey(), IS_A_NULL_KEY);
} else if (conceptEntry.getValue() == null) {
- result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID,
- "value on concept entry " + conceptEntry.getKey() + " may not be null"));
+ result2 = new BeanValidationResult(conceptEntry.getKey().getId(), conceptEntry.getKey());
+ addResult(result2, "value", conceptEntry.getValue(), IS_NULL);
} else if (!conceptEntry.getKey().equals(conceptEntry.getValue().getKey())) {
- result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID,
- "key on concept entry key " + conceptEntry.getKey() + " does not equal concept value key "
- + conceptEntry.getValue().getKey()));
- result = conceptEntry.getValue().validate(result);
+ result2 = new BeanValidationResult(conceptEntry.getKey().getId(), conceptEntry.getKey());
+ addResult(result2, "value", conceptEntry.getValue(), "does not equal concept key");
+ result2.addResult(conceptEntry.getValue().validate("value"));
} else {
- result = conceptEntry.getValue().validate(result);
+ result2 = new BeanValidationResult(conceptEntry.getKey().getId(), conceptEntry.getKey());
+ result2.addResult(conceptEntry.getValue().validate("value"));
}
+
+ result.addResult(result2);
}
- return result;
+ return (result.isClean() ? null : result);
}
@Override
diff --git a/models-base/src/main/java/org/onap/policy/models/base/PfKeyImpl.java b/models-base/src/main/java/org/onap/policy/models/base/PfKeyImpl.java
index 81066c37c..3cbef75f9 100644
--- a/models-base/src/main/java/org/onap/policy/models/base/PfKeyImpl.java
+++ b/models-base/src/main/java/org/onap/policy/models/base/PfKeyImpl.java
@@ -1,7 +1,7 @@
/*
* ============LICENSE_START=======================================================
* Copyright (C) 2019-2020 Nordix Foundation.
- * 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.
@@ -26,8 +26,9 @@ import java.util.List;
import lombok.Getter;
import lombok.NonNull;
import lombok.ToString;
+import org.onap.policy.common.parameters.BeanValidationResult;
+import org.onap.policy.common.parameters.ValidationResult;
import org.onap.policy.common.utils.validation.Assertions;
-import org.onap.policy.models.base.PfValidationResult.ValidationResult;
/**
* A key, upon which other key subclasses can be built, providing implementations of the methods.
@@ -241,20 +242,11 @@ public abstract class PfKeyImpl extends PfKey {
}
@Override
- public PfValidationResult validate(final PfValidationResult result) {
- final String nameValidationErrorMessage =
- Assertions.getStringParameterValidationMessage(NAME_TOKEN, getName(), getNameRegEx());
- if (nameValidationErrorMessage != null) {
- result.addValidationMessage(new PfValidationMessage(this, this.getClass(), ValidationResult.INVALID,
- "name invalid-" + nameValidationErrorMessage));
- }
+ public ValidationResult validate(@NonNull String fieldName) {
+ BeanValidationResult result = new BeanValidationResult(fieldName, this);
- final String versionValidationErrorMessage =
- Assertions.getStringParameterValidationMessage(VERSION_TOKEN, getVersion(), getVersionRegEx());
- if (versionValidationErrorMessage != null) {
- result.addValidationMessage(new PfValidationMessage(this, this.getClass(), ValidationResult.INVALID,
- "version invalid-" + versionValidationErrorMessage));
- }
+ result.addResult(validateRegex(NAME_TOKEN, getName(), getNameRegEx()));
+ result.addResult(validateRegex(VERSION_TOKEN, getVersion(), getVersionRegEx()));
return result;
}
diff --git a/models-base/src/main/java/org/onap/policy/models/base/PfKeyUse.java b/models-base/src/main/java/org/onap/policy/models/base/PfKeyUse.java
index 03873236c..616284daf 100644
--- a/models-base/src/main/java/org/onap/policy/models/base/PfKeyUse.java
+++ b/models-base/src/main/java/org/onap/policy/models/base/PfKeyUse.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
- * 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.
@@ -25,8 +25,9 @@ import java.util.List;
import lombok.EqualsAndHashCode;
import lombok.NonNull;
import lombok.ToString;
+import org.onap.policy.common.parameters.BeanValidationResult;
+import org.onap.policy.common.parameters.ValidationResult;
import org.onap.policy.common.utils.validation.Assertions;
-import org.onap.policy.models.base.PfValidationResult.ValidationResult;
/**
* This class records a usage of a key in the system. When the list of keys being used by a concept
@@ -134,12 +135,10 @@ public class PfKeyUse extends PfKey {
}
@Override
- public PfValidationResult validate(@NonNull final PfValidationResult result) {
- if (usedKey.isNullKey()) {
- result.addValidationMessage(new PfValidationMessage(usedKey, this.getClass(), ValidationResult.INVALID,
- "usedKey is a null key"));
- }
- return usedKey.validate(result);
+ public ValidationResult validate(@NonNull String fieldName) {
+ BeanValidationResult result = new BeanValidationResult(fieldName, this);
+ result.addResult(validateKeyNotNull("usedKey", usedKey));
+ return result;
}
@Override
diff --git a/models-base/src/main/java/org/onap/policy/models/base/PfModel.java b/models-base/src/main/java/org/onap/policy/models/base/PfModel.java
index 340f4e3b2..c87874774 100644
--- a/models-base/src/main/java/org/onap/policy/models/base/PfModel.java
+++ b/models-base/src/main/java/org/onap/policy/models/base/PfModel.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
- * 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.
@@ -32,8 +32,10 @@ import javax.persistence.Table;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NonNull;
+import org.onap.policy.common.parameters.BeanValidationResult;
+import org.onap.policy.common.parameters.ObjectValidationResult;
+import org.onap.policy.common.parameters.ValidationStatus;
import org.onap.policy.common.utils.validation.Assertions;
-import org.onap.policy.models.base.PfValidationResult.ValidationResult;
/**
* This class is the base class for all models in the Policy Framework. All model classes inherit
@@ -56,7 +58,7 @@ import org.onap.policy.models.base.PfValidationResult.ValidationResult;
@Data
@EqualsAndHashCode(callSuper = false)
public abstract class PfModel extends PfConcept {
- private static final String IS_A_NULL_KEY = " is a null key";
+ private static final String KEYS_TOKEN = "keys";
private static final long serialVersionUID = -771659065637205430L;
@@ -110,15 +112,10 @@ public abstract class PfModel extends PfConcept {
}
@Override
- public PfValidationResult validate(@NonNull final PfValidationResult resultIn) {
- PfValidationResult result = resultIn;
+ public BeanValidationResult validate(@NonNull String fieldName) {
+ BeanValidationResult result = new BeanValidationResult(fieldName, this);
- if (key.isNullKey()) {
- result.addValidationMessage(
- new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key is a null key"));
- }
-
- result = key.validate(result);
+ result.addResult(validateKeyNotNull("key", key));
// Key consistency check
final Set<PfConceptKey> artifactKeySet = new TreeSet<>();
@@ -128,9 +125,9 @@ public abstract class PfModel extends PfConcept {
for (final PfKey pfKey : this.getKeys()) {
// Check for the two type of keys we have
if (pfKey instanceof PfConceptKey) {
- result = validateArtifactKeyInModel((PfConceptKey) pfKey, artifactKeySet, result);
+ validateArtifactKeyInModel((PfConceptKey) pfKey, artifactKeySet, result);
} else if (pfKey instanceof PfReferenceKey) {
- result = validateReferenceKeyInModel((PfReferenceKey) pfKey, referenceKeySet, result);
+ validateReferenceKeyInModel((PfReferenceKey) pfKey, referenceKeySet, result);
} else {
// It must be a PfKeyUse, nothing else is legal
usedKeySet.add((PfKeyUse) pfKey);
@@ -140,12 +137,11 @@ public abstract class PfModel extends PfConcept {
// Check all reference keys have correct parent keys
for (final PfReferenceKey referenceKey : referenceKeySet) {
if (!artifactKeySet.contains(referenceKey.getParentConceptKey())) {
- result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID,
- "parent artifact key not found for reference key " + referenceKey));
+ addResult(result, "reference key", referenceKey, "parent artifact key not found");
}
}
- result = validateKeyUses(usedKeySet, artifactKeySet, referenceKeySet, result);
+ validateKeyUses(usedKeySet, artifactKeySet, referenceKeySet, result);
return result;
}
@@ -156,78 +152,69 @@ public abstract class PfModel extends PfConcept {
* @param artifactKey The artifact key to check
* @param artifactKeySet The set of artifact keys encountered so far, this key is appended to
* the set
- * @param result The validation result to append to
- * @return the result of the validation
+ * @param result where to add the results
*/
- private PfValidationResult validateArtifactKeyInModel(final PfConceptKey artifactKey,
- final Set<PfConceptKey> artifactKeySet, final PfValidationResult result) {
- // Null key check
- if (artifactKey.isNullKey()) {
- result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID,
- "key " + artifactKey + IS_A_NULL_KEY));
- }
+ private void validateArtifactKeyInModel(final PfConceptKey artifactKey,
+ final Set<PfConceptKey> artifactKeySet, final BeanValidationResult result) {
+
+ result.addResult(validateKeyNotNull(KEYS_TOKEN, artifactKey));
+
+ BeanValidationResult result2 = new BeanValidationResult(KEYS_TOKEN, artifactKey);
// Null key name start check
if (artifactKey.getName().toUpperCase().startsWith(PfKey.NULL_KEY_NAME)) {
- result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID,
- "key " + artifactKey + " name starts with keyword " + PfKey.NULL_KEY_NAME));
+ addResult(result2, "name of " + artifactKey.getId(), artifactKey.getName(),
+ "starts with keyword " + PfKey.NULL_KEY_NAME);
}
// Unique key check
if (artifactKeySet.contains(artifactKey)) {
- result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID,
- "duplicate key " + artifactKey + " found"));
+ addResult(result, KEYS_TOKEN, artifactKey, "duplicate key");
} else {
artifactKeySet.add(artifactKey);
}
-
- return result;
}
/**
* Check for consistent usage of a reference key in the model.
*
- * @param artifactKey The reference key to check
+ * @param referenceKey The reference key to check
* @param referenceKeySet The set of reference keys encountered so far, this key is appended to
* the set
- * @param result The validation result to append to
- * @return the result of the validation
+ * @param result where to add the results
*/
- private PfValidationResult validateReferenceKeyInModel(final PfReferenceKey referenceKey,
- final Set<PfReferenceKey> referenceKeySet, final PfValidationResult result) {
+ private void validateReferenceKeyInModel(final PfReferenceKey referenceKey,
+ final Set<PfReferenceKey> referenceKeySet, final BeanValidationResult result) {
// Null key check
if (referenceKey.isNullKey()) {
- result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID,
- "key " + referenceKey + IS_A_NULL_KEY));
+ addResult(result, KEYS_TOKEN, referenceKey, IS_A_NULL_KEY);
}
+ BeanValidationResult result2 = new BeanValidationResult(KEYS_TOKEN, referenceKey);
+
// Null parent key check
if (referenceKey.getParentConceptKey().isNullKey()) {
- result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID,
- "parent artifact key of key " + referenceKey + IS_A_NULL_KEY));
+ addResult(result2, "parent key of " + referenceKey.getId(), referenceKey.getParentConceptKey().getId(),
+ IS_A_NULL_KEY);
}
// Null local name check
if (referenceKey.getLocalName().equals(PfKey.NULL_KEY_NAME)) {
- result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID,
- "key " + referenceKey + " has a null local name"));
+ addResult(result2, "local name of " + referenceKey.getId(), referenceKey.getLocalName(), IS_NULL);
}
// Null key name start check
if (referenceKey.getParentConceptKey().getName().toUpperCase().startsWith(PfKey.NULL_KEY_NAME)) {
- result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID,
- "key " + referenceKey + " parent name starts with keyword " + PfKey.NULL_KEY_NAME));
+ addResult(result2, "parent name of " + referenceKey.getId(), referenceKey.getParentConceptKey().getName(),
+ "starts with keyword " + PfKey.NULL_KEY_NAME);
}
// Unique key check
if (referenceKeySet.contains(referenceKey)) {
- result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID,
- "duplicate key " + referenceKey + " found"));
+ addResult(result, KEYS_TOKEN, referenceKey, "duplicate key");
} else {
referenceKeySet.add(referenceKey);
}
-
- return result;
}
/**
@@ -238,29 +225,26 @@ public abstract class PfModel extends PfConcept {
* the set
* @param referenceKeySet The set of reference keys encountered so far, this key is appended to
* the set
- * @param result The validation result to append to
- * @return the result of the validation
+ * @param result where to add the results
*/
- private PfValidationResult validateKeyUses(final Set<PfKeyUse> usedKeySet, final Set<PfConceptKey> artifactKeySet,
- final Set<PfReferenceKey> referenceKeySet, final PfValidationResult result) {
+ private void validateKeyUses(final Set<PfKeyUse> usedKeySet, final Set<PfConceptKey> artifactKeySet,
+ final Set<PfReferenceKey> referenceKeySet, final BeanValidationResult result) {
// Check all key uses
for (final PfKeyUse usedKey : usedKeySet) {
if (usedKey.getKey() instanceof PfConceptKey) {
// PfConceptKey usage, check the key exists
if (!artifactKeySet.contains(usedKey.getKey())) {
- result.addValidationMessage(new PfValidationMessage(usedKey.getKey(), this.getClass(),
- ValidationResult.INVALID, "an artifact key used in the model is not defined"));
+ result.addResult(new ObjectValidationResult("artifact key", usedKey.getId(),
+ ValidationStatus.INVALID, NOT_DEFINED));
}
} else {
// PfReferenceKey usage, check the key exists
if (!referenceKeySet.contains(usedKey.getKey())) {
- result.addValidationMessage(new PfValidationMessage(usedKey.getKey(), this.getClass(),
- ValidationResult.INVALID, "a reference key used in the model is not defined"));
+ result.addResult(new ObjectValidationResult("reference key", usedKey.getId(),
+ ValidationStatus.INVALID, NOT_DEFINED));
}
}
}
-
- return result;
}
@Override
diff --git a/models-base/src/main/java/org/onap/policy/models/base/PfReferenceKey.java b/models-base/src/main/java/org/onap/policy/models/base/PfReferenceKey.java
index 7984e4297..83403ac43 100644
--- a/models-base/src/main/java/org/onap/policy/models/base/PfReferenceKey.java
+++ b/models-base/src/main/java/org/onap/policy/models/base/PfReferenceKey.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
- * 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.
@@ -28,8 +28,9 @@ import javax.persistence.Embeddable;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NonNull;
+import org.onap.policy.common.parameters.BeanValidationResult;
+import org.onap.policy.common.parameters.ValidationResult;
import org.onap.policy.common.utils.validation.Assertions;
-import org.onap.policy.models.base.PfValidationResult.ValidationResult;
/**
* A reference key identifies entities in the system that are contained in other entities. Every contained concept in
@@ -339,34 +340,13 @@ public class PfReferenceKey extends PfKey {
}
@Override
- public PfValidationResult validate(final PfValidationResult result) {
- final String parentNameValidationErrorMessage = Assertions.getStringParameterValidationMessage(PARENT_KEY_NAME,
- parentKeyName, NAME_REGEXP);
- if (parentNameValidationErrorMessage != null) {
- result.addValidationMessage(new PfValidationMessage(this, this.getClass(), ValidationResult.INVALID,
- "parentKeyName invalid-" + parentNameValidationErrorMessage));
- }
-
- final String parentKeyVersionValidationErrorMessage = Assertions
- .getStringParameterValidationMessage(PARENT_KEY_VERSION, parentKeyVersion, VERSION_REGEXP);
- if (parentKeyVersionValidationErrorMessage != null) {
- result.addValidationMessage(new PfValidationMessage(this, this.getClass(), ValidationResult.INVALID,
- "parentKeyVersion invalid-" + parentKeyVersionValidationErrorMessage));
- }
+ public ValidationResult validate(@NonNull String fieldName) {
+ BeanValidationResult result = new BeanValidationResult(fieldName, this);
- final String parentLocalNameValidationErrorMessage = Assertions
- .getStringParameterValidationMessage(PARENT_LOCAL_NAME, parentLocalName, LOCAL_NAME_REGEXP);
- if (parentLocalNameValidationErrorMessage != null) {
- result.addValidationMessage(new PfValidationMessage(this, this.getClass(), ValidationResult.INVALID,
- "parentLocalName invalid-" + parentLocalNameValidationErrorMessage));
- }
-
- final String localNameValidationErrorMessage = Assertions.getStringParameterValidationMessage(LOCAL_NAME,
- localName, LOCAL_NAME_REGEXP);
- if (localNameValidationErrorMessage != null) {
- result.addValidationMessage(new PfValidationMessage(this, this.getClass(), ValidationResult.INVALID,
- "localName invalid-" + localNameValidationErrorMessage));
- }
+ result.addResult(validateRegex(PARENT_KEY_NAME, parentKeyName, NAME_REGEXP));
+ result.addResult(validateRegex(PARENT_KEY_VERSION, parentKeyVersion, VERSION_REGEXP));
+ result.addResult(validateRegex(PARENT_LOCAL_NAME, parentLocalName, LOCAL_NAME_REGEXP));
+ result.addResult(validateRegex(LOCAL_NAME, localName, LOCAL_NAME_REGEXP));
return result;
}
diff --git a/models-base/src/main/java/org/onap/policy/models/base/PfValidationMessage.java b/models-base/src/main/java/org/onap/policy/models/base/PfValidationMessage.java
deleted file mode 100644
index cd8b08bfa..000000000
--- a/models-base/src/main/java/org/onap/policy/models/base/PfValidationMessage.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
- * 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.models.base;
-
-import org.onap.policy.common.utils.validation.Assertions;
-import org.onap.policy.models.base.PfValidationResult.ValidationResult;
-
-/**
- * A validation message is created for each validation observation observed during validation of a
- * concept. The message holds the key and the class of the concept on which the observation was made
- * as well as the type of observation and a message describing the observation.
- */
-public class PfValidationMessage {
- private final PfKey observedKey;
- private ValidationResult validationResult = ValidationResult.VALID;
- private final String observedClass;
- private final String message;
-
- /**
- * Create an validation observation with the given fields.
- *
- * @param observedKey the key of the class on which the validation observation was made
- * @param observedClass the class on which the validation observation was made
- * @param validationResult the type of observation made
- * @param message a message describing the observation
- */
- public PfValidationMessage(final PfKey observedKey, final Class<?> observedClass,
- final ValidationResult validationResult, final String message) {
- Assertions.argumentNotNull(observedKey, "observedKey may not be null");
- Assertions.argumentNotNull(observedClass, "observedClass may not be null");
- Assertions.argumentNotNull(validationResult, "validationResult may not be null");
- Assertions.argumentNotNull(message, "message may not be null");
-
- this.observedKey = observedKey;
- this.observedClass = observedClass.getName();
- this.validationResult = validationResult;
- this.message = message;
- }
-
- /**
- * Gets the key of the observation.
- *
- * @return the key of the observation
- */
- public PfKey getObservedKey() {
- return observedKey;
- }
-
- /**
- * Gets the observed class.
- *
- * @return the observed class
- */
- public String getObservedClass() {
- return observedClass;
- }
-
- /**
- * Gets the type of observation made.
- *
- * @return the type of observation made
- */
- public ValidationResult getValidationResult() {
- return validationResult;
- }
-
- /**
- * Get a description of the observation.
- *
- * @return the observation description
- */
- public String getMessage() {
- return message;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.lang.Object#toString()
- */
- @Override
- public String toString() {
- return observedKey.toString() + ':' + observedClass + ':' + validationResult.name() + ':' + message;
- }
-}
diff --git a/models-base/src/main/java/org/onap/policy/models/base/PfValidationResult.java b/models-base/src/main/java/org/onap/policy/models/base/PfValidationResult.java
deleted file mode 100644
index bbac3b7e5..000000000
--- a/models-base/src/main/java/org/onap/policy/models/base/PfValidationResult.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019-2020 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.models.base;
-
-import java.util.LinkedList;
-import java.util.List;
-import lombok.Getter;
-
-/**
- * This class records the result of a validation and holds all validation observation messages.
- */
-@Getter
-public class PfValidationResult {
- /**
- * The ValidationResult enumeration describes the severity of a validation result.
- */
- public enum ValidationResult {
- /** No problems or observations were detected during validation. */
- VALID,
- /**
- * Observations were made on a concept (such as blank descriptions) of a nature that will not affect the use of
- * the concept.
- */
- OBSERVATION,
- /**
- * Warnings were made on a concept (such as defined but unused concepts) of a nature that may affect the use of
- * the concept.
- */
- WARNING,
- /**
- * Errors were detected on a concept (such as referenced but undefined concepts) of a nature that will affect
- * the use of the concept.
- */
- INVALID
- }
-
- // The actual verification result
- private ValidationResult validationResult = ValidationResult.VALID;
-
- // Messages collected during the verification process
- private final List<PfValidationMessage> messageList = new LinkedList<>();
-
- /**
- * Check if a validation reported a valid concept, returns true if the model is usable (that is, even if the model
- * has warnings or observations).
- *
- * @return true, if the concept is reported as valid and can be used
- */
- public boolean isValid() {
- return validationResult != ValidationResult.INVALID;
- }
-
- /**
- * Check if a validation reported a concept with no errors or warnings, returns true if the model is OK to use.
- *
- * @return true, if the concept has no warnings or errors
- */
- public boolean isOk() {
- return validationResult == ValidationResult.VALID || validationResult == ValidationResult.OBSERVATION;
- }
-
-
- /**
- * Append a validation result to another validation result.
- *
- * @param result2Append the result to append to the current validation result
- */
- public void append(final PfValidationResult result2Append) {
- for (PfValidationMessage message : result2Append.getMessageList()) {
- addValidationMessage(message);
- }
- }
-
- /**
- * Adds a validation message to the validation result, used by validate() implementations on {@link PfConcept}
- * subclasses to report validaiton observations.
- *
- * @param validationMessage the validation message
- */
- public void addValidationMessage(final PfValidationMessage validationMessage) {
- messageList.add(validationMessage);
-
- // Check if the incoming message has a more sever status than the
- // current one on the overall validation result,
- // if so, the overall result goes to that level
- if (validationMessage.getValidationResult().ordinal() > validationResult.ordinal()) {
- validationResult = validationMessage.getValidationResult();
- }
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.lang.Object#toString()
- */
- @Override
- public String toString() {
- final StringBuilder builder = new StringBuilder();
-
- switch (validationResult) {
- case VALID:
-
- builder.append("***validation of model successful***");
- return builder.toString();
- case OBSERVATION:
-
- builder.append("\n***observations noted during validation of model***\n");
- break;
- case WARNING:
-
- builder.append("\n***warnings issued during validation of model***\n");
- break;
- case INVALID:
- builder.append("\n***validation of model failed***\n");
- break;
- default:
- break;
- }
-
- for (final PfValidationMessage message : messageList) {
- builder.append(message);
- builder.append("\n");
- }
-
- builder.append("********************************");
- return builder.toString();
- }
-}
diff --git a/models-base/src/main/java/org/onap/policy/models/base/Validated.java b/models-base/src/main/java/org/onap/policy/models/base/Validated.java
index d79d58f13..b962d46ab 100644
--- a/models-base/src/main/java/org/onap/policy/models/base/Validated.java
+++ b/models-base/src/main/java/org/onap/policy/models/base/Validated.java
@@ -20,234 +20,343 @@
package org.onap.policy.models.base;
+import com.google.re2j.Pattern;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
+import java.util.function.BiFunction;
+import java.util.function.Function;
import lombok.NonNull;
-import org.onap.policy.common.utils.validation.Assertions;
-import org.onap.policy.models.base.PfValidationResult.ValidationResult;
+import org.apache.commons.lang3.StringUtils;
+import org.onap.policy.common.parameters.BeanValidationResult;
+import org.onap.policy.common.parameters.ObjectValidationResult;
+import org.onap.policy.common.parameters.ValidationResult;
+import org.onap.policy.common.parameters.ValidationStatus;
/**
* Classes that can be validated. This can be used as a super class or as a stand-alone
* utility class.
*/
-public class Validated {
+public abstract class Validated {
+ public static final String IS_BLANK = "is blank";
+ public static final String IS_A_NULL_KEY = "is a null key";
+ public static final String IS_NULL = "is null";
+ public static final String NOT_DEFINED = "not defined";
+ public static final String NOT_FOUND = "not found";
+
+ public static final String KEY_TOKEN = "key";
+ public static final String VALUE_TOKEN = "value";
+
+ /**
+ * Validates the fields of the object.
+ *
+ * @param fieldName name of the field containing this
+ * @return the result, or {@code null}
+ */
+ public abstract ValidationResult validate(String fieldName);
/**
- * Validates the fields of the object. The default method simply returns the result.
+ * Adds a result indicating that a value is invalid.
*
- * @param result where to place the result
- * @return the result
+ * @param result where to put the result
+ * @param fieldName name of the field containing the value
+ * @param value the field's value
+ * @param errorMessage the error message
*/
- public PfValidationResult validate(@NonNull PfValidationResult result) {
- return result;
+ public static void addResult(@NonNull BeanValidationResult result, @NonNull String fieldName, Object value,
+ @NonNull String errorMessage) {
+ result.addResult(
+ new ObjectValidationResult(fieldName, getKeyId(value), ValidationStatus.INVALID, errorMessage));
}
/**
- * Validates that a field value is not null.
+ * Makes a result that indicates a value is invalid, because it is null.
*
- * @param container the object that contains the field
- * @param fieldName name of the field to be validated
- * @param value value to be validated
- * @param result where to place the result
- * @return the result
+ * @param fieldName name of the field containing the value
+ * @param value the field's value
+ * @return a result indicating the value is invalid
*/
- public PfValidationResult validateNotNull(@NonNull Object container, @NonNull String fieldName, Object value,
- @NonNull PfValidationResult result) {
+ public static ValidationResult makeNullResult(@NonNull String fieldName, Object value) {
+ return new ObjectValidationResult(fieldName, getKeyId(value), ValidationStatus.INVALID, IS_NULL);
+ }
+ /**
+ * Validates a value, if is not {@code null}, by invoking it's validate() method.
+ *
+ * @param result where to put the result
+ * @param fieldName name of the field containing the value
+ * @param value the field's value
+ */
+ public static void validateOptional(@NonNull BeanValidationResult result, @NonNull String fieldName,
+ Validated value) {
+ if (value != null) {
+ result.addResult(value.validate(fieldName));
+ }
+ }
+
+ /**
+ * Validates that a value is not {@code null}. If the value is a subclass of this
+ * class, then it's {@link #validate(String)} method is invoked, too.
+ *
+ * @param fieldName name of the field containing the value
+ * @param value the field's value
+ * @return a result, or {@code null}
+ */
+ public static ValidationResult validateNotNull(@NonNull String fieldName, Object value) {
if (value == null) {
- addError(container, fieldName, result, "null");
+ return new ObjectValidationResult(fieldName, value, ValidationStatus.INVALID, IS_NULL);
+ }
+
+ if (value instanceof Validated) {
+ return ((Validated) value).validate(fieldName);
}
- return result;
+ return null;
}
/**
- * Validates that the name and version of a concept key do not have the null default
- * values.
+ * Validates that a value is not "blank" (i.e., empty). value.
*
- * @param value value to be validated
- * @param result where to place the result
- * @return the result
+ * @param fieldName name of the field containing the value
+ * @param value the field's value
+ * @param checkNull {@code true} if to validate that the value is not {@code null}
+ * @return a result, or {@code null}
*/
- public PfValidationResult validateNotNull(@NonNull PfConceptKey value, @NonNull PfValidationResult result) {
-
- if (PfKey.NULL_KEY_NAME.equals(value.getName())) {
- addError(value, "name", result, "null");
+ public static ValidationResult validateNotBlank(@NonNull String fieldName, String value, boolean checkNull) {
+ if (value == null && !checkNull) {
+ return null;
}
- if (PfKey.NULL_KEY_VERSION.equals(value.getVersion())) {
- addError(value, "version", result, "null");
+ if (StringUtils.isBlank(value)) {
+ return new ObjectValidationResult(fieldName, value, ValidationStatus.INVALID, IS_BLANK);
}
- return result;
+ return null;
}
/**
- * Validates the contents of a field, verifying that it matches a pattern, if it is
- * non-null.
+ * Validates that a value matches regular expression.
*
- * @param container the object that contains the field
- * @param fieldName name of the field to be validated
- * @param value value to be validated
- * @param pattern pattern used to validate the value
- * @param result where to place the result
- * @return the result
+ * @param fieldName name of the field containing the value
+ * @param value the field's value
+ * @param pattern regular expression to be matched
+ * @return a result, or {@code null}
*/
- public PfValidationResult validateText(@NonNull Object container, @NonNull String fieldName, String value,
- @NonNull String pattern, @NonNull PfValidationResult result) {
+ public static ValidationResult validateRegex(@NonNull String fieldName, String value, @NonNull String pattern) {
+ if (value == null) {
+ return makeNullResult(fieldName, value);
+ }
- if (value != null) {
- addError(container, fieldName, result,
- Assertions.getStringParameterValidationMessage(fieldName, value, pattern));
+ if (!Pattern.matches(pattern, value)) {
+ return new ObjectValidationResult(fieldName, value, ValidationStatus.INVALID,
+ "does not match regular expression " + pattern);
}
- return result;
+ return null;
}
/**
- * Validates the contents of a property field, verifying that the keys ands values are
- * non-null.
+ * Validates a key, ensuring that it isn't null and that it's structurally sound.
*
- * @param container the object that contains the field
- * @param fieldName name of the field to be validated
- * @param properties properties to be validated
- * @param resultIn where to place the result
- * @return the result
+ * @param fieldName name of the field containing the key
+ * @param key the field's value
+ * @return a result, or {@code null}
*/
- public <T> PfValidationResult validatePropertiesNotNull(@NonNull Object container, @NonNull String fieldName,
- Map<String, T> properties, @NonNull PfValidationResult resultIn) {
+ public static ValidationResult validateKeyNotNull(@NonNull String fieldName, PfKey key) {
+ if (key == null) {
+ return new ObjectValidationResult(fieldName, key, ValidationStatus.INVALID, IS_A_NULL_KEY);
+ }
+
+ if (key.isNullKey()) {
+ return new ObjectValidationResult(fieldName, key.getId(), ValidationStatus.INVALID, IS_A_NULL_KEY);
+ }
- PfValidationResult result = resultIn;
+ return key.validate(fieldName);
+ }
- if (properties == null) {
+ /**
+ * Validates a key's version, ensuring that it isn't null.
+ *
+ * @param fieldName name of the field containing the key
+ * @param key the field's value
+ * @return a result, or {@code null}
+ */
+ public static BeanValidationResult validateKeyVersionNotNull(@NonNull String fieldName, PfConceptKey key) {
+ if (key != null && key.isNullVersion()) {
+ BeanValidationResult result = new BeanValidationResult(fieldName, key);
+ result.addResult(makeNullResult(PfKeyImpl.VERSION_TOKEN, key.getVersion()));
return result;
}
- for (Entry<String, T> ent : properties.entrySet()) {
- String key = ent.getKey();
- String keyName = fieldName + "." + key;
- result = validateNotNull(container, keyName, key, result);
+ return null;
+ }
+
+ /**
+ * Generates a function to validate that a value is not below a minimum.
+ *
+ * @param min minimum value allowed
+ * @param allowedValue {@code null} or an allowed value outside the range
+ * @param checkRef {@code true} to generate an error if the value is {@code null}
+ * @return a function to validate that a value is not below a minimum
+ */
+ public static BiFunction<String, Integer, ValidationResult> validateMin(int min, Integer allowedValue,
+ boolean checkRef) {
+ return (name, value) -> validateMin(name, value, min, allowedValue, checkRef);
+ }
+
+ /**
+ * Validates that a value is not below a minimum.
+ *
+ * @param fieldName name of the field containing the key
+ * @param value the field's value
+ * @param min minimum value allowed
+ * @param allowedValue {@code null} or an allowed value outside the range
+ * @param checkRef {@code true} to generate an error if the value is {@code null}
+ * @return a result, or {@code null}
+ */
+ public static ValidationResult validateMin(@NonNull String fieldName, Integer value, int min, Integer allowedValue,
+ boolean checkRef) {
+ if (value == null) {
+ if (checkRef) {
+ return makeNullResult(fieldName, value);
+ }
+
+ return null;
+ }
- result = validateNotNull(container, keyName, ent.getValue(), result);
+ if (value < min && !value.equals(allowedValue)) {
+ return new ObjectValidationResult(fieldName, value, ValidationStatus.INVALID,
+ "is below the minimum value: " + min);
}
- return result;
+ return null;
}
/**
- * Validates the items in a collection field are non-null.
+ * Validates the items in a list.
*
- * @param container the object that contains the field
- * @param fieldName name of the field to be validated
- * @param collection collection whose items are to be validated
- * @param resultIn where to place the result
- * @return the result
+ * @param result where to add the results
+ * @param fieldName name of the field containing the list
+ * @param list the field's list (may be {@code null})
+ * @param checker function to validate in individual item in the list
*/
- public <T> PfValidationResult validateCollectionNotNull(@NonNull Object container, @NonNull String fieldName,
- Collection<T> collection, @NonNull PfValidationResult resultIn) {
+ public static <T> void validateList(@NonNull BeanValidationResult result, @NonNull String fieldName,
+ Collection<T> list, @NonNull BiFunction<String, T, ValidationResult> checker) {
+ if (list == null) {
+ return;
+ }
- PfValidationResult result = resultIn;
+ BeanValidationResult result2 = new BeanValidationResult(fieldName, list);
- if (collection == null) {
- return result;
+ int count = 0;
+ for (T value : list) {
+ result2.addResult(checker.apply(String.valueOf(count++), value));
}
- String prefix = fieldName + ".";
- int count = 0;
+ if (!result2.isClean()) {
+ result.addResult(result2);
+ }
+ }
+
+ /**
+ * Validates the items in a map.
+ *
+ * @param result where to add the results
+ * @param fieldName name of the field containing the list
+ * @param map the field's map (may be {@code null})
+ * @param checker function to validate in individual item in the list
+ */
+ public static <T> void validateMap(@NonNull BeanValidationResult result, @NonNull String fieldName,
+ Map<String, T> map, @NonNull Function<Map.Entry<String, T>, ValidationResult> checker) {
+ if (map == null) {
+ return;
+ }
- for (T item : collection) {
- result = validateNotNull(container, prefix + count, item, result);
- ++count;
+ BeanValidationResult result2 = new BeanValidationResult(fieldName, map);
+
+ for (Entry<String, T> entry : map.entrySet()) {
+ result2.addResult(checker.apply(entry));
}
- return result;
+ if (!result2.isClean()) {
+ result.addResult(result2);
+ }
}
/**
- * Invokes the "validate()" method on each item in a collection field, if the item is
- * non-null.
+ * Validates a Map entry, ensuring that neither the key nor the value are "blank"
+ * (i.e., empty or {@code null}).
*
- * @param container the object that contains the field
- * @param fieldName name of the field to be validated
- * @param collection collection whose items are to be validated
- * @param result where to place the result
- * @return the result
+ * @param entry entry to be validated
+ * @return a result, or {@code null}
*/
- public <T extends Validated> PfValidationResult validateCollection(@NonNull Object container,
- @NonNull String fieldName, Collection<T> collection, @NonNull PfValidationResult result) {
+ public static BeanValidationResult validateEntryNotBlankNotBlank(Map.Entry<String, String> entry) {
+ BeanValidationResult result = new BeanValidationResult("" + entry.getKey(), entry.getKey());
- if (collection == null) {
- return result;
+ if (StringUtils.isBlank(entry.getKey())) {
+ Validated.addResult(result, KEY_TOKEN, entry.getKey(), IS_BLANK);
}
- for (T item : collection) {
- if (item != null) {
- result = item.validate(result);
- }
+ if (StringUtils.isBlank(entry.getValue())) {
+ Validated.addResult(result, VALUE_TOKEN, entry.getValue(), IS_BLANK);
}
- return result;
+ return (result.isClean() ? null : result);
}
/**
- * Invokes the "validate()" method on each item in a concept collection field, if the
- * item is non-null.
+ * Validates a Map entry, ensuring that the key is not "blank" (i.e., empty or
+ * {@code null}) and the value is not {@code null}.
*
- * @param container the object that contains the field
- * @param fieldName name of the field to be validated
- * @param collection collection whose items are to be validated
- * @param result where to place the result
- * @return the result
+ * @param entry entry to be validated
+ * @return a result, or {@code null}
*/
- public <T extends PfConcept> PfValidationResult validateConceptCollection(@NonNull Object container,
- @NonNull String fieldName, Collection<T> collection, @NonNull PfValidationResult result) {
+ public static BeanValidationResult validateEntryNotBlankNotNull(Map.Entry<String, String> entry) {
+ BeanValidationResult result = new BeanValidationResult("" + entry.getKey(), entry.getKey());
- if (collection == null) {
- return result;
+ if (StringUtils.isBlank(entry.getKey())) {
+ Validated.addResult(result, KEY_TOKEN, entry.getKey(), IS_BLANK);
}
- for (T item : collection) {
- if (item != null) {
- result = item.validate(result);
- }
+ if (entry.getValue() == null) {
+ result.addResult(makeNullResult(VALUE_TOKEN, entry.getValue()));
}
- return result;
+ return (result.isClean() ? null : result);
}
/**
- * Adds an error message to the validation result.
+ * Validates a Map entry, ensuring that neither the key nor the value are
+ * {@code null}. If the value is a subclass of this class, then it's
+ * {@link #validate(String)} method is invoked.
*
- * @param container the object that contains the field
- * @param fieldName name of the field to be validated
- * @param result where to place the result
- * @param errmsg the error message to be added, or {@code null} if nothing to add
+ * @param entry entry to be validated
+ * @return a result, or {@code null}
*/
- public void addError(@NonNull Object container, @NonNull String fieldName, @NonNull PfValidationResult result,
- String errmsg) {
- if (errmsg != null) {
- result.addValidationMessage(new PfValidationMessage(makeKey(container), container.getClass(),
- ValidationResult.INVALID, fieldName + " invalid-" + errmsg));
+ public static <V> BeanValidationResult validateEntryValueNotNull(Map.Entry<String, V> entry) {
+ BeanValidationResult result = new BeanValidationResult("" + entry.getKey(), entry.getKey());
+
+ if (entry.getKey() == null) {
+ result.addResult(makeNullResult(KEY_TOKEN, entry.getKey()));
+ }
+
+ V value = entry.getValue();
+ if (value == null) {
+ result.addResult(makeNullResult(VALUE_TOKEN, value));
+ } else if (value instanceof Validated) {
+ result.addResult(((Validated) value).validate(VALUE_TOKEN));
}
+
+ return (result.isClean() ? null : result);
}
/**
- * Makes a PfKey suitable for insertion into a validation message. Note: the
- * "toString()" method of the key simply invokes container.toString();
+ * Gets a key's ID, if the value is a {@link PfKey}.
*
- * @param container the container object for which the key should be made
- * @return a key for the container
+ * @param value value from which to get the ID
+ * @return the value's ID, if it's a key, the original value otherwise
*/
- public PfKey makeKey(@NonNull Object container) {
-
- return new PfConceptKey() {
- private static final long serialVersionUID = 1L;
-
- @Override
- public String toString() {
- return container.toString();
- }
- };
+ private static Object getKeyId(Object value) {
+ return (value instanceof PfKey ? ((PfKey) value).getId() : value);
}
}
diff --git a/models-base/src/test/java/org/onap/policy/models/base/PfConceptContainerTest.java b/models-base/src/test/java/org/onap/policy/models/base/PfConceptContainerTest.java
index 062f6f953..8c74850d2 100644
--- a/models-base/src/test/java/org/onap/policy/models/base/PfConceptContainerTest.java
+++ b/models-base/src/test/java/org/onap/policy/models/base/PfConceptContainerTest.java
@@ -21,6 +21,7 @@
package org.onap.policy.models.base;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -111,9 +112,7 @@ public class PfConceptContainerTest {
container.clean();
assertEquals(clonedContainer, container);
- PfValidationResult result = new PfValidationResult();
- result = container.validate(result);
- assertTrue(result.isOk());
+ assertThat(container.validate("").getResult()).isNull();
assertEquals(0, container.compareTo(clonedContainer));
@@ -136,30 +135,30 @@ public class PfConceptContainerTest {
final DummyPfConceptContainer container3 = container;
assertThatThrownBy(() -> container3.validate(null))
- .hasMessageMatching("^resultIn is marked .*on.*ull but is null$");
+ .hasMessageMatching("^fieldName is marked .*on.*ull but is null$");
DummyPfConceptContainer validateContainer = new DummyPfConceptContainer();
- assertFalse(validateContainer.validate(new PfValidationResult()).isOk());
+ assertFalse(validateContainer.validate("").isValid());
validateContainer.setKey(new PfConceptKey("VCKey", VERSION0_0_1));
- assertTrue(validateContainer.validate(new PfValidationResult()).isOk());
+ assertTrue(validateContainer.validate("").isValid());
validateContainer.getConceptMap().put(testConceptKey, new DummyPfConcept(testConceptKey));
- assertTrue(validateContainer.validate(new PfValidationResult()).isOk());
+ assertTrue(validateContainer.validate("").isValid());
validateContainer.getConceptMap().put(PfConceptKey.getNullKey(), new DummyPfConcept(PfConceptKey.getNullKey()));
- assertFalse(validateContainer.validate(new PfValidationResult()).isOk());
+ assertFalse(validateContainer.validate("").isValid());
validateContainer.getConceptMap().remove(PfConceptKey.getNullKey());
- assertTrue(validateContainer.validate(new PfValidationResult()).isOk());
+ assertTrue(validateContainer.validate("").isValid());
validateContainer.getConceptMap().put(testConceptKey, null);
- assertFalse(validateContainer.validate(new PfValidationResult()).isOk());
+ assertFalse(validateContainer.validate("").isValid());
validateContainer.getConceptMap().put(testConceptKey, new DummyPfConcept(testConceptKey));
- assertTrue(validateContainer.validate(new PfValidationResult()).isOk());
+ assertTrue(validateContainer.validate("").isValid());
validateContainer.getConceptMap().put(testConceptKey, new DummyPfConcept(conceptKey));
- assertFalse(validateContainer.validate(new PfValidationResult()).isOk());
+ assertFalse(validateContainer.validate("").isValid());
validateContainer.getConceptMap().put(testConceptKey, new DummyPfConcept(testConceptKey));
- assertTrue(validateContainer.validate(new PfValidationResult()).isOk());
+ assertTrue(validateContainer.validate("").isValid());
assertEquals(conceptKey, container.get(conceptKey).getKey());
assertEquals(conceptKey, container.get(conceptKey.getName()).getKey());
diff --git a/models-base/src/test/java/org/onap/policy/models/base/PfKeyImplTest.java b/models-base/src/test/java/org/onap/policy/models/base/PfKeyImplTest.java
index 8b94a48c3..8d6b1b9f4 100644
--- a/models-base/src/test/java/org/onap/policy/models/base/PfKeyImplTest.java
+++ b/models-base/src/test/java/org/onap/policy/models/base/PfKeyImplTest.java
@@ -21,6 +21,7 @@
package org.onap.policy.models.base;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
@@ -35,6 +36,7 @@ import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.junit.Test;
+import org.onap.policy.common.parameters.ValidationResult;
import org.onap.policy.models.base.PfKey.Compatibility;
import org.onap.policy.models.base.testconcepts.DummyPfKey;
@@ -109,20 +111,13 @@ public class PfKeyImplTest {
assertFalse(someKey1.isCompatible(someKey5));
assertFalse(someKey1.isCompatible(new DummyPfKey()));
- assertEquals(PfValidationResult.ValidationResult.VALID,
- someKey0.validate(new PfValidationResult()).getValidationResult());
- assertEquals(PfValidationResult.ValidationResult.VALID,
- someKey1.validate(new PfValidationResult()).getValidationResult());
- assertEquals(PfValidationResult.ValidationResult.VALID,
- someKey2.validate(new PfValidationResult()).getValidationResult());
- assertEquals(PfValidationResult.ValidationResult.VALID,
- someKey3.validate(new PfValidationResult()).getValidationResult());
- assertEquals(PfValidationResult.ValidationResult.VALID,
- someKey4.validate(new PfValidationResult()).getValidationResult());
- assertEquals(PfValidationResult.ValidationResult.VALID,
- someKey5.validate(new PfValidationResult()).getValidationResult());
- assertEquals(PfValidationResult.ValidationResult.VALID,
- someKey6.validate(new PfValidationResult()).getValidationResult());
+ assertTrue(someKey0.validate("").isValid());
+ assertTrue(someKey1.validate("").isValid());
+ assertTrue(someKey2.validate("").isValid());
+ assertTrue(someKey3.validate("").isValid());
+ assertTrue(someKey4.validate("").isValid());
+ assertTrue(someKey5.validate("").isValid());
+ assertTrue(someKey6.validate("").isValid());
someKey0.clean();
assertNotNull(someKey0.toString());
@@ -179,22 +174,20 @@ public class PfKeyImplTest {
Field nameField = testKey.getClass().getDeclaredField("name");
nameField.setAccessible(true);
nameField.set(testKey, "Key Name");
- PfValidationResult validationResult = new PfValidationResult();
- testKey.validate(validationResult);
+ ValidationResult validationResult = testKey.validate("");
nameField.set(testKey, "TheKey");
nameField.setAccessible(false);
- assertEquals("name invalid-parameter name with value Key Name " + "does not match regular expression "
- + PfKey.NAME_REGEXP, validationResult.getMessageList().get(0).getMessage());
+ assertThat(validationResult.getResult()).contains("\"name\"").doesNotContain("\"version\"")
+ .contains("does not match regular expression " + PfKey.NAME_REGEXP);
Field versionField = testKey.getClass().getDeclaredField("version");
versionField.setAccessible(true);
versionField.set(testKey, "Key Version");
- PfValidationResult validationResult2 = new PfValidationResult();
- testKey.validate(validationResult2);
+ ValidationResult validationResult2 = testKey.validate("");
versionField.set(testKey, VERSION001);
versionField.setAccessible(false);
- assertEquals("version invalid-parameter version with value Key Version " + "does not match regular expression "
- + PfKey.VERSION_REGEXP, validationResult2.getMessageList().get(0).getMessage());
+ assertThat(validationResult2.getResult()).doesNotContain("\"name\"").contains("\"version\"")
+ .contains("does not match regular expression " + PfKey.VERSION_REGEXP);
}
@Test
diff --git a/models-base/src/test/java/org/onap/policy/models/base/PfKeyUseTest.java b/models-base/src/test/java/org/onap/policy/models/base/PfKeyUseTest.java
index f9ad889c7..d2aebdc43 100644
--- a/models-base/src/test/java/org/onap/policy/models/base/PfKeyUseTest.java
+++ b/models-base/src/test/java/org/onap/policy/models/base/PfKeyUseTest.java
@@ -62,9 +62,7 @@ public class PfKeyUseTest {
keyUse.clean();
assertNotNull(keyUse);
- PfValidationResult result = new PfValidationResult();
- result = keyUse.validate(result);
- assertNotNull(result);
+ assertNotNull(keyUse.validate(""));
assertNotEquals(0, keyUse.hashCode());
@@ -84,8 +82,7 @@ public class PfKeyUseTest {
assertEquals(0, keyUse.compareTo(new PfKeyUse(key)));
PfKeyUse keyUseNull = new PfKeyUse(PfConceptKey.getNullKey());
- PfValidationResult resultNull = new PfValidationResult();
- assertEquals(false, keyUseNull.validate(resultNull).isValid());
+ assertEquals(false, keyUseNull.validate("").isValid());
assertThatThrownBy(() -> keyUse.setKey(null)).hasMessageMatching("^key is marked .*on.*ull but is null$");
@@ -93,7 +90,8 @@ public class PfKeyUseTest {
assertThatThrownBy(() -> keyUse.isCompatible(null)).hasMessageMatching(OTHER_KEY_IS_NULL);
- assertThatThrownBy(() -> keyUse.validate(null)).hasMessageMatching("^result is marked .*on.*ull but is null$");
+ assertThatThrownBy(() -> keyUse.validate(null))
+ .hasMessageMatching("^fieldName is marked .*on.*ull but is null$");
PfKeyUse testKeyUse = new PfKeyUse(new DummyPfConceptKeySub(new PfConceptKey()));
assertEquals(testKeyUse, new PfKeyUse(testKeyUse));
diff --git a/models-base/src/test/java/org/onap/policy/models/base/PfModelTest.java b/models-base/src/test/java/org/onap/policy/models/base/PfModelTest.java
index 9e4e350a1..760231a7c 100644
--- a/models-base/src/test/java/org/onap/policy/models/base/PfModelTest.java
+++ b/models-base/src/test/java/org/onap/policy/models/base/PfModelTest.java
@@ -73,59 +73,59 @@ public class PfModelTest {
public void testPfModelValidation() {
PfConceptKey dpmKey = new PfConceptKey("modelKey", VERSION001);
DummyPfModel dpm = new DummyPfModel(dpmKey);
- assertTrue(dpm.validate(new PfValidationResult()).isValid());
+ assertTrue(dpm.validate("").isValid());
- assertThatThrownBy(() -> dpm.validate(null)).hasMessageMatching("^resultIn is marked .*on.*ull but is null$");
+ assertThatThrownBy(() -> dpm.validate(null)).hasMessageMatching("^fieldName is marked .*on.*ull but is null$");
dpm.setKey(PfConceptKey.getNullKey());
- assertFalse(dpm.validate(new PfValidationResult()).isValid());
+ assertFalse(dpm.validate("").isValid());
dpm.setKey(dpmKey);
- assertTrue(dpm.validate(new PfValidationResult()).isValid());
+ assertTrue(dpm.validate("").isValid());
dpm.getKeyList().add(PfReferenceKey.getNullKey());
dpm.getKeyList().add(new PfKeyUse(PfReferenceKey.getNullKey()));
- assertFalse(dpm.validate(new PfValidationResult()).isValid());
+ assertFalse(dpm.validate("").isValid());
dpm.getKeyList().clear();
- assertTrue(dpm.validate(new PfValidationResult()).isValid());
+ assertTrue(dpm.validate("").isValid());
PfConceptKey goodCKey = new PfConceptKey("goodCKey", VERSION001);
PfReferenceKey goodRKey = new PfReferenceKey(goodCKey, "goodLocalName");
dpm.getKeyList().add(goodCKey);
dpm.getKeyList().add(goodRKey);
- assertTrue(dpm.validate(new PfValidationResult()).isValid());
+ assertTrue(dpm.validate("").isValid());
PfConceptKey goodCKeyDup = new PfConceptKey(goodCKey);
dpm.getKeyList().add(goodCKeyDup);
- assertFalse(dpm.validate(new PfValidationResult()).isValid());
+ assertFalse(dpm.validate("").isValid());
dpm.getKeyList().remove(goodCKeyDup);
- assertTrue(dpm.validate(new PfValidationResult()).isValid());
+ assertTrue(dpm.validate("").isValid());
PfReferenceKey goodRKeyDup = new PfReferenceKey(goodRKey);
dpm.getKeyList().add(goodRKeyDup);
- assertFalse(dpm.validate(new PfValidationResult()).isValid());
+ assertFalse(dpm.validate("").isValid());
dpm.getKeyList().remove(goodRKeyDup);
- assertTrue(dpm.validate(new PfValidationResult()).isValid());
+ assertTrue(dpm.validate("").isValid());
PfKeyUse goodCKeyUse = new PfKeyUse(goodCKey);
dpm.getKeyList().add(goodCKeyUse);
- assertTrue(dpm.validate(new PfValidationResult()).isValid());
+ assertTrue(dpm.validate("").isValid());
PfKeyUse goodRKeyUse = new PfKeyUse(goodRKey);
dpm.getKeyList().add(goodRKeyUse);
- assertTrue(dpm.validate(new PfValidationResult()).isValid());
+ assertTrue(dpm.validate("").isValid());
PfConceptKey badCKey = new PfConceptKey("badCKey", VERSION001);
PfKeyUse badCKeyUse = new PfKeyUse(badCKey);
dpm.getKeyList().add(badCKeyUse);
- assertFalse(dpm.validate(new PfValidationResult()).isValid());
+ assertFalse(dpm.validate("").isValid());
dpm.getKeyList().remove(badCKeyUse);
- assertTrue(dpm.validate(new PfValidationResult()).isValid());
+ assertTrue(dpm.validate("").isValid());
PfKeyUse badRKeyUse = new PfKeyUse(new PfReferenceKey(badCKey, "badLocalName"));
dpm.getKeyList().add(badRKeyUse);
- assertFalse(dpm.validate(new PfValidationResult()).isValid());
+ assertFalse(dpm.validate("").isValid());
dpm.getKeyList().remove(badRKeyUse);
- assertTrue(dpm.validate(new PfValidationResult()).isValid());
+ assertTrue(dpm.validate("").isValid());
}
}
diff --git a/models-base/src/test/java/org/onap/policy/models/base/PfReferenceKeyTest.java b/models-base/src/test/java/org/onap/policy/models/base/PfReferenceKeyTest.java
index a27a5ddea..de328e9f2 100644
--- a/models-base/src/test/java/org/onap/policy/models/base/PfReferenceKeyTest.java
+++ b/models-base/src/test/java/org/onap/policy/models/base/PfReferenceKeyTest.java
@@ -21,6 +21,7 @@
package org.onap.policy.models.base;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -30,6 +31,7 @@ import static org.junit.Assert.assertTrue;
import java.lang.reflect.Field;
import org.junit.Test;
+import org.onap.policy.common.parameters.ValidationResult;
public class PfReferenceKeyTest {
@@ -93,9 +95,7 @@ public class PfReferenceKeyTest {
assertEquals(PfKey.Compatibility.DIFFERENT, testReferenceKey.getCompatibility(PfReferenceKey.getNullKey()));
assertEquals(PfKey.Compatibility.IDENTICAL, testReferenceKey.getCompatibility(testReferenceKey));
- PfValidationResult result = new PfValidationResult();
- result = testReferenceKey.validate(result);
- assertEquals(PfValidationResult.ValidationResult.VALID, result.getValidationResult());
+ assertTrue(testReferenceKey.validate("").isValid());
testReferenceKey.clean();
@@ -139,49 +139,37 @@ public class PfReferenceKeyTest {
Field parentNameField = testReferenceKey.getClass().getDeclaredField("parentKeyName");
parentNameField.setAccessible(true);
parentNameField.set(testReferenceKey, "Parent Name");
- PfValidationResult validationResult = new PfValidationResult();
- testReferenceKey.validate(validationResult);
+ ValidationResult validationResult = testReferenceKey.validate("");
parentNameField.set(testReferenceKey, "ParentName");
parentNameField.setAccessible(false);
- assertEquals(
- "parentKeyName invalid-parameter parentKeyName with value Parent Name "
- + "does not match regular expression " + PfKey.NAME_REGEXP,
- validationResult.getMessageList().get(0).getMessage());
+ assertThat(validationResult.getResult()).contains("\"parentKeyName\"")
+ .contains("does not match regular expression " + PfKey.NAME_REGEXP);
Field parentVersionField = testReferenceKey.getClass().getDeclaredField("parentKeyVersion");
parentVersionField.setAccessible(true);
parentVersionField.set(testReferenceKey, "Parent Version");
- PfValidationResult validationResult2 = new PfValidationResult();
- testReferenceKey.validate(validationResult2);
+ ValidationResult validationResult2 = testReferenceKey.validate("");
parentVersionField.set(testReferenceKey, VERSION001);
parentVersionField.setAccessible(false);
- assertEquals(
- "parentKeyVersion invalid-parameter parentKeyVersion with value Parent Version "
- + "does not match regular expression " + PfKey.VERSION_REGEXP,
- validationResult2.getMessageList().get(0).getMessage());
+ assertThat(validationResult2.getResult()).contains("\"parentKeyVersion\"")
+ .contains("does not match regular expression " + PfKey.VERSION_REGEXP);
Field parentLocalNameField = testReferenceKey.getClass().getDeclaredField("parentLocalName");
parentLocalNameField.setAccessible(true);
parentLocalNameField.set(testReferenceKey, "Parent Local Name");
- PfValidationResult validationResult3 = new PfValidationResult();
- testReferenceKey.validate(validationResult3);
+ ValidationResult validationResult3 = testReferenceKey.validate("");
parentLocalNameField.set(testReferenceKey, PARENT_LOCAL_NAME);
parentLocalNameField.setAccessible(false);
- assertEquals(
- "parentLocalName invalid-parameter parentLocalName with value "
- + "Parent Local Name does not match regular expression [A-Za-z0-9\\-_\\.]+|^$",
- validationResult3.getMessageList().get(0).getMessage());
+ assertThat(validationResult3.getResult()).contains("\"parentLocalName\"")
+ .contains("does not match regular expression [A-Za-z0-9\\-_\\.]+|^$");
Field localNameField = testReferenceKey.getClass().getDeclaredField("localName");
localNameField.setAccessible(true);
localNameField.set(testReferenceKey, "Local Name");
- PfValidationResult validationResult4 = new PfValidationResult();
- testReferenceKey.validate(validationResult4);
+ ValidationResult validationResult4 = testReferenceKey.validate("");
localNameField.set(testReferenceKey, LOCAL_NAME);
localNameField.setAccessible(false);
- assertEquals(
- "localName invalid-parameter localName with value Local Name "
- + "does not match regular expression [A-Za-z0-9\\-_\\.]+|^$",
- validationResult4.getMessageList().get(0).getMessage());
+ assertThat(validationResult4.getResult()).contains("\"localName\"")
+ .contains("does not match regular expression [A-Za-z0-9\\-_\\.]+|^$");
}
}
diff --git a/models-base/src/test/java/org/onap/policy/models/base/ValidatedTest.java b/models-base/src/test/java/org/onap/policy/models/base/ValidatedTest.java
index 5d1367028..8534d82a6 100644
--- a/models-base/src/test/java/org/onap/policy/models/base/ValidatedTest.java
+++ b/models-base/src/test/java/org/onap/policy/models/base/ValidatedTest.java
@@ -1,9 +1,8 @@
-/*
+/*-
* ============LICENSE_START=======================================================
- * ONAP Policy Models
+ * ONAP
* ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,424 +20,426 @@
package org.onap.policy.models.base;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
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.assertSame;
import static org.junit.Assert.assertTrue;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
+import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.junit.Before;
+import java.util.function.BiFunction;
+import lombok.AllArgsConstructor;
+import lombok.NonNull;
import org.junit.Test;
+import org.onap.policy.common.parameters.BeanValidationResult;
+import org.onap.policy.common.parameters.ObjectValidationResult;
+import org.onap.policy.common.parameters.ValidationResult;
+import org.onap.policy.common.parameters.ValidationStatus;
+import org.onap.policy.common.utils.coder.CoderException;
+import org.onap.policy.common.utils.coder.StandardCoder;
public class ValidatedTest {
- private static final String COLLECTION_TEXT = "collection";
- private static final String ERROR_MESSAGE = "error message";
- private static final String COLLECTION_FIELD = "coll";
- private static final String VALID_VALUE = "abc123";
- private static final String PROPS_FIELD = "props";
- private static final String MY_NAME = "my.name";
- private static final String VALID_FIELD = "validField";
- private static final String INVALID_FIELD = "invalidField";
- private static final String NULL_FIELD = "nullField";
- private static final String WORD_PAT = "\\w*";
- private static final String MY_TO_STRING = "[some text]";
- private static final String VERSION = "1.2.3";
-
- private Validated validated;
-
- @Before
- public void setUp() {
- validated = new Validated();
+ private static final @NonNull String MY_FIELD = "myField";
+ private static final @NonNull String Q_KEY = "\"" + Validated.KEY_TOKEN + "\"";
+ private static final @NonNull String Q_VALUE = "\"" + Validated.VALUE_TOKEN + "\"";
+ private static final String NOT_SAME = "not same";
+ private static final String TEXT = "some text";
+ private static final String OTHER = "other text";
+ private static final String NAME = "myKey";
+ private static final String VERSION = "1.0.0";
+ private static final String BLANKS = "\t \n";
+
+ @Test
+ public void testAddResult() {
+ BeanValidationResult result = new BeanValidationResult("", this);
+ Validated.addResult(result, MY_FIELD, TEXT, "some message");
+ assertThat(result.getResult()).contains(MY_FIELD).contains(TEXT).contains("some message");
+
+ assertThatThrownBy(() -> Validated.addResult(null, MY_FIELD, TEXT, OTHER))
+ .isInstanceOf(NullPointerException.class);
+
+ assertThatThrownBy(() -> Validated.addResult(result, null, TEXT, OTHER))
+ .isInstanceOf(NullPointerException.class);
+
+ assertThatCode(() -> Validated.addResult(result, MY_FIELD, null, OTHER)).doesNotThrowAnyException();
+
+ assertThatThrownBy(() -> Validated.addResult(result, MY_FIELD, TEXT, null))
+ .isInstanceOf(NullPointerException.class);
}
@Test
- public void testValidate() {
- assertThatThrownBy(() -> validated.validate(null)).isInstanceOf(NullPointerException.class);
+ public void testMakeNullResult() {
+ ValidationResult rnull = Validated.makeNullResult(MY_FIELD, TEXT);
+ assertEquals(MY_FIELD, rnull.getName());
+ assertThat(rnull.getResult()).contains(MY_FIELD).contains(TEXT).contains(Validated.IS_NULL);
+ assertFalse(rnull.isValid());
+
+ assertThatThrownBy(() -> Validated.makeNullResult(null, TEXT)).isInstanceOf(NullPointerException.class);
- PfValidationResult result = new PfValidationResult();
- assertSame(result, validated.validate(result));
- assertTrue(result.isValid());
- assertEquals(0, result.getMessageList().size());
+ assertThatCode(() -> Validated.makeNullResult(MY_FIELD, null)).doesNotThrowAnyException();
}
@Test
- public void testValidateNotNull() {
- PfValidationResult result = new PfValidationResult();
+ public void testValidateOptional() {
+ BeanValidationResult result = new BeanValidationResult("", this);
+ Validated.validateOptional(result, MY_FIELD, null);
+ assertTrue(result.isClean());
- final PfValidationResult result2 = result;
- assertThatThrownBy(() -> validated.validateNotNull(null, VALID_FIELD, VALID_VALUE, result2))
- .isInstanceOf(NullPointerException.class);
- assertThatThrownBy(() -> validated.validateNotNull(this, null, VALID_VALUE, result2))
+ Validated.validateOptional(result, MY_FIELD, new MyString(TEXT));
+ assertTrue(result.isClean());
+
+ Validated.validateOptional(result, MY_FIELD, new MyString(OTHER));
+ assertThat(result.getResult()).contains(MY_FIELD).contains(OTHER).contains(NOT_SAME);
+
+ assertThatThrownBy(() -> Validated.validateOptional(null, MY_FIELD, new MyString(TEXT)))
.isInstanceOf(NullPointerException.class);
- assertThatThrownBy(() -> validated.validateNotNull(this, VALID_FIELD, VALID_VALUE, null))
+
+ assertThatThrownBy(() -> Validated.validateOptional(result, null, new MyString(TEXT)))
.isInstanceOf(NullPointerException.class);
- // null text
- result = validated.validateNotNull(this, NULL_FIELD, null, result);
+ assertThatCode(() -> Validated.validateOptional(result, MY_FIELD, null)).doesNotThrowAnyException();
+ }
+
+ @Test
+ public void testValidateNotNull() {
+ assertThat(Validated.validateNotNull(MY_FIELD, TEXT)).isNull();
- // invalid text
- result = validated.validateNotNull(this, INVALID_FIELD, "!!!", result);
+ assertThat(Validated.validateNotNull(MY_FIELD, null).getResult()).contains(MY_FIELD)
+ .contains(Validated.IS_NULL);
- // valid text
- result = validated.validateNotNull(this, VALID_FIELD, VALID_VALUE, result);
+ // should invoke the value's validate() method, which should return success
+ assertThat(Validated.validateNotNull(MY_FIELD, new MyString(TEXT))).isNull();
- // different value
- result = validated.validateNotNull(this, VALID_FIELD, Integer.valueOf(10), result);
+ // should invoke the value's validate() method, which should return failure
+ assertThat(Validated.validateNotNull(MY_FIELD, new MyString(OTHER)).getResult()).contains(MY_FIELD)
+ .contains(NOT_SAME);
- assertFalse(result.isValid());
- assertEquals(1, result.getMessageList().size());
+ assertThatThrownBy(() -> Validated.validateNotNull(null, TEXT)).isInstanceOf(NullPointerException.class);
- // check result for null text
- PfValidationMessage msg = result.getMessageList().get(0);
- assertEquals(ValidatedTest.class.getName(), msg.getObservedClass());
- assertEquals(MY_TO_STRING, msg.getObservedKey().toString());
- assertTrue(msg.getMessage().contains("nullField invalid-null"));
+ assertThatCode(() -> Validated.validateNotNull(MY_FIELD, null)).doesNotThrowAnyException();
}
@Test
- public void testValidateNotNullConceptKey() {
- PfValidationResult result = new PfValidationResult();
-
- // null key
- PfConceptKey key = new PfConceptKey();
- key.setVersion(VERSION);
- result = validated.validateNotNull(key, result);
-
- // null value
- key = new PfConceptKey();
- key.setName(MY_NAME);
- result = validated.validateNotNull(key, result);
-
- // both null
- key = new PfConceptKey();
- result = validated.validateNotNull(key, result);
-
- assertFalse(result.isValid());
- assertEquals(4, result.getMessageList().size());
-
- // valid key & value
- key = new PfConceptKey();
- key.setName(MY_NAME);
- key.setVersion(VERSION);
- result = validated.validateNotNull(key, result);
-
- // no change
- assertFalse(result.isValid());
- assertEquals(4, result.getMessageList().size());
-
- Iterator<PfValidationMessage> it = result.getMessageList().iterator();
-
- // check null key
- PfValidationMessage msg = it.next();
- assertEquals(PfConceptKey.class.getName(), msg.getObservedClass());
- assertTrue(msg.getMessage().contains("name invalid-null"));
-
- // check null value
- msg = it.next();
- assertEquals(PfConceptKey.class.getName(), msg.getObservedClass());
- assertTrue(msg.getMessage().contains("version invalid-null"));
-
- // check both null
- msg = it.next();
- assertEquals(PfConceptKey.class.getName(), msg.getObservedClass());
- assertTrue(msg.getMessage().contains("name invalid-null"));
- assertTrue(it.next().getMessage().contains("version invalid-null"));
-
- PfValidationResult pfValidationResult = new PfValidationResult();
- final PfConceptKey key2 = key;
- assertThatThrownBy(() -> validated.validateNotNull(key2, null)).isInstanceOf(NullPointerException.class);
- assertThatThrownBy(() -> validated.validateNotNull(null, pfValidationResult))
+ public void testValidateNotBlank() {
+ assertThat(Validated.validateNotBlank(MY_FIELD, TEXT, false)).isNull();
+ assertThat(Validated.validateNotBlank(MY_FIELD, TEXT, true)).isNull();
+
+ assertThat(Validated.validateNotBlank(MY_FIELD, null, false)).isNull();
+ assertThat(Validated.validateNotBlank(MY_FIELD, null, true).getResult()).contains(MY_FIELD)
+ .contains(Validated.IS_BLANK);
+
+ assertThat(Validated.validateNotBlank(MY_FIELD, "", false).getResult()).contains(MY_FIELD)
+ .contains(Validated.IS_BLANK);
+ assertThat(Validated.validateNotBlank(MY_FIELD, "", true).getResult()).contains(MY_FIELD)
+ .contains(Validated.IS_BLANK);
+
+ assertThatThrownBy(() -> Validated.validateNotBlank(null, TEXT, false))
.isInstanceOf(NullPointerException.class);
+
+ assertThatCode(() -> Validated.validateNotBlank(MY_FIELD, null, false)).doesNotThrowAnyException();
}
@Test
- public void testValidateText() {
- PfValidationResult result = new PfValidationResult();
+ public void testValidateRegex() {
+ assertThat(Validated.validateRegex(MY_FIELD, "hello", ".*ll.*")).isNull();
- final PfValidationResult result2 = result;
- assertThatThrownBy(() -> validated.validateText(null, VALID_FIELD, VALID_VALUE, WORD_PAT, result2))
- .isInstanceOf(NullPointerException.class);
- assertThatThrownBy(() -> validated.validateText(this, null, VALID_VALUE, WORD_PAT, result2))
- .isInstanceOf(NullPointerException.class);
- assertThatThrownBy(() -> validated.validateText(this, VALID_FIELD, VALID_VALUE, null, result2))
- .isInstanceOf(NullPointerException.class);
- assertThatThrownBy(() -> validated.validateText(this, VALID_FIELD, VALID_VALUE, WORD_PAT, null))
- .isInstanceOf(NullPointerException.class);
+ assertThat(Validated.validateRegex(MY_FIELD, "hello", "[x-z]").getResult()).contains(MY_FIELD).contains("hello")
+ .contains("does not match regular expression [x-z]");
- // null text
- result = validated.validateText(this, NULL_FIELD, null, WORD_PAT, result);
+ assertThatThrownBy(() -> Validated.validateRegex(null, "hello", "ll")).isInstanceOf(NullPointerException.class);
- // invalid text
- result = validated.validateText(this, INVALID_FIELD, "!!!", WORD_PAT, result);
+ assertThatCode(() -> Validated.validateRegex(MY_FIELD, null, "ll")).doesNotThrowAnyException();
- // valid text
- result = validated.validateText(this, VALID_FIELD, VALID_VALUE, WORD_PAT, result);
+ assertThatThrownBy(() -> Validated.validateRegex(MY_FIELD, "hello", null))
+ .isInstanceOf(NullPointerException.class);
+ }
- assertFalse(result.isValid());
- assertEquals(1, result.getMessageList().size());
+ @Test
+ public void testValidateKeyNotNull() throws CoderException {
+ assertThat(Validated.validateKeyNotNull(MY_FIELD, new PfConceptKey(NAME, VERSION)).getResult()).isNull();
+ assertThat(Validated.validateKeyNotNull(MY_FIELD, new PfConceptKey(NAME, PfConceptKey.NULL_KEY_VERSION))
+ .getResult()).isNull();
+ assertThat(Validated.validateKeyNotNull(MY_FIELD, new PfConceptKey(PfConceptKey.NULL_KEY_NAME, VERSION))
+ .getResult()).isNull();
+
+ // key is null
+ assertThat(Validated.validateKeyNotNull(MY_FIELD, new PfConceptKey()).getResult()).contains(MY_FIELD)
+ .doesNotContain("\"name\"").doesNotContain("\"version\"").contains(Validated.IS_A_NULL_KEY);
+
+ /*
+ * Key is not null, but key.validate() should fail due to an invalid version.
+ * Note: have to create the key by decoding from json, as the class will prevent
+ * an invalid version from being assigned.
+ */
+ PfConceptKey key = new StandardCoder().decode("{'name':'myKey','version':'bogus'}".replace('\'', '"'),
+ PfConceptKey.class);
+ assertThat(Validated.validateKeyNotNull(MY_FIELD, key).getResult()).contains(MY_FIELD).contains("version")
+ .contains("does not match regular expression");
+
+ // null parameter tests
+ assertThatThrownBy(() -> Validated.validateKeyNotNull(null, new PfConceptKey()))
+ .isInstanceOf(NullPointerException.class);
- // check result for invalid text
- PfValidationMessage msg = result.getMessageList().get(0);
- assertEquals(ValidatedTest.class.getName(), msg.getObservedClass());
- assertEquals(MY_TO_STRING, msg.getObservedKey().toString());
- assertTrue(msg.getMessage().contains("invalidField invalid-parameter invalidField"));
+ assertThatCode(() -> Validated.validateKeyNotNull(MY_FIELD, null)).doesNotThrowAnyException();
}
@Test
- public void testValidatePropertiesNotNull() {
- PfValidationResult result = new PfValidationResult();
- result = validated.validatePropertiesNotNull(this, "properties", null, result);
- assertTrue(result.isValid());
- assertEquals(0, result.getMessageList().size());
+ public void testValidateKeyVersionNotNull() {
+ assertThat(Validated.validateKeyVersionNotNull(MY_FIELD, null)).isNull();
- Map<String, Integer> map = new LinkedHashMap<>();
+ assertThat(Validated.validateKeyVersionNotNull(MY_FIELD, new PfConceptKey(NAME, VERSION))).isNull();
- // null key
- map.put(null, 10);
+ assertThat(Validated.validateKeyVersionNotNull(MY_FIELD, new PfConceptKey(NAME, PfConceptKey.NULL_KEY_VERSION))
+ .getResult()).contains(MY_FIELD).contains("version").contains(Validated.IS_NULL);
- // null value
- map.put("abc", null);
+ assertThatThrownBy(() -> Validated.validateKeyVersionNotNull(null, new PfConceptKey()))
+ .isInstanceOf(NullPointerException.class);
- // valid key & value
- map.put("def", 11);
+ assertThatCode(() -> Validated.validateKeyVersionNotNull(MY_FIELD, null)).doesNotThrowAnyException();
+ }
+ @Test
+ public void testValidateMinIntIntegerBoolean_testValidateMinStringIntegerIntIntegerBoolean() {
+ /*
+ * No "special" value, don't check the reference.
+ */
+ BiFunction<String, Integer, ValidationResult> func = Validated.validateMin(10, null, false);
+ assertThat(func.apply(MY_FIELD, null)).isNull();
- result = validated.validatePropertiesNotNull(this, PROPS_FIELD, map, result);
+ // exact match
+ assertThat(func.apply(MY_FIELD, 10)).isNull();
- assertFalse(result.isValid());
- assertEquals(2, result.getMessageList().size());
+ assertThat(func.apply(MY_FIELD, 20)).isNull();
- Iterator<PfValidationMessage> it = result.getMessageList().iterator();
+ assertThat(func.apply(MY_FIELD, 9).getResult()).contains(MY_FIELD).contains("9")
+ .contains("is below the minimum value: 10");
- // check null key
- PfValidationMessage msg = it.next();
- assertEquals(ValidatedTest.class.getName(), msg.getObservedClass());
- assertEquals(MY_TO_STRING, msg.getObservedKey().toString());
- assertTrue(msg.getMessage().contains("props.null invalid-null"));
+ /*
+ * "special" value, don't check the reference.
+ */
+ func = Validated.validateMin(10, 7, false);
+ assertThat(func.apply(MY_FIELD, null)).isNull();
- // check null value
- msg = it.next();
- assertEquals(ValidatedTest.class.getName(), msg.getObservedClass());
- assertEquals(MY_TO_STRING, msg.getObservedKey().toString());
- assertTrue(msg.getMessage().contains("props.abc invalid-null"));
+ // exact match
+ assertThat(func.apply(MY_FIELD, 10)).isNull();
- final PfValidationResult result2 = result;
- assertThatThrownBy(() -> validated.validatePropertiesNotNull(null, PROPS_FIELD, map, result2))
- .isInstanceOf(NullPointerException.class);
- assertThatThrownBy(() -> validated.validatePropertiesNotNull(this, null, map, result2))
- .isInstanceOf(NullPointerException.class);
- assertThatThrownBy(() -> validated.validatePropertiesNotNull(this, PROPS_FIELD, map, null))
- .isInstanceOf(NullPointerException.class);
- }
+ assertThat(func.apply(MY_FIELD, 20)).isNull();
- @Test
- public void testValidateCollectionNotNull() {
- PfValidationResult result = new PfValidationResult();
- result = validated.validateCollectionNotNull(this, COLLECTION_TEXT, null, result);
- assertTrue(result.isValid());
- assertEquals(0, result.getMessageList().size());
+ // special value - should be ok
+ assertThat(func.apply(MY_FIELD, 7)).isNull();
- final List<String> lst = Arrays.asList("abc", null, "def", null);
+ assertThat(func.apply(MY_FIELD, 9).getResult()).contains(MY_FIELD).contains("9")
+ .contains("is below the minimum value: 10");
- result = validated.validateCollectionNotNull(this, COLLECTION_FIELD, lst, result);
+ /*
+ * Check the reference (i.e., generate an error if the value is null).
+ */
+ func = Validated.validateMin(10, null, true);
+ assertThat(func.apply(MY_FIELD, null).getResult()).contains(MY_FIELD).contains(Validated.IS_NULL);
- assertFalse(result.isValid());
- assertEquals(2, result.getMessageList().size());
+ // exact match
+ assertThat(func.apply(MY_FIELD, 10)).isNull();
- Iterator<PfValidationMessage> it = result.getMessageList().iterator();
+ assertThat(func.apply(MY_FIELD, 20)).isNull();
- // check first item
- PfValidationMessage msg = it.next();
- assertEquals(ValidatedTest.class.getName(), msg.getObservedClass());
- assertEquals(MY_TO_STRING, msg.getObservedKey().toString());
- assertTrue(msg.getMessage().contains("coll.1 invalid-null"));
+ assertThat(func.apply(MY_FIELD, 9).getResult()).contains(MY_FIELD).contains("9")
+ .contains("is below the minimum value: 10");
- // check null value
- msg = it.next();
- assertEquals(ValidatedTest.class.getName(), msg.getObservedClass());
- assertEquals(MY_TO_STRING, msg.getObservedKey().toString());
- assertTrue(msg.getMessage().contains("coll.3 invalid-null"));
- final PfValidationResult result2 = result;
- assertThatThrownBy(() -> validated.validateCollectionNotNull(null, COLLECTION_FIELD, lst, result2))
- .isInstanceOf(NullPointerException.class);
- assertThatThrownBy(() -> validated.validateCollectionNotNull(this, null, lst, result2))
- .isInstanceOf(NullPointerException.class);
- assertThatThrownBy(() -> validated.validateCollectionNotNull(this, COLLECTION_FIELD, lst, null))
- .isInstanceOf(NullPointerException.class);
+ BiFunction<String, Integer, ValidationResult> func2 = func;
+ assertThatThrownBy(() -> func2.apply(null, 30)).isInstanceOf(NullPointerException.class);
+
+ assertThatCode(() -> func2.apply(MY_FIELD, null)).doesNotThrowAnyException();
}
@Test
- public void testValidateCollection() {
- PfValidationResult result = new PfValidationResult();
- result = validated.validateCollection(this, COLLECTION_TEXT, null, result);
- assertTrue(result.isValid());
- assertEquals(0, result.getMessageList().size());
-
- List<MyValid> lst = Arrays.asList(new MyValid(0, false), new MyValid(1, true), null, new MyValid(2, false),
- new MyValid(3, true));
- result = validated.validateCollection(this, COLLECTION_FIELD, lst, result);
-
- assertFalse(result.isValid());
- assertEquals(2, result.getMessageList().size());
-
- Iterator<PfValidationMessage> it = result.getMessageList().iterator();
-
- // check first item
- PfValidationMessage msg = it.next();
- assertEquals(MyValid.class.getName(), msg.getObservedClass());
- assertEquals(MY_TO_STRING, msg.getObservedKey().toString());
- assertTrue(msg.getMessage().contains("index.0 invalid-wrong value"));
-
- // check null value
- msg = it.next();
- assertEquals(MyValid.class.getName(), msg.getObservedClass());
- assertEquals(MY_TO_STRING, msg.getObservedKey().toString());
- assertTrue(msg.getMessage().contains("index.2 invalid-wrong value"));
-
- final PfValidationResult result2 = result;
- assertThatThrownBy(() -> validated.validateCollection(null, COLLECTION_FIELD, lst, result2))
+ public void testValidateList() {
+ BeanValidationResult result = new BeanValidationResult("", this);
+ Validated.validateList(result, MY_FIELD, null, Validated::validateNotNull);
+ assertThat(result.getResult()).isNull();
+
+ result = new BeanValidationResult("", this);
+ Validated.validateList(result, MY_FIELD, List.of(TEXT, OTHER), Validated::validateNotNull);
+ assertThat(result.getResult()).isNull();
+
+ List<String> list = new ArrayList<>();
+ list.add(TEXT);
+ list.add(null);
+ list.add(OTHER);
+ list.add(null);
+ result = new BeanValidationResult("", this);
+ Validated.validateList(result, MY_FIELD, list, Validated::validateNotNull);
+ assertThat(result.getResult()).doesNotContain("0").contains("1").doesNotContain("2").contains("3")
+ .contains(Validated.IS_NULL);
+
+ BeanValidationResult result2 = result;
+ assertThatThrownBy(() -> Validated.validateList(null, MY_FIELD, List.of(), Validated::validateNotNull))
.isInstanceOf(NullPointerException.class);
- assertThatThrownBy(() -> validated.validateCollection(this, null, lst, result2))
+
+ assertThatThrownBy(() -> Validated.validateList(result2, null, List.of(), Validated::validateNotNull))
.isInstanceOf(NullPointerException.class);
- assertThatThrownBy(() -> validated.validateCollection(this, COLLECTION_FIELD, lst, null))
+
+ assertThatCode(() -> Validated.validateList(result2, MY_FIELD, null, Validated::validateNotNull))
+ .doesNotThrowAnyException();
+
+ assertThatThrownBy(() -> Validated.validateList(result2, MY_FIELD, List.of(), null))
.isInstanceOf(NullPointerException.class);
}
@Test
- public void testValidateConceptCollection() {
- PfValidationResult result = new PfValidationResult();
- result = validated.validateConceptCollection(this, COLLECTION_TEXT, null, result);
- assertTrue(result.isValid());
- assertEquals(0, result.getMessageList().size());
-
- List<MyConcept> lst = Arrays.asList(new MyConcept(0, false), new MyConcept(1, true), null,
- new MyConcept(2, false), new MyConcept(3, true));
- result = validated.validateConceptCollection(this, COLLECTION_FIELD, lst, result);
-
- assertFalse(result.isValid());
- assertEquals(2, result.getMessageList().size());
-
- Iterator<PfValidationMessage> it = result.getMessageList().iterator();
-
- // check first item
- PfValidationMessage msg = it.next();
- assertEquals(MyConcept.class.getName(), msg.getObservedClass());
- assertEquals(MY_TO_STRING, msg.getObservedKey().toString());
- assertTrue(msg.getMessage().contains("index.0 invalid-wrong value"));
-
- // check null value
- msg = it.next();
- assertEquals(MyConcept.class.getName(), msg.getObservedClass());
- assertEquals(MY_TO_STRING, msg.getObservedKey().toString());
- assertTrue(msg.getMessage().contains("index.2 invalid-wrong value"));
-
- final PfValidationResult result2 = result;
- assertThatThrownBy(() -> validated.validateConceptCollection(null, COLLECTION_FIELD, lst, result2))
+ public void testValidateMap() {
+ BeanValidationResult result = new BeanValidationResult("", this);
+ Validated.validateMap(result, MY_FIELD, null, Validated::validateEntryNotBlankNotBlank);
+ assertThat(result.getResult()).isNull();
+
+ result = new BeanValidationResult("", this);
+ Validated.validateMap(result, MY_FIELD, Map.of("abc", TEXT, "def", OTHER),
+ Validated::validateEntryNotBlankNotBlank);
+ assertThat(result.getResult()).isNull();
+
+ // invalid values
+ Map<String, String> map = new HashMap<>();
+ map.put("ghi", TEXT);
+ map.put("jkl", "");
+ map.put("mno", OTHER);
+ map.put("pqr", "");
+ result = new BeanValidationResult("", this);
+ Validated.validateMap(result, MY_FIELD, map, Validated::validateEntryNotBlankNotBlank);
+ assertThat(result.getResult()).doesNotContain("abc").contains("jkl").doesNotContain("mno").contains("pqr")
+ .contains(Q_VALUE).doesNotContain(Q_KEY).contains(Validated.IS_BLANK);
+
+ // invalid keys
+ map = new HashMap<>();
+ map.put("stu", TEXT);
+ map.put("", TEXT);
+ map.put("vwx", OTHER);
+ map.put(null, OTHER);
+ result = new BeanValidationResult("", this);
+ Validated.validateMap(result, MY_FIELD, map, Validated::validateEntryNotBlankNotBlank);
+ assertThat(result.getResult()).doesNotContain("stu").contains("\"\"").doesNotContain("vwx").contains("null")
+ .contains(Q_KEY).doesNotContain(Q_VALUE).contains(Validated.IS_BLANK);
+
+ BeanValidationResult result2 = result;
+ Map<String, String> map2 = map;
+ assertThatThrownBy(() -> Validated.validateMap(null, MY_FIELD, map2, Validated::validateEntryNotBlankNotBlank))
.isInstanceOf(NullPointerException.class);
- assertThatThrownBy(() -> validated.validateConceptCollection(this, null, lst, result2))
+
+ assertThatThrownBy(() -> Validated.validateMap(result2, null, map2, Validated::validateEntryNotBlankNotBlank))
.isInstanceOf(NullPointerException.class);
- assertThatThrownBy(() -> validated.validateConceptCollection(this, COLLECTION_FIELD, lst, null))
+
+ assertThatCode(() -> Validated.validateMap(result2, MY_FIELD, null, Validated::validateEntryNotBlankNotBlank))
+ .doesNotThrowAnyException();
+
+ assertThatThrownBy(() -> Validated.validateMap(result2, MY_FIELD, map2, null))
.isInstanceOf(NullPointerException.class);
}
@Test
- public void testAddError() {
- final PfValidationResult result = new PfValidationResult();
- final PfValidationResult result2 = result;
+ public void testValidateEntryNotBlankNotBlank() {
+ assertThat(Validated.validateEntryNotBlankNotBlank(makeEntry(TEXT, OTHER))).isNull();
- assertThatThrownBy(() -> validated.addError(null, VALID_FIELD, result2, ERROR_MESSAGE))
- .isInstanceOf(NullPointerException.class);
- assertThatThrownBy(() -> validated.addError(this, null, result2, ERROR_MESSAGE))
- .isInstanceOf(NullPointerException.class);
- assertThatThrownBy(() -> validated.addError(this, VALID_FIELD, null, ERROR_MESSAGE))
- .isInstanceOf(NullPointerException.class);
-
- validated.addError(this, VALID_FIELD, result, "error-A");
- validated.addError(this, VALID_FIELD, result, null);
- validated.addError(this, VALID_FIELD, result, "error-B");
+ // try invalid values for the key
+ assertThat(Validated.validateEntryNotBlankNotBlank(makeEntry(null, OTHER)).getResult()).contains(Q_KEY)
+ .contains(Validated.IS_BLANK).doesNotContain(Q_VALUE);
- assertFalse(result.isValid());
- assertEquals(2, result.getMessageList().size());
+ assertThat(Validated.validateEntryNotBlankNotBlank(makeEntry(BLANKS, OTHER)).getResult()).contains(Q_KEY)
+ .contains(Validated.IS_BLANK).doesNotContain(Q_VALUE);
- Iterator<PfValidationMessage> it = result.getMessageList().iterator();
+ // try invalid values for the value
+ assertThat(Validated.validateEntryNotBlankNotBlank(makeEntry(TEXT, null)).getResult()).contains(Q_VALUE)
+ .contains(Validated.IS_BLANK).doesNotContain(Q_KEY);
- PfValidationMessage msg = it.next();
- assertEquals(ValidatedTest.class.getName(), msg.getObservedClass());
- assertEquals(MY_TO_STRING, msg.getObservedKey().toString());
- assertTrue(msg.getMessage().contains("validField invalid-error-A"));
+ assertThat(Validated.validateEntryNotBlankNotBlank(makeEntry(TEXT, BLANKS)).getResult()).contains(Q_VALUE)
+ .contains(Validated.IS_BLANK).doesNotContain(Q_KEY);
- msg = it.next();
- assertEquals(ValidatedTest.class.getName(), msg.getObservedClass());
- assertEquals(MY_TO_STRING, msg.getObservedKey().toString());
- assertTrue(msg.getMessage().contains("validField invalid-error-B"));
+ // both invalid
+ assertThat(Validated.validateEntryNotBlankNotBlank(makeEntry(BLANKS, BLANKS)).getResult()).contains(Q_KEY)
+ .contains(Q_VALUE);
}
@Test
- public void testMakeKey() {
- assertThatThrownBy(() -> validated.makeKey(null)).isInstanceOf(NullPointerException.class);
+ public void testValidateEntryNotBlankNotNull() {
+ assertThat(Validated.validateEntryNotBlankNotNull(makeEntry(TEXT, OTHER))).isNull();
- PfKey key = validated.makeKey(this);
- assertEquals(MY_TO_STRING, key.toString());
- }
+ // try invalid values for the key
+ assertThat(Validated.validateEntryNotBlankNotNull(makeEntry(null, OTHER)).getResult()).contains(Q_KEY)
+ .contains(Validated.IS_BLANK).doesNotContain(Q_VALUE);
+
+ assertThat(Validated.validateEntryNotBlankNotNull(makeEntry(BLANKS, OTHER)).getResult()).contains(Q_KEY)
+ .contains(Validated.IS_BLANK).doesNotContain(Q_VALUE);
- @Override
- public String toString() {
- return MY_TO_STRING;
+ // try invalid values for the value
+ assertThat(Validated.validateEntryNotBlankNotNull(makeEntry(TEXT, null)).getResult()).contains(Q_VALUE)
+ .contains(Validated.IS_NULL).doesNotContain(Q_KEY);
+
+ // blanks should have no impact for the value
+ assertThat(Validated.validateEntryNotBlankNotNull(makeEntry(TEXT, BLANKS))).isNull();
+
+ // both invalid
+ assertThat(Validated.validateEntryNotBlankNotNull(makeEntry(BLANKS, null)).getResult()).contains(Q_KEY)
+ .contains(Q_VALUE);
}
- private static class MyValid extends Validated {
- private boolean valid;
- private int index;
+ @Test
+ public void testValidateEntryValueNotNull() {
+ assertThat(Validated.validateEntryValueNotNull(makeEntry(TEXT, OTHER))).isNull();
- public MyValid(int index, boolean valid) {
- this.index = index;
- this.valid = valid;
- }
+ // blanks should have no impact
+ assertThat(Validated.validateEntryValueNotNull(makeEntry(BLANKS, OTHER))).isNull();
+ assertThat(Validated.validateEntryNotBlankNotNull(makeEntry(TEXT, BLANKS))).isNull();
- @Override
- public PfValidationResult validate(PfValidationResult result) {
- if (!valid) {
- this.addError(this, "index." + index, result, "wrong value");
- }
+ assertThat(Validated.validateEntryValueNotNull(makeEntry(null, OTHER)).getResult()).contains(Q_KEY)
+ .contains(Validated.IS_NULL).doesNotContain(Q_VALUE);
- return result;
- }
+ assertThat(Validated.validateEntryValueNotNull(makeEntry(TEXT, null)).getResult()).contains(Q_VALUE)
+ .contains(Validated.IS_NULL).doesNotContain(Q_KEY);
- @Override
- public String toString() {
- return MY_TO_STRING;
- }
+ // should invoke the value's validate() method, which should return success
+ assertThat(Validated.validateEntryValueNotNull(makeEntry(TEXT, new MyString(TEXT)))).isNull();
+
+ // should invoke the value's validate() method, which should return failure
+ assertThat(Validated.validateEntryValueNotNull(makeEntry(TEXT, new MyString(OTHER))).getResult())
+ .contains(Q_VALUE).contains(NOT_SAME).doesNotContain(Q_KEY);
+
+ // both invalid
+ assertThat(Validated.validateEntryValueNotNull(makeEntry(null, null)).getResult()).contains(Q_KEY)
+ .contains(Q_VALUE);
}
- private static class MyConcept extends PfConceptKey {
- private static final long serialVersionUID = 1L;
+ @Test
+ public void testGetKeyId() {
+ // not a key field - should just use the given value
+ BeanValidationResult result = new BeanValidationResult("", this);
+ Validated.addResult(result, MY_FIELD, TEXT, "some message");
+ assertThat(result.getResult()).contains(MY_FIELD).contains(TEXT).contains("some message");
+
+ // repeat with a key field - should use the key's ID
+ result = new BeanValidationResult("", this);
+ Validated.addResult(result, MY_FIELD, new PfConceptKey(NAME, VERSION), "some message");
+ assertThat(result.getResult()).contains(MY_FIELD).contains("myKey:1.0.0").contains("some message");
+ }
- private boolean valid;
- private int index;
+ private <V> Map.Entry<String, V> makeEntry(String key, V value) {
+ Map<String, V> map = new HashMap<>();
+ map.put(key, value);
+ return map.entrySet().iterator().next();
+ }
- public MyConcept(int index, boolean valid) {
- this.index = index;
- this.valid = valid;
- }
+ @AllArgsConstructor
+ private static class MyString extends Validated {
+ private final String text;
@Override
- public PfValidationResult validate(PfValidationResult result) {
- if (!valid) {
- new Validated().addError(this, "index." + index, result, "wrong value");
+ public ValidationResult validate(String fieldName) {
+ if (TEXT.equals(text)) {
+ return null;
}
- return result;
- }
-
- @Override
- public String toString() {
- return MY_TO_STRING;
+ return new ObjectValidationResult(fieldName, text, ValidationStatus.INVALID, NOT_SAME);
}
}
}
diff --git a/models-base/src/test/java/org/onap/policy/models/base/ValidationTest.java b/models-base/src/test/java/org/onap/policy/models/base/ValidationTest.java
deleted file mode 100644
index 6030d2ab9..000000000
--- a/models-base/src/test/java/org/onap/policy/models/base/ValidationTest.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019-2020 Nordix Foundation.
- * 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.models.base;
-
-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.models.base.PfValidationResult.ValidationResult;
-
-public class ValidationTest {
-
- private static final String HELLO = "hello";
- private static final String SOME_MESSAGE = "Some message";
-
- @Test
- public void testValidation1() {
- PfValidationResult result = new PfValidationResult();
- PfConceptKey pfKeyey = new PfConceptKey("PK", "0.0.1");
- result = pfKeyey.validate(result);
-
- assertNotNull(result);
- assertTrue(result.isOk());
- assertTrue(result.isValid());
- assertEquals(PfValidationResult.ValidationResult.VALID, result.getValidationResult());
- assertNotNull(result.getMessageList());
-
- PfValidationMessage vmess0 = new PfValidationMessage(PfConceptKey.getNullKey(), PfConceptKey.class,
- ValidationResult.VALID, SOME_MESSAGE);
- result.addValidationMessage(vmess0);
-
- assertTrue(result.isOk());
- assertTrue(result.isValid());
- assertEquals(PfValidationResult.ValidationResult.VALID, result.getValidationResult());
- assertNotNull(result.getMessageList());
- assertNotNull(HELLO, result.toString());
-
- PfValidationMessage vmess1 = new PfValidationMessage(PfConceptKey.getNullKey(), PfConceptKey.class,
- ValidationResult.OBSERVATION, SOME_MESSAGE);
- result.addValidationMessage(vmess1);
-
- assertTrue(result.isOk());
- assertTrue(result.isValid());
- assertEquals(PfValidationResult.ValidationResult.OBSERVATION, result.getValidationResult());
- assertNotNull(result.getMessageList());
- assertNotNull(HELLO, result.toString());
- }
-
-
- @Test
- public void testValidation2() {
- PfValidationResult result = new PfValidationResult();
-
- PfValidationMessage vmess2 = new PfValidationMessage(PfConceptKey.getNullKey(), PfConceptKey.class,
- ValidationResult.WARNING, SOME_MESSAGE);
- result.addValidationMessage(vmess2);
-
- assertFalse(result.isOk());
- assertTrue(result.isValid());
- assertEquals(PfValidationResult.ValidationResult.WARNING, result.getValidationResult());
- assertNotNull(result.getMessageList());
- assertNotNull(HELLO, result.toString());
-
- PfValidationMessage vmess3 = new PfValidationMessage(PfConceptKey.getNullKey(), PfConceptKey.class,
- ValidationResult.INVALID, SOME_MESSAGE);
- result.addValidationMessage(vmess3);
-
- assertFalse(result.isOk());
- assertFalse(result.isValid());
- assertEquals(PfValidationResult.ValidationResult.INVALID, result.getValidationResult());
- assertNotNull(result.getMessageList());
- assertNotNull(HELLO, result.toString());
-
- assertEquals(PfValidationResult.ValidationResult.INVALID, result.getMessageList().get(1).getValidationResult());
- assertEquals(SOME_MESSAGE, result.getMessageList().get(1).getMessage());
- assertEquals(PfConceptKey.class.getName(), result.getMessageList().get(1).getObservedClass());
- assertEquals(PfConceptKey.getNullKey(), result.getMessageList().get(1).getObservedKey());
- }
-
- @Test
- public void testValidationAppend() {
- PfValidationResult result = new PfValidationResult();
-
- PfValidationResult result2 = new PfValidationResult();
- PfValidationMessage vmess1 = new PfValidationMessage(PfConceptKey.getNullKey(), PfConceptKey.class,
- ValidationResult.OBSERVATION, "Message 1");
- result2.addValidationMessage(vmess1);
-
- result.append(result2);
- assertEquals(1, result.getMessageList().size());
- assertEquals(ValidationResult.OBSERVATION, result.getValidationResult());
-
- PfValidationResult result3 = new PfValidationResult();
- PfValidationMessage vmess2 = new PfValidationMessage(PfConceptKey.getNullKey(), PfConceptKey.class,
- ValidationResult.WARNING, "Message 2");
- result3.addValidationMessage(vmess2);
- result.append(result3);
- assertEquals(2, result.getMessageList().size());
- assertEquals(ValidationResult.WARNING, result.getValidationResult());
-
- PfValidationResult result4 = new PfValidationResult();
- PfValidationMessage vmess3 = new PfValidationMessage(PfConceptKey.getNullKey(), PfConceptKey.class,
- ValidationResult.INVALID, "Message 3");
- PfValidationMessage vmess4 = new PfValidationMessage(PfConceptKey.getNullKey(), PfConceptKey.class,
- ValidationResult.VALID, "Message 4");
- result4.addValidationMessage(vmess3);
- result4.addValidationMessage(vmess4);
- result.append(result4);
- assertEquals(4, result.getMessageList().size());
- assertEquals(ValidationResult.INVALID, result.getValidationResult());
- }
-}
diff --git a/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfConcept.java b/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfConcept.java
index be398b95f..67a450702 100644
--- a/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfConcept.java
+++ b/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfConcept.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
- * 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.
@@ -27,13 +27,12 @@ import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NonNull;
import org.apache.commons.lang3.ObjectUtils;
+import org.onap.policy.common.parameters.BeanValidationResult;
+import org.onap.policy.common.parameters.ValidationResult;
import org.onap.policy.models.base.PfAuthorative;
import org.onap.policy.models.base.PfConcept;
import org.onap.policy.models.base.PfConceptKey;
import org.onap.policy.models.base.PfKey;
-import org.onap.policy.models.base.PfValidationMessage;
-import org.onap.policy.models.base.PfValidationResult;
-import org.onap.policy.models.base.PfValidationResult.ValidationResult;
@Data
@EqualsAndHashCode(callSuper = false)
@@ -102,20 +101,11 @@ public class DummyPfConcept extends PfConcept implements PfAuthorative<DummyAuth
}
@Override
- public PfValidationResult validate(PfValidationResult resultIn) {
- PfValidationResult result = resultIn;
+ public ValidationResult validate(@NonNull String fieldName) {
+ BeanValidationResult result = new BeanValidationResult(fieldName, this);
- if (key.isNullKey()) {
- result.addValidationMessage(
- new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID, "key is a null key"));
- }
-
- result = key.validate(result);
-
- if (description != null && description.trim().length() == 0) {
- result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID,
- "property description may not be blank"));
- }
+ result.addResult(validateKeyNotNull("key", key));
+ result.addResult(validateNotBlank("description", description, false));
return result;
}
diff --git a/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfKey.java b/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfKey.java
index 81ebb6e59..5a5891ad6 100644
--- a/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfKey.java
+++ b/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfKey.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
- * 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,9 +24,9 @@ package org.onap.policy.models.base.testconcepts;
import java.util.Arrays;
import java.util.List;
import lombok.NonNull;
+import org.onap.policy.common.parameters.ValidationResult;
import org.onap.policy.models.base.PfConcept;
import org.onap.policy.models.base.PfKey;
-import org.onap.policy.models.base.PfValidationResult;
public class DummyPfKey extends PfKey {
private static final long serialVersionUID = 1L;
@@ -75,7 +75,7 @@ public class DummyPfKey extends PfKey {
}
@Override
- public PfValidationResult validate(PfValidationResult result) {
+ public ValidationResult validate(@NonNull String fieldName) {
return null;
}
diff --git a/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfModel.java b/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfModel.java
index 764b91b24..f828fba09 100644
--- a/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfModel.java
+++ b/models-base/src/test/java/org/onap/policy/models/base/testconcepts/DummyPfModel.java
@@ -1,7 +1,7 @@
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2019 Nordix Foundation.
- * 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.
@@ -25,12 +25,13 @@ import java.util.ArrayList;
import java.util.List;
import lombok.Data;
import lombok.EqualsAndHashCode;
+import lombok.NonNull;
+import org.onap.policy.common.parameters.BeanValidationResult;
import org.onap.policy.models.base.PfConcept;
import org.onap.policy.models.base.PfConceptKey;
import org.onap.policy.models.base.PfKey;
import org.onap.policy.models.base.PfModel;
import org.onap.policy.models.base.PfUtils;
-import org.onap.policy.models.base.PfValidationResult;
@Data
@EqualsAndHashCode(callSuper = true)
@@ -108,11 +109,12 @@ public class DummyPfModel extends PfModel {
}
@Override
- public PfValidationResult validate(final PfValidationResult resultIn) {
- PfValidationResult result = super.validate(resultIn);
+ public BeanValidationResult validate(@NonNull String fieldName) {
+ BeanValidationResult result = super.validate(fieldName);
+ int count = 0;
for (PfKey pfKey : keyList) {
- result = pfKey.validate(result);
+ result.addResult(pfKey.validate("keyList." + (count++)));
}
return result;