import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang3.StringUtils;
-import org.onap.policy.common.parameters.annotations.ClassName;
-import org.onap.policy.common.parameters.annotations.Max;
import org.onap.policy.common.parameters.annotations.Min;
import org.onap.policy.common.parameters.annotations.NotBlank;
import org.onap.policy.common.parameters.annotations.NotNull;
import org.onap.policy.common.parameters.annotations.Pattern;
-import org.onap.policy.common.parameters.annotations.Size;
import org.onap.policy.common.parameters.annotations.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
protected void addValidators(ValueValidator validator) {
validator.addAnnotation(NotNull.class, this::verNotNull);
validator.addAnnotation(NotBlank.class, this::verNotBlank);
- validator.addAnnotation(Size.class, this::verSize);
- validator.addAnnotation(Max.class, this::verMax);
validator.addAnnotation(Min.class, this::verMin);
validator.addAnnotation(Pattern.class, this::verRegex);
- validator.addAnnotation(ClassName.class, this::verClassName);
validator.addAnnotation(Valid.class, this::verCascade);
}
return true;
}
- /**
- * Verifies that the value has the specified number of elements.
- *
- * @param result where to add the validation result
- * @param fieldName field whose value is being verified
- * @param annot annotation against which the value is being verified
- * @param value value to be verified
- * @return {@code true} if the next check should be performed, {@code false} otherwise
- */
- public boolean verSize(BeanValidationResult result, String fieldName, Size annot, Object value) {
- int size;
- if (value instanceof Collection) {
- size = ((Collection<?>) value).size();
-
- } else if (value instanceof Map) {
- size = ((Map<?, ?>) value).size();
-
- } else {
- return true;
- }
-
-
- if (size < annot.min()) {
- result.addResult(fieldName, xlate(value), ValidationStatus.INVALID,
- "minimum number of elements: " + annot.min());
- return false;
- }
-
- return true;
- }
-
/**
* Verifies that the value matches a regular expression.
*
return false;
}
- /**
- * Verifies that the value is <= the minimum value.
- *
- * @param result where to add the validation result
- * @param fieldName field whose value is being verified
- * @param annot annotation against which the value is being verified
- * @param value value to be verified
- * @return {@code true} if the next check should be performed, {@code false} otherwise
- */
- public boolean verMax(BeanValidationResult result, String fieldName, Max annot, Object value) {
- if (!(value instanceof Number)) {
- return true;
- }
-
- Number num = (Number) value;
- if (num instanceof Integer || num instanceof Long) {
- if (num.longValue() <= annot.value()) {
- return true;
- }
-
- } else if (num instanceof Float || num instanceof Double) {
- if (num.doubleValue() <= annot.value()) {
- return true;
- }
-
- } else {
- return true;
- }
-
- result.addResult(fieldName, xlate(value), ValidationStatus.INVALID,
- "exceeds the maximum value: " + annot.value());
- return false;
- }
-
/**
* Verifies that the value is >= the minimum value.
*
return false;
}
- /**
- * Verifies that the value is a valid class name.
- *
- * @param result where to add the validation result
- * @param fieldName field whose value is being verified
- * @param value value to be verified
- * @return {@code true} if the next check should be performed, {@code false} otherwise
- */
- public boolean verClassName(BeanValidationResult result, String fieldName, Object value) {
- if (!(value instanceof String)) {
- return true;
- }
-
- try {
- Class.forName(value.toString());
- return true;
-
- } catch (final ClassNotFoundException exp) {
- result.addResult(fieldName, value, ValidationStatus.INVALID, "class is not in the classpath");
- return false;
- }
- }
-
/**
* Verifies that the value is valid by recursively invoking
* {@link #validateTop(String, Object)}.
// By default we do not show validation results for parameters that are validated as clean
public static final boolean DO_NOT_SHOW_CLEAN_RESULTS = false;
-
- // Messages for clean validations
- public static final String PARAMETER_GROUP_HAS_STATUS_MESSAGE = "parameter group has status ";
- public static final String PARAMETER_GROUP_MAP_HAS_STATUS_MESSAGE = "parameter group map has status ";
- public static final String PARAMETER_HAS_STATUS_MESSAGE = "parameter has status ";
}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.parameters.annotations;
-
-import static java.lang.annotation.ElementType.FIELD;
-import static java.lang.annotation.ElementType.TYPE_USE;
-import static java.lang.annotation.RetentionPolicy.RUNTIME;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-
-/**
- * Indicates that a field (i.e., String) identifies the name of a class in the classpath.
- */
-@Retention(RUNTIME)
-@Target({FIELD, TYPE_USE})
-public @interface ClassName {
-
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.parameters.annotations;
-
-import static java.lang.annotation.ElementType.FIELD;
-import static java.lang.annotation.ElementType.TYPE_USE;
-import static java.lang.annotation.RetentionPolicy.RUNTIME;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-
-@Retention(RUNTIME)
-@Target({FIELD, TYPE_USE})
-public @interface Max {
-
- /**
- * The maximum value allowed.
- *
- * @return the maximum value allowed
- */
- long value();
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.common.parameters.annotations;
-
-import static java.lang.annotation.ElementType.FIELD;
-import static java.lang.annotation.ElementType.TYPE_USE;
-import static java.lang.annotation.RetentionPolicy.RUNTIME;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-
-/**
- * Indicates the size of a Map or Collection.
- */
-@Retention(RUNTIME)
-@Target({FIELD, TYPE_USE})
-public @interface Size {
-
- /**
- * The minimum size allowed.
- *
- * @return the minimum size allowed
- */
- int min();
-}
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
/**
* The Class Assertions is a static class that is used as a shorthand for assertions in the source code.
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class Assertions {
- // Logger for this class
- private static final Logger LOGGER = LoggerFactory.getLogger(Assertions.class);
-
- /**
- * Gets the validation message for a string parameter.
- *
- * @param parameterName the string parameter name
- * @param parameterValue the string parameter value
- * @param pattern The regular expression
- * @return null if the parameter is valid, the validation message otherwise
- */
- public static String getStringParameterValidationMessage(final String parameterName, final String parameterValue,
- final String pattern) {
- try {
- validateStringParameter(parameterName, parameterValue, pattern);
- } catch (IllegalArgumentException e) {
- String message = "parameter " + parameterName + " with value " + parameterValue
- + " does not match regular expression " + pattern;
- if (LOGGER.isTraceEnabled()) {
- LOGGER.trace(message, e);
- }
-
- return message;
- }
-
- return null;
- }
-
/**
* Checks if a string parameter matches a regular expression.
*
}
}
- /**
- * Used as a shorthand to check that method arguments are not false, throws IllegalArgumentException on error.
- *
- * @param value the value to check if false
- * @param message the error message to issue
- */
- public static void argumentNotFalse(final boolean value, final String message) {
- if (!value) {
- throw new IllegalArgumentException(message);
- }
- }
-
- /**
- * Used as a shorthand to check that method arguments are not null, throws an exception of the specified type on
- * error.
- *
- * @param <T> the generic type of the argument to check
- * @param <E> the exception to throw if incoming value is null
- * @param value the value of the type
- * @param exceptionClass the class of exception to return an instance of
- * @param message the error message to issue
- * @throws E an instance of the passed Exception Class
- */
- public static <T, E extends Exception> void argumentOfClassNotNull(final T value, final Class<E> exceptionClass,
- final String message) throws E {
- if (value == null) {
- // Instantiate the exception and throw it
- try {
- throw exceptionClass.getConstructor(String.class).newInstance(message);
- } catch (final Exception errorException) {
- throw new IllegalArgumentException(message, errorException);
- }
- }
- }
-
- /**
- * Used as a shorthand to check that method argument is not false, throws an exception of the specified type on
- * error.
- *
- * @param <E> the exception to throw if incoming value is false
- * @param value the value to check if false
- * @param exceptionClass the class of exception to return an instance of
- * @param message the error message to issue
- * @throws E an instance of the passed Exception Class
- */
- public static <E extends Exception> void argumentOfClassNotFalse(final boolean value, final Class<E> exceptionClass,
- final String message) throws E {
- if (!value) {
- // Instantiate the exception and throw it
- try {
- throw exceptionClass.getConstructor(String.class).newInstance(message);
- } catch (final Exception errorException) {
- throw new IllegalArgumentException(message, errorException);
- }
- }
- }
-
/**
* Used as a shorthand to check that an object is an instance of a given class, throws IllegalArgumentException on
* error.
+ requiredClass.getName());
}
}
-
- /**
- * Used as a shorthand to check that an instance of a class can be an instance of a given class, throws
- * IllegalArgumentException on error.
- *
- * @param <T> the generic type of the argument to check
- * @param checkClass the class to check
- * @param requiredClass the class that the object should be an instance of
- * @throws IllegalArgumentException if the incoming object is not an instance of requiredClass
- */
- public static <T> void assignableFrom(final Class<?> checkClass, final Class<T> requiredClass) {
- if (!requiredClass.isAssignableFrom(checkClass)) {
- throw new IllegalArgumentException(checkClass.getName() + " is not an instance of "
- + requiredClass.getName());
- }
- }
}
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.Getter;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
-import org.onap.policy.common.parameters.annotations.ClassName;
-import org.onap.policy.common.parameters.annotations.Max;
import org.onap.policy.common.parameters.annotations.Min;
import org.onap.policy.common.parameters.annotations.NotBlank;
import org.onap.policy.common.parameters.annotations.NotNull;
import org.onap.policy.common.parameters.annotations.Pattern;
-import org.onap.policy.common.parameters.annotations.Size;
import org.onap.policy.common.parameters.annotations.Valid;
class TestBeanValidator {
private static final String STR_FIELD = "strValue";
private static final String INT_FIELD = "intValue";
private static final String NUM_FIELD = "numValue";
- private static final String ITEMS_FIELD = "items";
private static final String STRING_VALUE = "string value";
private static final int INT_VALUE = 20;
assertTrue(validator.validateTop(TOP, notBlankInt).isValid());
}
- /**
- * Tests verSize with a collection.
- */
- @Test
- void testVerSizeCollection() {
- @Getter
- class CollectionSizeCheck {
- @Size(min = 3)
- Collection<Integer> items;
- }
-
- CollectionSizeCheck collCheck = new CollectionSizeCheck();
-
- // valid length - exact
- collCheck.items = List.of(1, 2, 3);
- assertThat(validator.validateTop(TOP, collCheck).isValid()).isTrue();
-
- // valid length - extra
- collCheck.items = List.of(1, 2, 3, 4);
- assertThat(validator.validateTop(TOP, collCheck).isValid()).isTrue();
-
- // too few
- collCheck.items = List.of(1, 2);
- assertInvalid("testVerSize", validator.validateTop(TOP, collCheck), ITEMS_FIELD, "minimum", "3");
-
- // null
- collCheck.items = null;
- assertThat(validator.validateTop(TOP, collCheck).isValid()).isTrue();
- }
-
- /**
- * Tests verSize with a map.
- */
- @Test
- void testVerSizeMap() {
- @Getter
- class MapSizeCheck {
- @Size(min = 3)
- Map<Integer, Integer> items;
- }
-
- MapSizeCheck mapCheck = new MapSizeCheck();
-
- // valid length - exact
- mapCheck.items = Map.of(1, 10, 2, 20, 3, 30);
- assertThat(validator.validateTop(TOP, mapCheck).isValid()).isTrue();
-
- // valid length - extra
- mapCheck.items = Map.of(1, 10, 2, 20, 3, 30, 4, 40);
- assertThat(validator.validateTop(TOP, mapCheck).isValid()).isTrue();
-
- // too few
- mapCheck.items = Map.of(1, 10, 2, 20);
- assertInvalid("testVerSize", validator.validateTop(TOP, mapCheck), ITEMS_FIELD, "minimum", "3");
-
- // null
- mapCheck.items = null;
- assertThat(validator.validateTop(TOP, mapCheck).isValid()).isTrue();
- }
-
- /**
- * Tests verSize with an object for which it doesn't apply.
- */
- @Test
- void testVerSizeOther() {
- @Getter
- class OtherSizeCheck {
- @Size(min = 3)
- Integer items;
- }
-
- OtherSizeCheck otherCheck = new OtherSizeCheck();
-
- otherCheck.items = 10;
- assertThat(validator.validateTop(TOP, otherCheck).isValid()).isTrue();
- }
-
@Test
void testVerRegex() {
@Getter
"does not match regular expression [a-f]");
}
- @Test
- void testVerMax() {
- /*
- * Field is not a number.
- */
- @Getter
- class NonNumeric {
- @Max(100)
- String strValue;
- }
-
- NonNumeric nonNumeric = new NonNumeric();
- nonNumeric.strValue = STRING_VALUE;
- assertTrue(validator.validateTop(TOP, nonNumeric).isValid());
-
- /*
- * Integer field.
- */
- @Getter
- class IntField {
- @Max(100)
- Integer intValue;
- }
-
- // ok value
- IntField intField = new IntField();
- assertNumeric(intField, value -> {
- intField.intValue = value;
- }, INT_FIELD, "maximum", 100, 101);
-
- /*
- * Long field.
- */
- @Getter
- class LongField {
- @Max(100)
- Long numValue;
- }
-
- // ok value
- LongField longField = new LongField();
- assertNumeric(longField, value -> {
- longField.numValue = (long) value;
- }, NUM_FIELD, "maximum", 100, 101);
-
- /*
- * Float field.
- */
- @Getter
- class FloatField {
- @Max(100)
- Float numValue;
- }
-
- // ok value
- FloatField floatField = new FloatField();
- assertNumeric(floatField, value -> {
- floatField.numValue = (float) value;
- }, NUM_FIELD, "maximum", 100, 101);
-
- /*
- * Double field.
- */
- @Getter
- class DoubleField {
- @Max(100)
- Double numValue;
- }
-
- // ok value
- DoubleField doubleField = new DoubleField();
- assertNumeric(doubleField, value -> {
- doubleField.numValue = (double) value;
- }, NUM_FIELD, "maximum", 100, 101);
-
- /*
- * Atomic Integer field (which is a subclass of Number).
- */
- @Getter
- class AtomIntValue {
- @Max(100)
- AtomicInteger numValue;
- }
-
- // ok value
- AtomIntValue atomIntField = new AtomIntValue();
- atomIntField.numValue = new AtomicInteger(INT_VALUE);
- assertTrue(validator.validateTop(TOP, atomIntField).isValid());
-
- // invalid value - should be OK, because it isn't an Integer
- atomIntField.numValue.set(101);
- assertTrue(validator.validateTop(TOP, atomIntField).isValid());
- }
-
@Test
void testVerMin() {
/*
assertTrue(validator.validateTop(TOP, atomIntField).isValid());
}
- @Test
- void testVerClassName() {
- @Getter
- class ClassNameCheck {
- @ClassName
- String strValue;
- }
-
- ClassNameCheck classCheck = new ClassNameCheck();
-
- // null should be OK
- classCheck.strValue = null;
- assertTrue(validator.validateTop(TOP, classCheck).isValid());
-
- // valid class name
- classCheck.strValue = getClass().getName();
- assertTrue(validator.validateTop(TOP, classCheck).isValid());
-
- // invalid class name
- classCheck.strValue = "<unknown class>";
- assertInvalid("testVerClassName", validator.validateTop(TOP, classCheck),
- STR_FIELD, "class is not in the classpath");
- }
-
@Test
void testVerCascade() {
@Getter
package org.onap.policy.common.utils.validation;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.Test;
private static final String HELLO = "Hello";
private static final String IT_IS_OK = "it is OK";
private static final String IT_IS_NULL = "it is null";
- private static final String IT_IS_TRUE = "it is true";
- private static final String IT_IS_FALSE = "it is false";
@Test
void testAssertions() {
- Assertions.argumentNotFalse(true, IT_IS_TRUE);
-
- assertThatIllegalArgumentException().isThrownBy(() -> Assertions.argumentNotFalse(false, IT_IS_FALSE))
- .withMessage(IT_IS_FALSE);
-
-
- Assertions.argumentOfClassNotFalse(true, ArithmeticException.class, IT_IS_TRUE);
-
- assertThatIllegalArgumentException().isThrownBy(
- () -> Assertions.argumentOfClassNotFalse(false, ArithmeticException.class, IT_IS_FALSE))
- .withMessage(IT_IS_FALSE);
-
-
Assertions.argumentNotNull(HELLO, IT_IS_OK);
assertThatIllegalArgumentException().isThrownBy(() -> Assertions.argumentNotNull(null, IT_IS_NULL))
.withMessage(IT_IS_NULL);
- Assertions.argumentOfClassNotNull(true, ArithmeticException.class, IT_IS_OK);
-
- assertThatIllegalArgumentException().isThrownBy(
- () -> Assertions.argumentOfClassNotNull(null, ArithmeticException.class, IT_IS_NULL))
- .withMessage(IT_IS_NULL);
-
-
- Assertions.assignableFrom(java.util.TreeMap.class, java.util.Map.class);
-
- assertThatIllegalArgumentException()
- .isThrownBy(() -> Assertions.assignableFrom(java.util.Map.class, java.util.TreeMap.class))
- .withMessage("java.util.Map is not an instance of java.util.TreeMap");
-
-
Assertions.instanceOf(HELLO, String.class);
assertThatIllegalArgumentException().isThrownBy(() -> Assertions.instanceOf(100, String.class))
assertThatIllegalArgumentException()
.isThrownBy(() -> Assertions.validateStringParameter("name", "MyName", "^M.*f$"))
.withMessage("parameter \"name\": value \"MyName\", does not match regular expression \"^M.*f$\"");
-
-
- assertNull(Assertions.getStringParameterValidationMessage("Greeting", HELLO, "^H.*o$"));
- assertEquals("parameter Greeting with value Hello does not match regular expression Goodbye",
- Assertions.getStringParameterValidationMessage("Greeting", HELLO, "Goodbye"));
}
}
*/
public abstract Compatibility getCompatibility(@NonNull PfKey otherKey);
- /**
- * Check if two keys are compatible, that is the keys are IDENTICAL or have only MINOR, PATCH differences.
- *
- * @param otherKey the key to check compatibility against
- * @return true, if the keys are compatible
- */
- 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();
}
return Compatibility.PATCH;
}
- @Override
- public boolean isCompatible(@NonNull final PfKey otherKey) {
- if (!(otherKey instanceof PfKeyImpl otherConceptKey)) {
- return false;
- }
-
- final var compatibility = this.getCompatibility(otherConceptKey);
-
- return !(compatibility == Compatibility.DIFFERENT || compatibility == Compatibility.MAJOR);
- }
-
- @Override
- public boolean isNewerThan(@NonNull final PfKey otherKey) {
- Assertions.instanceOf(otherKey, PfKeyImpl.class);
-
- final PfKeyImpl otherConceptKey = (PfKeyImpl) 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 Integer.parseInt(thisVersionArray[0]) > Integer.parseInt(otherVersionArray[0]);
- }
-
- if (thisVersionArray.length >= 2 && otherVersionArray.length >= 2
- && !thisVersionArray[1].equals(otherVersionArray[1])) {
- return Integer.parseInt(thisVersionArray[1]) > Integer.parseInt(otherVersionArray[1]);
- }
-
- if (thisVersionArray.length >= 3 && otherVersionArray.length >= 3
- && !thisVersionArray[2].equals(otherVersionArray[2])) {
- return Integer.parseInt(thisVersionArray[2]) > Integer.parseInt(otherVersionArray[2]);
- }
-
- 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 void clean() {
setName(getName());
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019, 2021, 2023 Nordix Foundation.
- * Modifications Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * 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 jakarta.persistence.Column;
-import jakarta.persistence.Embeddable;
-import java.io.Serial;
-import java.util.ArrayList;
-import java.util.List;
-import lombok.Data;
-import lombok.EqualsAndHashCode;
-import lombok.NonNull;
-import org.onap.policy.common.parameters.annotations.NotNull;
-import org.onap.policy.common.parameters.annotations.Pattern;
-import org.onap.policy.common.utils.validation.Assertions;
-
-/**
- * A reference key identifies entities in the system that are contained in other entities. Every contained concept in
- * the system must have an {@link PfReferenceKey} to identify it. Non-contained first order concepts are identified
- * using an {@link PfConceptKey} key.
- *
- * <p>An {@link PfReferenceKey} contains an {@link PfConceptKey} key reference to the first order entity that contains
- * it. The local name of the reference key must uniquely identify the referenced concept among those concepts contained
- * in the reference key's parent. In other words, if a parent concept has more than one child, the local name in the key
- * of all its children must be unique.
- *
- * <p>If a reference key's parent is itself a reference key, then the parent's local name must be set in the reference
- * key. If the parent is a first order concept, then the parent's local name in the key will be set to NULL.
- *
- * <p>Key validation checks that the parent name and parent version fields match the NAME_REGEXP and
- * VERSION_REGEXP regular expressions respectively and that the local name fields match the
- * LOCAL_NAME_REGEXP regular expression.
- */
-@Embeddable
-@Data
-@EqualsAndHashCode(callSuper = false)
-public class PfReferenceKey extends PfKey {
- private static final String PARENT_KEY_NAME = "parentKeyName";
- private static final String PARENT_KEY_VERSION = "parentKeyVersion";
- private static final String PARENT_LOCAL_NAME = "parentLocalName";
- private static final String LOCAL_NAME = "localName";
-
- @Serial
- private static final long serialVersionUID = 8932717618579392561L;
-
- /**
- * Regular expression to specify the structure of local names in reference keys.
- */
- public static final String LOCAL_NAME_REGEXP = "[A-Za-z0-9\\-_\\.]+|^$";
-
- /**
- * Regular expression to specify the structure of IDs in reference keys.
- */
- public static final String REFERENCE_KEY_ID_REGEXP =
- "[A-Za-z0-9\\-_]+:[0-9].[0-9].[0-9]:[A-Za-z0-9\\-_]+:[A-Za-z0-9\\-_]+";
-
- private static final int PARENT_NAME_FIELD = 0;
- private static final int PARENT_VERSION_FIELD = 1;
- private static final int PARENT_LOCAL_NAME_FIELD = 2;
- private static final int LOCAL_NAME_FIELD = 3;
-
- @Column(name = PARENT_KEY_NAME, length = 120)
- @NotNull
- @Pattern(regexp = NAME_REGEXP)
- private String parentKeyName;
-
- @Column(name = PARENT_KEY_VERSION, length = 15)
- @NotNull
- @Pattern(regexp = VERSION_REGEXP)
- private String parentKeyVersion;
-
- @Column(name = PARENT_LOCAL_NAME, length = 120)
- @NotNull
- @Pattern(regexp = LOCAL_NAME_REGEXP)
- private String parentLocalName;
-
- @Column(name = LOCAL_NAME, length = 120)
- @NotNull
- @Pattern(regexp = LOCAL_NAME_REGEXP)
- private String localName;
-
- /**
- * The default constructor creates a null reference key.
- */
- public PfReferenceKey() {
- this(NULL_KEY_NAME, NULL_KEY_VERSION, NULL_KEY_NAME, NULL_KEY_NAME);
- }
-
- /**
- * The Copy Constructor creates a key by copying another key.
- *
- * @param referenceKey the reference key to copy from
- */
- public PfReferenceKey(final PfReferenceKey referenceKey) {
- this(referenceKey.getParentKeyName(), referenceKey.getParentKeyVersion(), referenceKey.getParentLocalName(),
- referenceKey.getLocalName());
- }
-
- /**
- * Constructor to create a null reference key for the specified parent concept key.
- *
- * @param pfConceptKey the parent concept key of this reference key
- */
- public PfReferenceKey(final PfConceptKey pfConceptKey) {
- this(pfConceptKey.getName(), pfConceptKey.getVersion(), NULL_KEY_NAME, NULL_KEY_NAME);
- }
-
- /**
- * Constructor to create a reference key for the given parent concept key with the given local name.
- *
- * @param pfConceptKey the parent concept key of this reference key
- * @param localName the local name of this reference key
- */
- public PfReferenceKey(final PfConceptKey pfConceptKey, final String localName) {
- this(pfConceptKey, NULL_KEY_NAME, localName);
- }
-
- /**
- * Constructor to create a reference key for the given parent reference key with the given local name.
- *
- * @param parentReferenceKey the parent reference key of this reference key
- * @param localName the local name of this reference key
- */
- public PfReferenceKey(final PfReferenceKey parentReferenceKey, final String localName) {
- this(parentReferenceKey.getParentConceptKey(), parentReferenceKey.getLocalName(), localName);
- }
-
- /**
- * Constructor to create a reference key for the given parent reference key (specified by the parent reference key's
- * concept key and local name) with the given local name.
- *
- * @param pfConceptKey the concept key of the parent reference key of this reference key
- * @param parentLocalName the local name of the parent reference key of this reference key
- * @param localName the local name of this reference key
- */
- public PfReferenceKey(final PfConceptKey pfConceptKey, final String parentLocalName, final String localName) {
- this(pfConceptKey.getName(), pfConceptKey.getVersion(), parentLocalName, localName);
- }
-
- /**
- * Constructor to create a reference key for the given parent concept key (specified by the parent concept key's
- * name and version) with the given local name.
- *
- * @param parentKeyName the name of the parent concept key of this reference key
- * @param parentKeyVersion the version of the parent concept key of this reference key
- * @param localName the local name of this reference key
- */
- public PfReferenceKey(final String parentKeyName, final String parentKeyVersion, final String localName) {
- this(parentKeyName, parentKeyVersion, NULL_KEY_NAME, localName);
- }
-
- /**
- * Constructor to create a reference key for the given parent key (specified by the parent key's name, version nad
- * local name) with the given local name.
- *
- * @param parentKeyName the parent key name of this reference key
- * @param parentKeyVersion the parent key version of this reference key
- * @param parentLocalName the parent local name of this reference key
- * @param localName the local name of this reference key
- */
- public PfReferenceKey(final String parentKeyName, final String parentKeyVersion, final String parentLocalName,
- final String localName) {
- super();
- this.parentKeyName = Assertions.validateStringParameter(PARENT_KEY_NAME, parentKeyName, NAME_REGEXP);
- this.parentKeyVersion = Assertions.validateStringParameter(PARENT_KEY_VERSION, parentKeyVersion,
- VERSION_REGEXP);
- this.parentLocalName = Assertions.validateStringParameter(PARENT_LOCAL_NAME, parentLocalName,
- LOCAL_NAME_REGEXP);
- this.localName = Assertions.validateStringParameter(LOCAL_NAME, localName, LOCAL_NAME_REGEXP);
- }
-
- /**
- * Constructor to create a key from the specified key ID.
- *
- * @param id the key ID in a format that respects the KEY_ID_REGEXP
- */
- public PfReferenceKey(final String id) {
- final var conditionedId = Assertions.validateStringParameter("id", id, REFERENCE_KEY_ID_REGEXP);
-
- // Split on colon, if the id passes the regular expression test above
- // it'll have just three colons separating the parent name,
- // parent version, parent local name, and and local name
- // No need for range checks or size checks on the array
- final String[] nameVersionNameArray = conditionedId.split(":");
-
- // Initiate the new key
- parentKeyName = Assertions.validateStringParameter(PARENT_KEY_NAME, nameVersionNameArray[PARENT_NAME_FIELD],
- NAME_REGEXP);
- parentKeyVersion = Assertions.validateStringParameter(PARENT_KEY_VERSION,
- nameVersionNameArray[PARENT_VERSION_FIELD], VERSION_REGEXP);
- parentLocalName = Assertions.validateStringParameter(PARENT_LOCAL_NAME,
- nameVersionNameArray[PARENT_LOCAL_NAME_FIELD], LOCAL_NAME_REGEXP);
- localName = Assertions.validateStringParameter(LOCAL_NAME, nameVersionNameArray[LOCAL_NAME_FIELD],
- LOCAL_NAME_REGEXP);
- }
-
- /**
- * Get a null reference key.
- *
- * @return a null reference key
- */
- public static PfReferenceKey getNullKey() {
- return new PfReferenceKey(PfKey.NULL_KEY_NAME, PfKey.NULL_KEY_VERSION, PfKey.NULL_KEY_NAME,
- PfKey.NULL_KEY_NAME);
- }
-
- @Override
- public PfReferenceKey getKey() {
- return this;
- }
-
- @Override
- public List<PfKey> getKeys() {
- final List<PfKey> keyList = new ArrayList<>();
- keyList.add(getKey());
- return keyList;
- }
-
- @Override
- public String getId() {
- return parentKeyName + ':' + parentKeyVersion + ':' + parentLocalName + ':' + localName;
- }
-
- @Override
- public boolean isNullKey() {
- return (PfKey.NULL_KEY_NAME.equals(this.getParentKeyName()) && PfKey.NULL_KEY_VERSION
- .equals(this.getParentKeyVersion()) && PfKey.NULL_KEY_NAME.equals(this.getParentLocalName())
- && PfKey.NULL_KEY_NAME.equals(this.getLocalName()));
- }
-
- /**
- * Gets the parent concept key of this reference key.
- *
- * @return the parent concept key of this reference key
- */
- public PfConceptKey getParentConceptKey() {
- return new PfConceptKey(parentKeyName, parentKeyVersion);
- }
-
- /**
- * Gets the parent reference key of this reference key.
- *
- * @return the parent reference key of this reference key
- */
- public PfReferenceKey getParentReferenceKey() {
- return new PfReferenceKey(parentKeyName, parentKeyVersion, parentLocalName);
- }
-
- /**
- * Sets the parent concept key of this reference key.
- *
- * @param parentKey the parent concept key of this reference key
- */
- public void setParentConceptKey(final PfConceptKey parentKey) {
- Assertions.argumentNotNull(parentKey, "parentKey may not be null");
-
- parentKeyName = parentKey.getName();
- parentKeyVersion = parentKey.getVersion();
- parentLocalName = NULL_KEY_NAME;
- }
-
- /**
- * Sets the parent reference key of this reference key.
- *
- * @param parentKey the parent reference key of this reference key
- */
- public void setParentReferenceKey(final PfReferenceKey parentKey) {
- Assertions.argumentNotNull(parentKey, "parentKey may not be null");
-
- parentKeyName = parentKey.getParentKeyName();
- parentKeyVersion = parentKey.getParentKeyVersion();
- parentLocalName = parentKey.getLocalName();
- }
-
- @Override
- public PfKey.Compatibility getCompatibility(@NonNull final PfKey otherKey) {
- if (!(otherKey instanceof PfReferenceKey otherReferenceKey)) {
- return Compatibility.DIFFERENT;
- }
-
- return this.getParentConceptKey().getCompatibility(otherReferenceKey.getParentConceptKey());
- }
-
- @Override
- public boolean isCompatible(@NonNull final PfKey otherKey) {
- if (!(otherKey instanceof PfReferenceKey otherReferenceKey)) {
- return false;
- }
-
- return this.getParentConceptKey().isCompatible(otherReferenceKey.getParentConceptKey());
- }
-
- @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 void clean() {
- parentKeyName = Assertions.validateStringParameter(PARENT_KEY_NAME, parentKeyName, NAME_REGEXP);
- parentKeyVersion = Assertions.validateStringParameter(PARENT_KEY_VERSION, parentKeyVersion, VERSION_REGEXP);
- parentLocalName = Assertions.validateStringParameter(PARENT_LOCAL_NAME, parentLocalName, LOCAL_NAME_REGEXP);
- localName = Assertions.validateStringParameter(LOCAL_NAME, localName, LOCAL_NAME_REGEXP);
- }
-
- @Override
- public int compareTo(@NonNull final PfConcept otherObj) {
- Assertions.argumentNotNull(otherObj, "comparison object may not be null");
-
- if (this == otherObj) {
- return 0;
- }
- if (getClass() != otherObj.getClass()) {
- return getClass().getName().compareTo(otherObj.getClass().getName());
- }
-
- final PfReferenceKey other = (PfReferenceKey) otherObj;
- if (!parentKeyName.equals(other.parentKeyName)) {
- return parentKeyName.compareTo(other.parentKeyName);
- }
- if (!parentKeyVersion.equals(other.parentKeyVersion)) {
- return parentKeyVersion.compareTo(other.parentKeyVersion);
- }
- if (!parentLocalName.equals(other.parentLocalName)) {
- return parentLocalName.compareTo(other.parentLocalName);
- }
- return localName.compareTo(other.localName);
- }
-}
package org.onap.policy.models.base;
-import jakarta.ws.rs.core.Response;
-import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
public static <K, T, R> Map<K, R> mapMap(Map<K, T> source, Function<T, R> mapFunc) {
return mapMap(source, mapFunc, null);
}
-
- /**
- * Makes a copy of an object using the copy constructor from the object's class.
- *
- * @param source object to be copied
- * @return a copy of the source, or {@code null} if the source is {@code null}
- * @throws PfModelRuntimeException if the object cannot be copied
- */
- public static <T> T makeCopy(T source) {
- if (source == null) {
- return null;
- }
-
- try {
- @SuppressWarnings("unchecked") Class<? extends T> clazz = (Class<? extends T>) source.getClass();
-
- return clazz.getConstructor(clazz).newInstance(source);
-
- } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException
- | RuntimeException e) {
- throw new PfModelRuntimeException(Response.Status.INTERNAL_SERVER_ERROR,
- "error copying concept key class: " + source.getClass().getName(), e);
- }
- }
}
import org.onap.policy.common.parameters.ValidationResult;
import org.onap.policy.common.parameters.ValidationStatus;
import org.onap.policy.common.parameters.ValueValidator;
-import org.onap.policy.models.base.validation.annotations.PfMin;
import org.onap.policy.models.base.validation.annotations.VerifyKey;
public class PfValidator extends BeanValidator {
super.addValidators(validator);
validator.addAnnotation(VerifyKey.class, this::verKey);
- validator.addAnnotation(PfMin.class, this::verPfMin);
- }
-
- /**
- * Verifies that the value is >= the minimum value.
- *
- * @param result where to add the validation result
- * @param fieldName field whose value is being verified
- * @param annot annotation against which the value is being verified
- * @param value value to be verified
- * @return {@code true} if the next check should be performed, {@code false} otherwise
- */
- public boolean verPfMin(BeanValidationResult result, String fieldName, PfMin annot, Object value) {
- if (!(value instanceof Number num)) {
- return true;
- }
-
- if (num.longValue() == annot.allowed()) {
- // this value is always allowed
- return true;
- }
-
- return verMin(result, fieldName, annot.value(), value);
}
/**
* utility class.
*/
public 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";
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * ONAP
- * ================================================================================
- * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.policy.models.base.validation.annotations;
-
-import static java.lang.annotation.ElementType.FIELD;
-import static java.lang.annotation.ElementType.TYPE_USE;
-import static java.lang.annotation.RetentionPolicy.RUNTIME;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-
-/**
- * Same as the "Min" annotation, but allows an extra value that is not in the range.
- */
-@Retention(RUNTIME)
-@Target({FIELD, TYPE_USE})
-public @interface PfMin {
-
- /**
- * The minimum value allowed.
- *
- * @return the minimum value allowed
- */
- long value();
-
- /**
- * Allowed value.
- */
- long allowed();
-}
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class ToscaUtils {
- private static final String ROOT_KEY_NAME_SUFFIX = ".Root";
// @formatter:off
private static final Set<PfConceptKey> PREDEFINED_TOSCA_DATA_TYPES = Set.of(
class PfKeyImplTest {
- private static final String OTHER_IS_NULL = "^otherKey is marked .*on.*ull but is null$";
private static final String ID_IS_NULL = "^id is marked .*on.*ull but is null$";
- private static final String VERSION123 = "1.2.3";
- private static final String VERSION100 = "1.0.0";
private static final String VERSION001 = "0.0.1";
private static final String NAME = "name";
private static MyKey someKey;
assertEquals(Compatibility.MAJOR, someKey5.getCompatibility(someKey1));
assertEquals(Compatibility.MAJOR, someKey6.getCompatibility(someKey1));
assertEquals(Compatibility.MAJOR, buildKey3.getCompatibility(someKey1));
-
- assertTrue(someKey1.isCompatible(someKey2));
- assertTrue(someKey1.isCompatible(someKey3));
- assertTrue(someKey1.isCompatible(someKey4));
- assertFalse(someKey1.isCompatible(someKey0));
- assertFalse(someKey1.isCompatible(someKey5));
- assertFalse(someKey1.isCompatible(buildKey3));
- assertFalse(someKey1.isCompatible(buildKey4));
- assertFalse(someKey1.isCompatible(new DummyPfKey()));
}
@Test
MyKey someKey8 = new MyKey();
someKey8.setVersion(VERSION001);
assertFalse(someKey8.isNullKey());
-
- someKey8.setVersion("10");
- assertEquals(0, someKey8.getMinorVersion());
-
- someKey8.setVersion("10.11");
- assertEquals(0, someKey8.getPatchVersion());
}
@Test
assertThatThrownBy(() -> new MyKey(null, VERSION001))
.hasMessageMatching("^name is marked .*on.*ull but is null$");
-
- assertThatThrownBy(() -> new MyKey("AKey", VERSION001).isCompatible(null)).hasMessageMatching(OTHER_IS_NULL);
}
@Test
.contains("does not match regular expression " + PfKey.VERSION_REGEXP);
}
- @Test
- void testkeynewerThan() {
- MyKey key1 = new MyKey("Key1", VERSION123);
-
- assertThatThrownBy(() -> key1.isNewerThan(null)).hasMessageMatching(OTHER_IS_NULL);
-
- assertThatThrownBy(() -> key1.isNewerThan(new PfReferenceKey())).hasMessage(
- "org.onap.policy.models.base.PfReferenceKey is not " + "an instance of " + PfKeyImpl.class.getName());
-
- assertFalse(key1.isNewerThan(key1));
-
- MyKey key1a = new MyKey("Key1a", VERSION123);
- assertFalse(key1.isNewerThan(key1a));
-
- MyKey key1b = new MyKey("Key0", VERSION123);
- 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(VERSION123);
- assertFalse(key1.isNewerThan(key1a));
-
- key1a.setVersion("1.1.3");
- assertTrue(key1.isNewerThan(key1a));
- key1a.setVersion("1.3.3");
- assertFalse(key1.isNewerThan(key1a));
- key1a.setVersion(VERSION123);
- assertFalse(key1.isNewerThan(key1a));
-
- key1a.setVersion("1.2.2");
- assertTrue(key1.isNewerThan(key1a));
- key1a.setVersion("1.2.4");
- assertFalse(key1.isNewerThan(key1a));
- key1a.setVersion(VERSION123);
- assertFalse(key1.isNewerThan(key1a));
-
- key1.setVersion(VERSION100);
- assertFalse(key1.isNewerThan(key1a));
- key1a.setVersion(VERSION100);
- assertFalse(key1.isNewerThan(key1a));
-
- PfReferenceKey refKey = new PfReferenceKey();
-
- assertThatThrownBy(() -> refKey.isNewerThan(null)).hasMessageMatching(OTHER_IS_NULL);
-
- assertThatThrownBy(() -> refKey.isNewerThan(new MyKey()))
- .hasMessage(MyKey.class.getName() + " is not an instance of " + PfReferenceKey.class.getName());
-
- assertFalse(refKey.isNewerThan(refKey));
- }
-
- @Test
- void testmajorMinorPatch() {
- MyKey key = new MyKey("Key", VERSION100);
- assertEquals(1, key.getMajorVersion());
- assertEquals(0, key.getMinorVersion());
- assertEquals(0, key.getPatchVersion());
-
- key = new MyKey("Key", "1.2.0");
- assertEquals(1, key.getMajorVersion());
- assertEquals(2, key.getMinorVersion());
- assertEquals(0, key.getPatchVersion());
-
- key = new MyKey("Key", VERSION123);
- assertEquals(1, key.getMajorVersion());
- assertEquals(2, key.getMinorVersion());
- assertEquals(3, key.getPatchVersion());
- }
-
@Getter
@Setter
@EqualsAndHashCode(callSuper = false)
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2019-2021, 2024 Nordix Foundation.
- * 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.
- * 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.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertNotEquals;
-import static org.junit.jupiter.api.Assertions.assertNotNull;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.lang.reflect.Field;
-import org.junit.jupiter.api.Test;
-import org.onap.policy.common.parameters.ValidationResult;
-
-class PfReferenceKeyTest {
-
- private static final String PARENT_LOCAL_NAME = "ParentLocalName";
- private static final String NPKLN = "NPKLN";
- private static final String LOCAL_NAME = "LocalName";
- private static final String VERSION002 = "0.0.2";
- private static final String VERSION001 = "0.0.1";
-
- @Test
- void testPfReferenceKeyNotNull() {
- assertNotNull(new PfReferenceKey());
- assertNotNull(new PfReferenceKey(new PfConceptKey()));
- assertNotNull(new PfReferenceKey(new PfConceptKey(), LOCAL_NAME));
- assertNotNull(new PfReferenceKey(new PfReferenceKey()));
- assertNotNull(new PfReferenceKey(new PfReferenceKey(), LOCAL_NAME));
- assertNotNull(new PfReferenceKey(new PfConceptKey(), PARENT_LOCAL_NAME, LOCAL_NAME));
- assertNotNull(new PfReferenceKey("ParentKeyName", VERSION001, LOCAL_NAME));
- assertNotNull(new PfReferenceKey("ParentKeyName", VERSION001, PARENT_LOCAL_NAME, LOCAL_NAME));
- assertNotNull(new PfReferenceKey("ParentKeyName:0.0.1:ParentLocalName:LocalName"));
- assertEquals(PfReferenceKey.getNullKey().getKey(), PfReferenceKey.getNullKey());
- assertEquals("NULL:0.0.0:NULL:NULL", PfReferenceKey.getNullKey().getId());
-
- assertThatThrownBy(() -> new PfReferenceKey(new PfConceptKey(), null))
- .hasMessage("parameter \"localName\" is null");
- }
-
- @Test
- void testPfReferenceKey() {
- PfReferenceKey testReferenceKey = new PfReferenceKey();
- testReferenceKey.setParentConceptKey(new PfConceptKey("PN", VERSION001));
- 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());
-
- testReferenceKey.setParentReferenceKey(new PfReferenceKey("PN", VERSION001, "LN"));
- assertEquals("PN:0.0.1:NULL:LN", testReferenceKey.getParentReferenceKey().getId());
-
- testReferenceKey.setParentKeyName("NPKN");
- assertEquals("NPKN", testReferenceKey.getParentKeyName());
-
- testReferenceKey.setParentKeyVersion(VERSION001);
- assertEquals(VERSION001, testReferenceKey.getParentKeyVersion());
-
- testReferenceKey.setParentLocalName(NPKLN);
- assertEquals(NPKLN, testReferenceKey.getParentLocalName());
-
- testReferenceKey.setLocalName("NLN");
- assertEquals("NLN", testReferenceKey.getLocalName());
-
- assertThatThrownBy(() -> testReferenceKey.isCompatible(null))
- .hasMessageMatching("^otherKey is marked .*on.*ull but is null$");
-
- assertFalse(testReferenceKey.isCompatible(PfConceptKey.getNullKey()));
- assertFalse(testReferenceKey.isCompatible(PfReferenceKey.getNullKey()));
- assertTrue(testReferenceKey.isCompatible(testReferenceKey));
-
- assertEquals(PfKey.Compatibility.DIFFERENT, testReferenceKey.getCompatibility(PfConceptKey.getNullKey()));
- assertEquals(PfKey.Compatibility.DIFFERENT, testReferenceKey.getCompatibility(PfReferenceKey.getNullKey()));
- assertEquals(PfKey.Compatibility.IDENTICAL, testReferenceKey.getCompatibility(testReferenceKey));
-
- assertTrue(testReferenceKey.validate("").isValid());
- }
-
- @Test
- void testMultiplePfReferenceKey() {
- PfReferenceKey testReferenceKey = setTestReferenceKey();
- testReferenceKey.clean();
-
- PfReferenceKey clonedReferenceKey = new PfReferenceKey(testReferenceKey);
- assertEquals("PfReferenceKey(parentKeyName=NPKN, parentKeyVersion=0.0.1, parentLocalName=NPKLN, localName=NLN)",
- clonedReferenceKey.toString());
-
- assertNotEquals(0, testReferenceKey.hashCode());
-
- assertEquals(testReferenceKey, (Object) testReferenceKey);
- assertEquals(testReferenceKey, clonedReferenceKey);
- assertNotEquals(testReferenceKey, (Object) "Hello");
- assertNotEquals(testReferenceKey, new PfReferenceKey("PKN", VERSION002, "PLN", "LN"));
- assertNotEquals(testReferenceKey, new PfReferenceKey("NPKN", VERSION002, "PLN", "LN"));
- assertNotEquals(testReferenceKey, new PfReferenceKey("NPKN", VERSION001, "PLN", "LN"));
- assertNotEquals(testReferenceKey, new PfReferenceKey("NPKN", VERSION001, "NPLN", "LN"));
- assertEquals(testReferenceKey, new PfReferenceKey("NPKN", VERSION001, NPKLN, "NLN"));
-
- assertEquals(0, testReferenceKey.compareTo(testReferenceKey));
- assertEquals(0, testReferenceKey.compareTo(clonedReferenceKey));
- assertNotEquals(0, testReferenceKey.compareTo(new PfConceptKey()));
- assertNotEquals(0, testReferenceKey.compareTo(new PfReferenceKey("PKN", VERSION002, "PLN", "LN")));
- assertNotEquals(0, testReferenceKey.compareTo(new PfReferenceKey("NPKN", VERSION002, "PLN", "LN")));
- assertNotEquals(0, testReferenceKey.compareTo(new PfReferenceKey("NPKN", VERSION001, "PLN", "LN")));
- assertNotEquals(0, testReferenceKey.compareTo(new PfReferenceKey("NPKN", VERSION001, "NPLN", "LN")));
- assertEquals(0, testReferenceKey.compareTo(new PfReferenceKey("NPKN", VERSION001, NPKLN, "NLN")));
-
- assertNotNull(testReferenceKey);
-
- assertThatThrownBy(() -> new PfReferenceKey((PfReferenceKey) null)).isInstanceOf(NullPointerException.class);
-
- assertEquals(testReferenceKey, new PfReferenceKey(testReferenceKey));
- }
-
- @Test
- void testValidation() throws Exception {
- PfReferenceKey testReferenceKey = new PfReferenceKey();
- testReferenceKey.setParentConceptKey(new PfConceptKey("PN", VERSION001));
- assertEquals("PN:0.0.1", testReferenceKey.getParentConceptKey().getId());
-
- Field parentNameField = testReferenceKey.getClass().getDeclaredField("parentKeyName");
- parentNameField.setAccessible(true);
- parentNameField.set(testReferenceKey, "Parent Name");
- ValidationResult validationResult = testReferenceKey.validate("");
- parentNameField.set(testReferenceKey, "ParentName");
- parentNameField.setAccessible(false);
- 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");
- ValidationResult validationResult2 = testReferenceKey.validate("");
- parentVersionField.set(testReferenceKey, VERSION001);
- parentVersionField.setAccessible(false);
- 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");
- ValidationResult validationResult3 = testReferenceKey.validate("");
- parentLocalNameField.set(testReferenceKey, PARENT_LOCAL_NAME);
- parentLocalNameField.setAccessible(false);
- 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");
- ValidationResult validationResult4 = testReferenceKey.validate("");
- localNameField.set(testReferenceKey, LOCAL_NAME);
- localNameField.setAccessible(false);
- assertThat(validationResult4.getResult()).contains("\"localName\"")
- .contains("does not match regular expression [A-Za-z0-9\\-_\\.]+|^$");
- }
-
- private PfReferenceKey setTestReferenceKey() {
- PfReferenceKey testReferenceKey = new PfReferenceKey();
- testReferenceKey.setParentConceptKey(new PfConceptKey("PN", VERSION001));
- testReferenceKey.setParentReferenceKey(new PfReferenceKey("PN", VERSION001, "LN"));
- testReferenceKey.setParentKeyName("NPKN");
- testReferenceKey.setParentKeyVersion(VERSION001);
- testReferenceKey.setParentLocalName(NPKLN);
- testReferenceKey.setLocalName("NLN");
-
- return testReferenceKey;
- }
-}
package org.onap.policy.models.base;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
-import lombok.Getter;
-import lombok.ToString;
import org.junit.jupiter.api.Test;
/**
newMap.remove("abcX");
newMap.put("something", 789);
}
-
- @Test
- void testMakeCopy() {
- assertNull(PfUtils.makeCopy((MyObject) null));
- NoCopyConstructor noCopyConstructor = new NoCopyConstructor();
- MyObject origObject = new MyObject();
- origObject.name = HELLO;
- assertEquals(origObject.toString(), PfUtils.makeCopy(origObject).toString());
-
- assertThatThrownBy(() -> PfUtils.makeCopy(noCopyConstructor)).isInstanceOf(PfModelRuntimeException.class);
- }
-
- @Getter
- @ToString
- private static class MyObject {
- private String name;
-
- public MyObject() {
- // do nothing
- }
-
- @SuppressWarnings("unused")
- public MyObject(MyObject source) {
- this.name = source.name;
- }
- }
-
- @Getter
- private static class NoCopyConstructor {
- private String name;
- }
}
import org.onap.policy.common.parameters.annotations.NotNull;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
-import org.onap.policy.models.base.validation.annotations.PfMin;
import org.onap.policy.models.base.validation.annotations.VerifyKey;
class PfValidatorTest {
assertThat(validator.validateTop("", data).getResult()).contains("strValue", "null");
}
- @Test
- void testVerPfMin() {
- PfMinChecker data = new PfMinChecker();
- data.intValue = 10;
- assertThat(validator.validateTop("", data).getResult()).isNull();
-
- data.intValue = -2;
- assertThat(validator.validateTop("", data).getResult()).isNull();
-
- data.intValue = null;
- assertThat(validator.validateTop("", data).getResult()).isNull();
-
- data.intValue = STRING_VALUE;
- assertThat(validator.validateTop("", data).getResult()).isNull();
-
- data.intValue = -1;
- assertThat(validator.validateTop("", data).getResult()).contains("intValue", "-1");
- }
-
@Test
void testVerCascadeBeanValidationResultStringObject() {
CascadeChecker checker = new CascadeChecker();
private String strValue;
}
- public static class PfMinChecker {
- @Getter
- @PfMin(value = 5, allowed = -2)
- private Object intValue;
- }
-
public static class CascadeChecker extends Validated {
@Getter
@Valid
return null;
}
- @Override
- public boolean isCompatible(@NonNull PfKey otherKey) {
- return false;
- }
-
@Override
public PfKey getKey() {
return null;
public int hashCode() {
return 0;
}
-
- @Override
- public boolean isNewerThan(@NonNull PfKey otherKey) {
- return false;
- }
-
- @Override
- public int getMajorVersion() {
- return 0;
- }
-
- @Override
- public int getMinorVersion() {
- return 0;
- }
-
- @Override
- public int getPatchVersion() {
- return 0;
- }
}