diff options
Diffstat (limited to 'models-base')
21 files changed, 1036 insertions, 311 deletions
diff --git a/models-base/pom.xml b/models-base/pom.xml index 712bc9108..0523c3324 100644 --- a/models-base/pom.xml +++ b/models-base/pom.xml @@ -17,8 +17,7 @@ SPDX-License-Identifier: Apache-2.0 ============LICENSE_END========================================================= --> -<project xmlns="http://maven.apache.org/POM/4.0.0" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> @@ -30,4 +29,12 @@ <artifactId>policy-models-base</artifactId> <name>${project.artifactId}</name> <description>[${project.parent.artifactId}] module provides basic model handling for the ONAP Policy Framework</description> + + <dependencies> + <dependency> + <groupId>org.onap.policy.models</groupId> + <artifactId>policy-models-errors</artifactId> + <version>${project.version}</version> + </dependency> + </dependencies> </project> diff --git a/models-base/src/main/java/org/onap/policy/models/base/PfConceptKey.java b/models-base/src/main/java/org/onap/policy/models/base/PfConceptKey.java index 9f575851b..84239e5eb 100644 --- a/models-base/src/main/java/org/onap/policy/models/base/PfConceptKey.java +++ b/models-base/src/main/java/org/onap/policy/models/base/PfConceptKey.java @@ -177,6 +177,73 @@ public class PfConceptKey extends PfKey { } @Override + public boolean isNewerThan(@NonNull final PfKey otherKey) { + Assertions.instanceOf(otherKey, PfConceptKey.class); + + final PfConceptKey otherConceptKey = (PfConceptKey) otherKey; + + if (this.equals(otherConceptKey)) { + return false; + } + + if (!this.getName().equals(otherConceptKey.getName())) { + return this.getName().compareTo(otherConceptKey.getName()) > 0; + } + + final String[] thisVersionArray = getVersion().split("\\."); + final String[] otherVersionArray = otherConceptKey.getVersion().split("\\."); + + // There must always be at least one element in each version + if (!thisVersionArray[0].equals(otherVersionArray[0])) { + return thisVersionArray[0].compareTo(otherVersionArray[0]) > 0; + } + + if (thisVersionArray.length >= 2 && otherVersionArray.length >= 2 + && !thisVersionArray[1].equals(otherVersionArray[1])) { + return thisVersionArray[1].compareTo(otherVersionArray[1]) > 0; + } + + if (thisVersionArray.length >= 3 && otherVersionArray.length >= 3 + && !thisVersionArray[2].equals(otherVersionArray[2])) { + return thisVersionArray[2].compareTo(otherVersionArray[2]) > 0; + } + + return false; + } + + @Override + public int getMajorVersion() { + final String[] versionArray = getVersion().split("\\."); + + // There must always be at least one element in each version + return Integer.parseInt(versionArray[0]); + } + + @Override + public int getMinorVersion() { + final String[] versionArray = getVersion().split("\\."); + + if (versionArray.length >= 2) { + return Integer.parseInt(versionArray[1]); + } + else { + return 0; + } + } + + @Override + public int getPatchVersion() { + final String[] versionArray = getVersion().split("\\."); + + if (versionArray.length >= 3) { + return Integer.parseInt(versionArray[2]); + } + else { + return 0; + } + } + + @Override public PfValidationResult validate(final PfValidationResult result) { final String nameValidationErrorMessage = Assertions.getStringParameterValidationMessage(NAME_TOKEN, name, NAME_REGEXP); diff --git a/models-base/src/main/java/org/onap/policy/models/base/PfKey.java b/models-base/src/main/java/org/onap/policy/models/base/PfKey.java index 6e9035e95..5407030ba 100644 --- a/models-base/src/main/java/org/onap/policy/models/base/PfKey.java +++ b/models-base/src/main/java/org/onap/policy/models/base/PfKey.java @@ -102,9 +102,38 @@ public abstract class PfKey extends PfConcept { public abstract boolean isCompatible(@NonNull PfKey otherKey); /** + * Check if this key is a newer version than the other key. + * + * @param otherKey the key to check against + * @return true, if this key is newer than the other key + */ + public abstract boolean isNewerThan(@NonNull PfKey otherKey); + + /** * Check if a key equals its null key. * * @return true, if the key is a null key */ public abstract boolean isNullKey(); + + /** + * Get the major version of a key. + * + * @return the major version of a key + */ + public abstract int getMajorVersion(); + + /** + * Get the minor version of a key. + * + * @return the minor version of a key + */ + public abstract int getMinorVersion(); + + /** + * Get the patch version of a key. + * + * @return the patch version of a key + */ + public abstract int getPatchVersion(); } 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 57141c2fa..836707ef2 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 @@ -111,6 +111,26 @@ public class PfKeyUse extends PfKey { } @Override + public boolean isNewerThan(@NonNull final PfKey otherKey) { + return usedKey.isCompatible(otherKey); + } + + @Override + public int getMajorVersion() { + return usedKey.getMajorVersion(); + } + + @Override + public int getMinorVersion() { + return usedKey.getMinorVersion(); + } + + @Override + public int getPatchVersion() { + return usedKey.getPatchVersion(); + } + + @Override public void clean() { usedKey.clean(); } diff --git a/models-base/src/main/java/org/onap/policy/models/base/PfModelException.java b/models-base/src/main/java/org/onap/policy/models/base/PfModelException.java index ce44e51f3..46c5bd311 100644 --- a/models-base/src/main/java/org/onap/policy/models/base/PfModelException.java +++ b/models-base/src/main/java/org/onap/policy/models/base/PfModelException.java @@ -25,18 +25,20 @@ import javax.ws.rs.core.Response; import lombok.Getter; import lombok.ToString; -import org.apache.commons.lang3.exception.ExceptionUtils; +import org.onap.policy.models.errors.concepts.ErrorResponse; +import org.onap.policy.models.errors.concepts.ErrorResponseInfo; +import org.onap.policy.models.errors.concepts.ErrorResponseUtils; /** * This class is a base exception from which all model exceptions are sub classes. */ @Getter @ToString -public class PfModelException extends Exception implements PfModelExceptionInfo { +public class PfModelException extends Exception implements ErrorResponseInfo { private static final long serialVersionUID = -8507246953751956974L; - // The status code on the exception - private final Response.Status statusCode; + // The error response of the exception + private final ErrorResponse errorResponse = new ErrorResponse(); // The object on which the exception was thrown private final transient Object object; @@ -60,7 +62,8 @@ public class PfModelException extends Exception implements PfModelExceptionInfo */ public PfModelException(final Response.Status statusCode, final String message, final Object object) { super(message); - this.statusCode = statusCode; + errorResponse.setResponseCode(statusCode); + ErrorResponseUtils.getExceptionMessages(errorResponse, this); this.object = object; } @@ -86,45 +89,8 @@ public class PfModelException extends Exception implements PfModelExceptionInfo public PfModelException(final Response.Status statusCode, final String message, final Exception exception, final Object object) { super(message, exception); - this.statusCode = statusCode; + errorResponse.setResponseCode(statusCode); + ErrorResponseUtils.getExceptionMessages(errorResponse, this); this.object = object; } - - /** - * Get the message from this exception and its causes. - * - * @return the cascaded messages from this exception and the exceptions that caused it - */ - @Override - public String getCascadedMessage() { - return buildCascadedMessage(this); - } - - /** - * Build a cascaded message from an exception and all its nested exceptions. - * - * @param throwable the top level exception - * @return cascaded message string - */ - public static String buildCascadedMessage(Throwable throwable) { - final StringBuilder builder = new StringBuilder(); - builder.append(throwable.getMessage()); - - for (Throwable t = throwable; t != null; t = t.getCause()) { - builder.append("\ncaused by: "); - builder.append(t.getMessage()); - } - - return builder.toString(); - } - - /** - * Get the stack trace of the exception as a string. - * - * @return the stack trace of this message as a string - */ - @Override - public String getStackTraceAsString() { - return ExceptionUtils.getStackTrace(this); - } } diff --git a/models-base/src/main/java/org/onap/policy/models/base/PfModelExceptionInfo.java b/models-base/src/main/java/org/onap/policy/models/base/PfModelExceptionInfo.java deleted file mode 100644 index 2fe244cec..000000000 --- a/models-base/src/main/java/org/onap/policy/models/base/PfModelExceptionInfo.java +++ /dev/null @@ -1,59 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 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 javax.ws.rs.core.Response; - -/** - * Interface implemented bu Policy framework model exceptions to allow uniform reading of status codes and cascaded - * messages. - * - * @author Liam Fallon (liam.fallon@est.tech) - */ -public interface PfModelExceptionInfo { - - /** - * Get the status code associated with an exception. - * @return the status code - */ - public Response.Status getStatusCode(); - - /** - * Get the messages for all the cascaded exceptions in an exception. - * - * @return the cascaded message - */ - public String getCascadedMessage(); - - /** - * Get the object associated with an exception. - * - * @return the object associated with an exception - */ - public Object getObject(); - - /** - * Get the stack trace of the exception as a string. - * - * @return the stack trace of this message as a string - */ - public String getStackTraceAsString(); -} diff --git a/models-base/src/main/java/org/onap/policy/models/base/PfModelRuntimeException.java b/models-base/src/main/java/org/onap/policy/models/base/PfModelRuntimeException.java index 32855c2a4..472412865 100644 --- a/models-base/src/main/java/org/onap/policy/models/base/PfModelRuntimeException.java +++ b/models-base/src/main/java/org/onap/policy/models/base/PfModelRuntimeException.java @@ -25,18 +25,20 @@ import javax.ws.rs.core.Response; import lombok.Getter; import lombok.ToString; -import org.apache.commons.lang3.exception.ExceptionUtils; +import org.onap.policy.models.errors.concepts.ErrorResponse; +import org.onap.policy.models.errors.concepts.ErrorResponseInfo; +import org.onap.policy.models.errors.concepts.ErrorResponseUtils; /** * This class is a base model run time exception from which all model run time exceptions are sub classes. */ @Getter @ToString -public class PfModelRuntimeException extends RuntimeException implements PfModelExceptionInfo { +public class PfModelRuntimeException extends RuntimeException implements ErrorResponseInfo { private static final long serialVersionUID = -8507246953751956974L; - // The return code on the exception - private final Response.Status statusCode; + // The error response of the exception + private final ErrorResponse errorResponse = new ErrorResponse(); // The object on which the exception was thrown private final transient Object object; @@ -61,7 +63,8 @@ public class PfModelRuntimeException extends RuntimeException implements PfModel public PfModelRuntimeException(final Response.Status statusCode, final String message, final Object object) { super(message); this.object = object; - this.statusCode = statusCode; + errorResponse.setResponseCode(statusCode); + ErrorResponseUtils.getExceptionMessages(errorResponse, this); } /** @@ -87,26 +90,7 @@ public class PfModelRuntimeException extends RuntimeException implements PfModel final Object object) { super(message, exception); this.object = object; - this.statusCode = statusCode; - } - - /** - * Get the message from this exception and its causes. - * - * @return the message of this exception and all the exceptions that caused this exception - */ - @Override - public String getCascadedMessage() { - return PfModelException.buildCascadedMessage(this); - } - - /** - * Get the stack trace of the exception as a string. - * - * @return the stack trace of this message as a string - */ - @Override - public String getStackTraceAsString() { - return ExceptionUtils.getStackTrace(this); + errorResponse.setResponseCode(statusCode); + ErrorResponseUtils.getExceptionMessages(errorResponse, this); } } 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 19e8beee9..185ccfa69 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 @@ -28,6 +28,7 @@ import javax.persistence.Embeddable; import lombok.Data; import lombok.EqualsAndHashCode; +import lombok.NonNull; import org.onap.policy.common.utils.validation.Assertions; import org.onap.policy.models.base.PfValidationResult.ValidationResult; @@ -305,7 +306,7 @@ public class PfReferenceKey extends PfKey { } @Override - public boolean isCompatible(final PfKey otherKey) { + public boolean isCompatible(@NonNull final PfKey otherKey) { if (!(otherKey instanceof PfReferenceKey)) { return false; } @@ -315,6 +316,31 @@ public class PfReferenceKey extends PfKey { } @Override + public int getMajorVersion() { + return this.getParentConceptKey().getMajorVersion(); + } + + @Override + public int getMinorVersion() { + return this.getParentConceptKey().getMinorVersion(); + } + + @Override + public int getPatchVersion() { + return this.getParentConceptKey().getPatchVersion(); + } + + + @Override + public boolean isNewerThan(@NonNull final PfKey otherKey) { + Assertions.instanceOf(otherKey, PfReferenceKey.class); + + final PfReferenceKey otherReferenceKey = (PfReferenceKey) otherKey; + + return this.getParentConceptKey().isNewerThan(otherReferenceKey.getParentConceptKey()); + } + + @Override public PfValidationResult validate(final PfValidationResult result) { final String parentNameValidationErrorMessage = Assertions.getStringParameterValidationMessage(PARENT_KEY_NAME, parentKeyName, NAME_REGEXP); diff --git a/models-base/src/main/java/org/onap/policy/models/base/PfUtils.java b/models-base/src/main/java/org/onap/policy/models/base/PfUtils.java index 8e77d3fcf..7bdd9a5f4 100644 --- a/models-base/src/main/java/org/onap/policy/models/base/PfUtils.java +++ b/models-base/src/main/java/org/onap/policy/models/base/PfUtils.java @@ -21,6 +21,7 @@ package org.onap.policy.models.base; +import java.util.ArrayList; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; @@ -72,7 +73,7 @@ public final class PfUtils { */ public static <T> List<T> mapList(List<T> source, Function<T, T> mapFunc) { if (source == null) { - return null; + return new ArrayList<>(); } return source.stream().map(mapFunc).collect(Collectors.toList()); 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 new file mode 100644 index 000000000..7a0a8377b --- /dev/null +++ b/models-base/src/main/java/org/onap/policy/models/base/Validated.java @@ -0,0 +1,253 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.models.base; + +import java.util.Collection; +import java.util.Map; +import java.util.Map.Entry; +import lombok.NonNull; +import org.onap.policy.common.utils.validation.Assertions; +import org.onap.policy.models.base.PfValidationResult.ValidationResult; + +/** + * Classes that can be validated. This can be used as a super class or as a stand-alone + * utility class. + */ +public class Validated { + + /** + * Validates the fields of the object. The default method simply returns the result. + * + * @param result where to place the result + * @return the result + */ + public PfValidationResult validate(@NonNull PfValidationResult result) { + return result; + } + + /** + * Validates that a field value is not 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 + */ + public PfValidationResult validateNotNull(@NonNull Object container, @NonNull String fieldName, Object value, + @NonNull PfValidationResult result) { + + if (value == null) { + addError(container, fieldName, result, "null"); + } + + return result; + } + + /** + * Validates that the name and version of a concept key do not have the null default + * values. + * + * @param value value to be validated + * @param result where to place the result + * @return the result + */ + public PfValidationResult validateNotNull(@NonNull PfConceptKey value, @NonNull PfValidationResult result) { + + if (PfConceptKey.NULL_KEY_NAME.equals(value.getName())) { + addError(value, "name", result, "null"); + } + + if (PfConceptKey.NULL_KEY_VERSION.equals(value.getVersion())) { + addError(value, "version", result, "null"); + } + + return result; + } + + /** + * Validates the contents of a field, verifying that it matches a pattern, if it is + * non-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 pattern pattern used to validate the value + * @param result where to place the result + * @return the result + */ + public PfValidationResult validateText(@NonNull Object container, @NonNull String fieldName, String value, + @NonNull String pattern, @NonNull PfValidationResult result) { + + if (value != null) { + addError(container, fieldName, result, + Assertions.getStringParameterValidationMessage(fieldName, value, pattern)); + } + + return result; + } + + /** + * Validates the contents of a property field, verifying that the keys ands values are + * non-null. + * + * @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 + */ + public <T> PfValidationResult validatePropertiesNotNull(@NonNull Object container, @NonNull String fieldName, + Map<String, T> properties, @NonNull PfValidationResult resultIn) { + + PfValidationResult result = resultIn; + + if (properties == null) { + return result; + } + + for (Entry<String, T> ent : properties.entrySet()) { + String key = ent.getKey(); + String keyName = fieldName + "." + key; + result = validateNotNull(container, keyName, key, result); + + result = validateNotNull(container, keyName, ent.getValue(), result); + } + + return result; + } + + /** + * Validates the items in a collection field are non-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 resultIn where to place the result + * @return the result + */ + public <T> PfValidationResult validateCollectionNotNull(@NonNull Object container, @NonNull String fieldName, + Collection<T> collection, @NonNull PfValidationResult resultIn) { + + PfValidationResult result = resultIn; + + if (collection == null) { + return result; + } + + String prefix = fieldName + "."; + int count = 0; + + for (T item : collection) { + result = validateNotNull(container, prefix + count, item, result); + ++count; + } + + return result; + } + + /** + * Invokes the "validate()" method on each item in a collection field, if the item is + * non-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 + */ + public <T extends Validated> PfValidationResult validateCollection(@NonNull Object container, + @NonNull String fieldName, Collection<T> collection, @NonNull PfValidationResult result) { + + if (collection == null) { + return result; + } + + for (T item : collection) { + if (item != null) { + result = item.validate(result); + } + } + + return result; + } + + /** + * Invokes the "validate()" method on each item in a concept collection field, if the + * item is non-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 + */ + public <T extends PfConcept> PfValidationResult validateConceptCollection(@NonNull Object container, + @NonNull String fieldName, Collection<T> collection, @NonNull PfValidationResult result) { + + if (collection == null) { + return result; + } + + for (T item : collection) { + if (item != null) { + result = item.validate(result); + } + } + + return result; + } + + /** + * Adds an error message to the validation result. + * + * @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 + */ + 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)); + } + } + + /** + * Makes a PfKey suitable for insertion into a validation message. Note: the + * "toString()" method of the key simply invokes container.toString(); + * + * @param container the container object for which the key should be made + * @return a key for the container + */ + public PfKey makeKey(@NonNull Object container) { + + return new PfConceptKey() { + private static final long serialVersionUID = 1L; + + @Override + public String toString() { + return container.toString(); + } + }; + } +} diff --git a/models-base/src/main/java/org/onap/policy/models/base/keys/PolicyTypeIdent.java b/models-base/src/main/java/org/onap/policy/models/base/keys/PolicyTypeIdent.java deleted file mode 100644 index 09e03816e..000000000 --- a/models-base/src/main/java/org/onap/policy/models/base/keys/PolicyTypeIdent.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP Policy Models - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.models.base.keys; - -import lombok.NoArgsConstructor; -import lombok.NonNull; -import org.onap.policy.models.base.PfConceptKey; - -/** - * Identifies a policy type. Both the name and version must be non-null. - */ -@NonNull -@NoArgsConstructor -public class PolicyTypeIdent extends PfConceptKey { - private static final long serialVersionUID = 1L; - - public PolicyTypeIdent(String name, String version) { - super(name, version); - } - - public PolicyTypeIdent(PolicyTypeIdent source) { - super(source); - } -} diff --git a/models-base/src/test/java/org/onap/policy/models/base/ExceptionsTest.java b/models-base/src/test/java/org/onap/policy/models/base/ExceptionsTest.java index 0a5b6a0a6..664e3ddbc 100644 --- a/models-base/src/test/java/org/onap/policy/models/base/ExceptionsTest.java +++ b/models-base/src/test/java/org/onap/policy/models/base/ExceptionsTest.java @@ -28,6 +28,7 @@ import java.io.IOException; import javax.ws.rs.core.Response; import org.junit.Test; +import org.onap.policy.models.errors.concepts.ErrorResponse; public class ExceptionsTest { @@ -41,7 +42,8 @@ public class ExceptionsTest { String key = "A String"; PfModelException ae = new PfModelException(Response.Status.OK, "Message", new IOException("IO exception message"), key); - assertEquals("Message\ncaused by: Message\ncaused by: IO exception message", ae.getCascadedMessage()); + ErrorResponse errorResponse = ae.getErrorResponse(); + assertEquals("Message\nIO exception message", String.join("\n", errorResponse.getErrorDetails())); assertEquals(key, ae.getObject()); assertNotNull(new PfModelRuntimeException(Response.Status.OK, "Message")); @@ -52,8 +54,9 @@ public class ExceptionsTest { String rkey = "A String"; PfModelRuntimeException re = new PfModelRuntimeException(Response.Status.OK, "Runtime Message", new IOException("IO runtime exception message"), rkey); - assertEquals("Runtime Message\ncaused by: Runtime Message\ncaused by: IO runtime exception message", - re.getCascadedMessage()); + errorResponse = re.getErrorResponse(); + assertEquals("Runtime Message\nIO runtime exception message", + String.join("\n", errorResponse.getErrorDetails())); assertEquals(key, re.getObject()); } } diff --git a/models-base/src/test/java/org/onap/policy/models/base/PfKeyTest.java b/models-base/src/test/java/org/onap/policy/models/base/PfKeyTest.java index 848889cc3..a4c504788 100644 --- a/models-base/src/test/java/org/onap/policy/models/base/PfKeyTest.java +++ b/models-base/src/test/java/org/onap/policy/models/base/PfKeyTest.java @@ -42,9 +42,10 @@ public class PfKeyTest { new PfConceptKey("some bad key id"); fail("This test should throw an exception"); } catch (IllegalArgumentException e) { - assertEquals("parameter \"id\": value \"some bad key id\", " + assertEquals( + "parameter \"id\": value \"some bad key id\", " + "does not match regular expression \"[A-Za-z0-9\\-_\\.]+:[0-9].[0-9].[0-9]\"", - e.getMessage()); + e.getMessage()); } PfConceptKey someKey0 = new PfConceptKey(); @@ -110,19 +111,19 @@ public class PfKeyTest { assertFalse(someKey1.isCompatible(new DummyPfKey())); assertEquals(PfValidationResult.ValidationResult.VALID, - someKey0.validate(new PfValidationResult()).getValidationResult()); + someKey0.validate(new PfValidationResult()).getValidationResult()); assertEquals(PfValidationResult.ValidationResult.VALID, - someKey1.validate(new PfValidationResult()).getValidationResult()); + someKey1.validate(new PfValidationResult()).getValidationResult()); assertEquals(PfValidationResult.ValidationResult.VALID, - someKey2.validate(new PfValidationResult()).getValidationResult()); + someKey2.validate(new PfValidationResult()).getValidationResult()); assertEquals(PfValidationResult.ValidationResult.VALID, - someKey3.validate(new PfValidationResult()).getValidationResult()); + someKey3.validate(new PfValidationResult()).getValidationResult()); assertEquals(PfValidationResult.ValidationResult.VALID, - someKey4.validate(new PfValidationResult()).getValidationResult()); + someKey4.validate(new PfValidationResult()).getValidationResult()); assertEquals(PfValidationResult.ValidationResult.VALID, - someKey5.validate(new PfValidationResult()).getValidationResult()); + someKey5.validate(new PfValidationResult()).getValidationResult()); assertEquals(PfValidationResult.ValidationResult.VALID, - someKey6.validate(new PfValidationResult()).getValidationResult()); + someKey6.validate(new PfValidationResult()).getValidationResult()); someKey0.clean(); assertNotNull(someKey0.toString()); @@ -150,14 +151,14 @@ public class PfKeyTest { @Test public void testNullArguments() { try { - new PfConceptKey((String)null); + new PfConceptKey((String) null); fail("test should throw an exception here"); } catch (Exception exc) { assertEquals("id is marked @NonNull but is null", exc.getMessage()); } try { - new PfConceptKey((PfConceptKey)null); + new PfConceptKey((PfConceptKey) null); fail("id is marked @NonNull but is null"); } catch (Exception exc) { assertEquals("copyConcept is marked @NonNull but is null", exc.getMessage()); @@ -207,9 +208,9 @@ public class PfKeyTest { nameField.set(testKey, "TheKey"); nameField.setAccessible(false); assertEquals( - "name invalid-parameter name with value Key Name " - + "does not match regular expression [A-Za-z0-9\\-_\\.]+", - validationResult.getMessageList().get(0).getMessage()); + "name invalid-parameter name with value Key Name " + + "does not match regular expression [A-Za-z0-9\\-_\\.]+", + validationResult.getMessageList().get(0).getMessage()); } catch (Exception validationException) { fail("test should not throw an exception"); } @@ -223,11 +224,105 @@ public class PfKeyTest { versionField.set(testKey, "0.0.1"); versionField.setAccessible(false); assertEquals( - "version invalid-parameter version with value Key Version " - + "does not match regular expression [A-Za-z0-9.]+", - validationResult.getMessageList().get(0).getMessage()); + "version invalid-parameter version with value Key Version " + + "does not match regular expression [A-Za-z0-9.]+", + validationResult.getMessageList().get(0).getMessage()); } catch (Exception validationException) { fail("test should not throw an exception"); } } + + @Test + public void testkeynewerThan() { + PfConceptKey key1 = new PfConceptKey("Key1", "1.2.3"); + + try { + key1.isNewerThan(null); + fail("test should throw an exception"); + } catch (Exception exc) { + assertEquals("otherKey is marked @NonNull but is null", exc.getMessage()); + } + + try { + key1.isNewerThan(new PfReferenceKey()); + fail("test should throw an exception"); + } catch (Exception exc) { + assertEquals("org.onap.policy.models.base.PfReferenceKey is not " + + "an instance of org.onap.policy.models.base.PfConceptKey", exc.getMessage()); + } + + assertFalse(key1.isNewerThan(key1)); + + PfConceptKey key1a = new PfConceptKey("Key1a", "1.2.3"); + assertFalse(key1.isNewerThan(key1a)); + + PfConceptKey key1b = new PfConceptKey("Key0", "1.2.3"); + assertTrue(key1.isNewerThan(key1b)); + + key1a.setName("Key1"); + assertFalse(key1.isNewerThan(key1a)); + + key1a.setVersion("0.2.3"); + assertTrue(key1.isNewerThan(key1a)); + key1a.setVersion("2.2.3"); + assertFalse(key1.isNewerThan(key1a)); + key1a.setVersion("1.2.3"); + assertFalse(key1.isNewerThan(key1a)); + + key1a.setVersion("1.1.3"); + assertTrue(key1.isNewerThan(key1a)); + key1a.setVersion("1.3.3"); + assertFalse(key1.isNewerThan(key1a)); + key1a.setVersion("1.2.3"); + assertFalse(key1.isNewerThan(key1a)); + + key1a.setVersion("1.2.2"); + assertTrue(key1.isNewerThan(key1a)); + key1a.setVersion("1.2.4"); + assertFalse(key1.isNewerThan(key1a)); + key1a.setVersion("1.2.3"); + assertFalse(key1.isNewerThan(key1a)); + + key1.setVersion("1"); + assertFalse(key1.isNewerThan(key1a)); + key1a.setVersion("1"); + assertFalse(key1.isNewerThan(key1a)); + + PfReferenceKey refKey = new PfReferenceKey(); + + try { + refKey.isNewerThan(null); + fail("test should throw an exception"); + } catch (Exception exc) { + assertEquals("otherKey is marked @NonNull but is null", exc.getMessage()); + } + + try { + refKey.isNewerThan(new PfConceptKey()); + fail("test should throw an exception"); + } catch (Exception exc) { + assertEquals("org.onap.policy.models.base.PfConceptKey is not " + + "an instance of org.onap.policy.models.base.PfReferenceKey", exc.getMessage()); + } + + assertFalse(refKey.isNewerThan(refKey)); + } + + @Test + public void testmajorMinorPatch() { + PfConceptKey key = new PfConceptKey("Key", "1"); + assertEquals(1, key.getMajorVersion()); + assertEquals(0, key.getMinorVersion()); + assertEquals(0, key.getPatchVersion()); + + key = new PfConceptKey("Key", "1.2"); + assertEquals(1, key.getMajorVersion()); + assertEquals(2, key.getMinorVersion()); + assertEquals(0, key.getPatchVersion()); + + key = new PfConceptKey("Key", "1.2.3"); + assertEquals(1, key.getMajorVersion()); + assertEquals(2, key.getMinorVersion()); + assertEquals(3, key.getPatchVersion()); + } } 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 ccdc72dcd..72df28f04 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 @@ -131,5 +131,9 @@ public class PfKeyUseTest { } catch (Exception exc) { assertEquals("error copying concept key: Some error message", exc.getMessage()); } + + assertEquals(0, testKeyUse.getMajorVersion()); + assertEquals(0, testKeyUse.getMinorVersion()); + assertEquals(0, testKeyUse.getPatchVersion()); } } diff --git a/models-base/src/test/java/org/onap/policy/models/base/PfModelExceptionInfoTest.java b/models-base/src/test/java/org/onap/policy/models/base/PfModelExceptionInfoTest.java index 1257975ad..183b44c13 100644 --- a/models-base/src/test/java/org/onap/policy/models/base/PfModelExceptionInfoTest.java +++ b/models-base/src/test/java/org/onap/policy/models/base/PfModelExceptionInfoTest.java @@ -25,6 +25,7 @@ import static org.junit.Assert.assertEquals; import javax.ws.rs.core.Response; import org.junit.Test; +import org.onap.policy.models.errors.concepts.ErrorResponseInfo; /** * Test PfModelExceptionInfo interface. @@ -49,15 +50,15 @@ public class PfModelExceptionInfoTest { } } - private String getErrorMessage(final PfModelExceptionInfo pfme) { + private String getErrorMessage(final ErrorResponseInfo eri) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Server returned: "); - stringBuilder.append(pfme.getStatusCode().toString()); + stringBuilder.append(eri.getErrorResponse().getResponseCode().toString()); + stringBuilder.append("Error Message:\n"); + stringBuilder.append(eri.getErrorResponse().getErrorMessage()); stringBuilder.append("\nDetailed Message:\n"); - stringBuilder.append(pfme.getCascadedMessage()); - stringBuilder.append("\nStack Trace:\n"); - stringBuilder.append(pfme.getStackTraceAsString()); + stringBuilder.append(String.join("\n", eri.getErrorResponse().getErrorDetails())); return stringBuilder.toString(); } 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 64d4bc6b8..edf4466f8 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 @@ -58,6 +58,10 @@ public class PfReferenceKeyTest { testReferenceKey.setParentConceptKey(new PfConceptKey("PN", "0.0.1")); assertEquals("PN:0.0.1", testReferenceKey.getParentConceptKey().getId()); + assertEquals(0, testReferenceKey.getMajorVersion()); + assertEquals(0, testReferenceKey.getMinorVersion()); + assertEquals(1, testReferenceKey.getPatchVersion()); + assertEquals(1, testReferenceKey.getKeys().size()); assertFalse(testReferenceKey.isNullKey()); @@ -76,6 +80,13 @@ public class PfReferenceKeyTest { testReferenceKey.setLocalName("NLN"); assertEquals("NLN", testReferenceKey.getLocalName()); + try { + testReferenceKey.isCompatible(null); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("otherKey is marked @NonNull but is null", exc.getMessage()); + } + assertFalse(testReferenceKey.isCompatible(PfConceptKey.getNullKey())); assertFalse(testReferenceKey.isCompatible(PfReferenceKey.getNullKey())); assertTrue(testReferenceKey.isCompatible(testReferenceKey)); diff --git a/models-base/src/test/java/org/onap/policy/models/base/PfUtilsTest.java b/models-base/src/test/java/org/onap/policy/models/base/PfUtilsTest.java index bdbab5c36..11ddf3132 100644 --- a/models-base/src/test/java/org/onap/policy/models/base/PfUtilsTest.java +++ b/models-base/src/test/java/org/onap/policy/models/base/PfUtilsTest.java @@ -1,4 +1,4 @@ -/* +/*- * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. @@ -23,7 +23,7 @@ package org.onap.policy.models.base; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.List; @@ -47,9 +47,10 @@ public class PfUtilsTest { @Test public void testMapList() { - assertNull(PfUtils.mapList(null, item -> { + List<Object> resultList = PfUtils.mapList(null, item -> { throw new RuntimeException("should not be invoked"); - })); + }); + assertTrue(resultList.isEmpty()); List<String> origList = Arrays.asList("abc", "def"); List<String> newList = PfUtils.mapList(origList, text -> text + "X"); 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 new file mode 100644 index 000000000..391e7333b --- /dev/null +++ b/models-base/src/test/java/org/onap/policy/models/base/ValidatedTest.java @@ -0,0 +1,441 @@ +/* + * ============LICENSE_START======================================================= + * ONAP Policy Models + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.models.base; + +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.List; +import java.util.Map; +import org.junit.Before; +import org.junit.Test; + +public class ValidatedTest { + 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(); + } + + @Test + public void testValidate() { + assertThatThrownBy(() -> validated.validate(null)).isInstanceOf(NullPointerException.class); + + PfValidationResult result = new PfValidationResult(); + assertSame(result, validated.validate(result)); + assertTrue(result.isValid()); + assertEquals(0, result.getMessageList().size()); + } + + @Test + public void testValidateNotNull() { + PfValidationResult result = new PfValidationResult(); + + final PfValidationResult result2 = result; + assertThatThrownBy(() -> validated.validateNotNull(null, VALID_FIELD, VALID_VALUE, result2)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy(() -> validated.validateNotNull(this, null, VALID_VALUE, result2)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy(() -> validated.validateNotNull(this, VALID_FIELD, VALID_VALUE, null)) + .isInstanceOf(NullPointerException.class); + + // null text + result = validated.validateNotNull(this, NULL_FIELD, null, result); + + // invalid text + result = validated.validateNotNull(this, INVALID_FIELD, "!!!", result); + + // valid text + result = validated.validateNotNull(this, VALID_FIELD, VALID_VALUE, result); + + // different value + result = validated.validateNotNull(this, VALID_FIELD, Integer.valueOf(10), result); + + assertFalse(result.isValid()); + assertEquals(1, result.getMessageList().size()); + + // 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")); + } + + @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")); + + final PfConceptKey key2 = key; + assertThatThrownBy(() -> validated.validateNotNull(key2, null)).isInstanceOf(NullPointerException.class); + assertThatThrownBy(() -> validated.validateNotNull(null, new PfValidationResult())) + .isInstanceOf(NullPointerException.class); + } + + @Test + public void testValidateText() { + PfValidationResult result = new PfValidationResult(); + + 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); + + // null text + result = validated.validateText(this, NULL_FIELD, null, WORD_PAT, result); + + // invalid text + result = validated.validateText(this, INVALID_FIELD, "!!!", WORD_PAT, result); + + // valid text + result = validated.validateText(this, VALID_FIELD, VALID_VALUE, WORD_PAT, result); + + assertFalse(result.isValid()); + assertEquals(1, result.getMessageList().size()); + + // 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")); + } + + @Test + public void testValidatePropertiesNotNull() { + PfValidationResult result = new PfValidationResult(); + result = validated.validatePropertiesNotNull(this, "properties", null, result); + assertTrue(result.isValid()); + assertEquals(0, result.getMessageList().size()); + + Map<String, Integer> map = new LinkedHashMap<>(); + + // null key + map.put(null, 10); + + // null value + map.put("abc", null); + + // valid key & value + map.put("def", 11); + + + result = validated.validatePropertiesNotNull(this, PROPS_FIELD, map, result); + + assertFalse(result.isValid()); + assertEquals(2, result.getMessageList().size()); + + Iterator<PfValidationMessage> it = result.getMessageList().iterator(); + + // 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")); + + // 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")); + + 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); + } + + @Test + public void testValidateCollectionNotNull() { + PfValidationResult result = new PfValidationResult(); + result = validated.validateCollectionNotNull(this, "collection", null, result); + assertTrue(result.isValid()); + assertEquals(0, result.getMessageList().size()); + + final List<String> lst = Arrays.asList("abc", null, "def", null); + + result = validated.validateCollectionNotNull(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(ValidatedTest.class.getName(), msg.getObservedClass()); + assertEquals(MY_TO_STRING, msg.getObservedKey().toString()); + assertTrue(msg.getMessage().contains("coll.1 invalid-null")); + + // 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); + } + + @Test + public void testValidateCollection() { + PfValidationResult result = new PfValidationResult(); + result = validated.validateCollection(this, "collection", 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().replace('$', '.'), 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().replace('$', '.'), 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)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy(() -> validated.validateCollection(this, null, lst, result2)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy(() -> validated.validateCollection(this, COLLECTION_FIELD, lst, null)) + .isInstanceOf(NullPointerException.class); + } + + @Test + public void testValidateConceptCollection() { + PfValidationResult result = new PfValidationResult(); + result = validated.validateConceptCollection(this, "collection", 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().replace('$', '.'), 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().replace('$', '.'), 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)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy(() -> validated.validateConceptCollection(this, null, lst, result2)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy(() -> validated.validateConceptCollection(this, COLLECTION_FIELD, lst, null)) + .isInstanceOf(NullPointerException.class); + } + + @Test + public void testAddError() { + final PfValidationResult result = new PfValidationResult(); + final PfValidationResult result2 = result; + + 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"); + + assertFalse(result.isValid()); + assertEquals(2, result.getMessageList().size()); + + Iterator<PfValidationMessage> it = result.getMessageList().iterator(); + + 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")); + + msg = it.next(); + assertEquals(ValidatedTest.class.getName(), msg.getObservedClass()); + assertEquals(MY_TO_STRING, msg.getObservedKey().toString()); + assertTrue(msg.getMessage().contains("validField invalid-error-B")); + } + + @Test + public void testMakeKey() { + assertThatThrownBy(() -> validated.makeKey(null)).isInstanceOf(NullPointerException.class); + + PfKey key = validated.makeKey(this); + assertEquals(MY_TO_STRING, key.toString()); + } + + @Override + public String toString() { + return MY_TO_STRING; + } + + private static class MyValid extends Validated { + private boolean valid; + private int index; + + public MyValid(int index, boolean valid) { + this.index = index; + this.valid = valid; + } + + @Override + public PfValidationResult validate(PfValidationResult result) { + if (!valid) { + this.addError(this, "index." + index, result, "wrong value"); + } + + return result; + } + + @Override + public String toString() { + return MY_TO_STRING; + } + } + + private static class MyConcept extends PfConceptKey { + private static final long serialVersionUID = 1L; + + private boolean valid; + private int index; + + public MyConcept(int index, boolean valid) { + this.index = index; + this.valid = valid; + } + + @Override + public PfValidationResult validate(PfValidationResult result) { + if (!valid) { + new Validated().addError(this, "index." + index, result, "wrong value"); + } + + return result; + } + + @Override + public String toString() { + return MY_TO_STRING; + } + } +} diff --git a/models-base/src/test/java/org/onap/policy/models/base/keys/TestModels.java b/models-base/src/test/java/org/onap/policy/models/base/keys/TestModels.java deleted file mode 100644 index a1bf3be68..000000000 --- a/models-base/src/test/java/org/onap/policy/models/base/keys/TestModels.java +++ /dev/null @@ -1,46 +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.keys; - -import com.openpojo.reflection.filters.FilterPackageInfo; -import com.openpojo.validation.Validator; -import com.openpojo.validation.ValidatorBuilder; -import com.openpojo.validation.test.impl.GetterTester; -import com.openpojo.validation.test.impl.SetterTester; - -import org.junit.Test; -import org.onap.policy.common.utils.validation.ToStringTester; - -/** - * Class to perform unit testing of models. - * - * @author Ram Krishna Verma (ram.krishna.verma@est.tech) - */ -public class TestModels { - - @Test - public void testModels() { - final Validator validator = ValidatorBuilder.create().with(new ToStringTester()).with(new SetterTester()) - .with(new GetterTester()).build(); - validator.validate(TestModels.class.getPackage().getName(), new FilterPackageInfo()); - } -} diff --git a/models-base/src/test/java/org/onap/policy/models/base/keys/TestPolicyTypeIdent.java b/models-base/src/test/java/org/onap/policy/models/base/keys/TestPolicyTypeIdent.java deleted file mode 100644 index 1638a87da..000000000 --- a/models-base/src/test/java/org/onap/policy/models/base/keys/TestPolicyTypeIdent.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP Policy Models - * ================================================================================ - * 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. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.models.base.keys; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; - -import org.junit.Test; -import org.onap.policy.models.base.keys.PolicyTypeIdent; -import org.onap.policy.models.base.keys.TestModels; - -/** - * Test the other constructors, as {@link TestModels} tests the other methods. - */ -public class TestPolicyTypeIdent { - private static final String NAME = "my-name"; - private static final String VERSION = "1.2.3"; - - @Test - public void testAllArgsConstructor() { - assertThatThrownBy(() -> new PolicyTypeIdent(null, VERSION)).isInstanceOf(NullPointerException.class); - assertThatThrownBy(() -> new PolicyTypeIdent(NAME, null)).isInstanceOf(NullPointerException.class); - - PolicyTypeIdent orig = new PolicyTypeIdent(NAME, VERSION); - assertEquals(NAME, orig.getName()); - assertEquals(VERSION, orig.getVersion()); - } - - @Test - public void testCopyConstructor() { - assertThatThrownBy(() -> new PolicyTypeIdent(null)).isInstanceOf(NullPointerException.class); - - PolicyTypeIdent orig = new PolicyTypeIdent(); - - // verify with null values - assertEquals(orig.toString(), new PolicyTypeIdent(orig).toString()); - - // verify with all values - orig = new PolicyTypeIdent(NAME, VERSION); - assertEquals(orig.toString(), new PolicyTypeIdent(orig).toString()); - } -} 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 6cf41e60c..f485b0d0f 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 @@ -23,11 +23,13 @@ package org.onap.policy.models.base.testconcepts; import java.util.Arrays; import java.util.List; +import lombok.NonNull; + 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 { +public class DummyPfKey extends PfKey { private static final long serialVersionUID = 1L; @Override @@ -94,4 +96,25 @@ public class DummyPfKey extends PfKey { public PfConcept copyTo(PfConcept target) { return null; } + + @Override + public boolean isNewerThan(@NonNull PfKey otherKey) { + // TODO Auto-generated method stub + return false; + } + + @Override + public int getMajorVersion() { + return 0; + } + + @Override + public int getMinorVersion() { + return 0; + } + + @Override + public int getPatchVersion() { + return 0; + } } |