diff options
123 files changed, 7151 insertions, 819 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/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/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/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; + } } diff --git a/models-decisions/src/main/java/org/onap/policy/models/decisions/concepts/DecisionRequest.java b/models-decisions/src/main/java/org/onap/policy/models/decisions/concepts/DecisionRequest.java index 94c9c9585..1ba7f4362 100644 --- a/models-decisions/src/main/java/org/onap/policy/models/decisions/concepts/DecisionRequest.java +++ b/models-decisions/src/main/java/org/onap/policy/models/decisions/concepts/DecisionRequest.java @@ -43,6 +43,9 @@ public class DecisionRequest { @SerializedName("ONAPInstance") private String onapInstance; + @SerializedName("requestId") + private String requestId; + @SerializedName("action") private String action; diff --git a/models-decisions/src/main/java/org/onap/policy/models/decisions/concepts/DecisionResponse.java b/models-decisions/src/main/java/org/onap/policy/models/decisions/concepts/DecisionResponse.java index b265fe4fb..b4f288685 100644 --- a/models-decisions/src/main/java/org/onap/policy/models/decisions/concepts/DecisionResponse.java +++ b/models-decisions/src/main/java/org/onap/policy/models/decisions/concepts/DecisionResponse.java @@ -33,7 +33,8 @@ import lombok.Data; */ @Data public class DecisionResponse { - - private String errorMessage; + private String status; + private Map<String, Object> advice; + private Map<String, Object> obligations; private List<Map<String, Object>> policies; } diff --git a/models-errors/pom.xml b/models-errors/pom.xml index ab998537e..4e297868e 100644 --- a/models-errors/pom.xml +++ b/models-errors/pom.xml @@ -27,7 +27,7 @@ <version>2.0.0-SNAPSHOT</version> </parent> - <artifactId>models-errors</artifactId> + <artifactId>policy-models-errors</artifactId> <name>${project.artifactId}</name> <description>The models for Policy API's to return Error/warning message details.</description> diff --git a/models-errors/src/main/java/org/onap/policy/models/errors/concepts/ErrorResponse.java b/models-errors/src/main/java/org/onap/policy/models/errors/concepts/ErrorResponse.java index b072ba1f6..88960f8ae 100644 --- a/models-errors/src/main/java/org/onap/policy/models/errors/concepts/ErrorResponse.java +++ b/models-errors/src/main/java/org/onap/policy/models/errors/concepts/ErrorResponse.java @@ -22,6 +22,7 @@ package org.onap.policy.models.errors.concepts; import com.google.gson.annotations.SerializedName; +import java.io.Serializable; import java.util.List; import javax.ws.rs.core.Response; @@ -36,7 +37,8 @@ import lombok.Data; * */ @Data -public class ErrorResponse { +public class ErrorResponse implements Serializable { + private static final long serialVersionUID = 6760066094588944729L; @SerializedName("code") private Response.Status responseCode; diff --git a/models-base/src/main/java/org/onap/policy/models/base/PfModelExceptionInfo.java b/models-errors/src/main/java/org/onap/policy/models/errors/concepts/ErrorResponseInfo.java index 2fe244cec..ed7104b04 100644 --- a/models-base/src/main/java/org/onap/policy/models/base/PfModelExceptionInfo.java +++ b/models-errors/src/main/java/org/onap/policy/models/errors/concepts/ErrorResponseInfo.java @@ -18,42 +18,19 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.models.base; - -import javax.ws.rs.core.Response; +package org.onap.policy.models.errors.concepts; /** - * Interface implemented bu Policy framework model exceptions to allow uniform reading of status codes and cascaded - * messages. + * Interface implemented by Policy framework model exceptions to allow uniform reading of error responses. * * @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(); +public interface ErrorResponseInfo { /** - * Get the stack trace of the exception as a string. + * Get the error response. * - * @return the stack trace of this message as a string + * @return the error response */ - public String getStackTraceAsString(); + public ErrorResponse getErrorResponse(); } diff --git a/models-errors/src/main/java/org/onap/policy/models/errors/concepts/ErrorResponseUtils.java b/models-errors/src/main/java/org/onap/policy/models/errors/concepts/ErrorResponseUtils.java new file mode 100644 index 000000000..5052d36fd --- /dev/null +++ b/models-errors/src/main/java/org/onap/policy/models/errors/concepts/ErrorResponseUtils.java @@ -0,0 +1,56 @@ +/*- + * ============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.errors.concepts; + +import java.util.ArrayList; +import java.util.List; + +/** + * Utility class for managing {@link ErrorResponse objects}. + * + * @author Liam Fallon (liam.fallon@est.tech) + */ +public final class ErrorResponseUtils { + /** + * Private constructor used to prevent sub class instantiation. + */ + private ErrorResponseUtils() {} + + /** + * Store the cascaded messages from an exception and all its nested exceptions in an ErrorResponse object. + * + * @param throwable the top level exception + */ + public static void getExceptionMessages(final ErrorResponse errorResponse, final Throwable throwable) { + errorResponse.setErrorMessage(throwable.getMessage()); + + List<String> cascascadedErrorMessages = new ArrayList<>(); + + for (Throwable t = throwable; t != null; t = t.getCause()) { + cascascadedErrorMessages.add(t.getMessage()); + } + + if (!cascascadedErrorMessages.isEmpty()) { + errorResponse.setErrorDetails(cascascadedErrorMessages); + } + } +} + diff --git a/models-errors/src/test/java/org/onap/policy/models/errors/concepts/ErrorResponseUtilsTest.java b/models-errors/src/test/java/org/onap/policy/models/errors/concepts/ErrorResponseUtilsTest.java new file mode 100644 index 000000000..4f4ef395a --- /dev/null +++ b/models-errors/src/test/java/org/onap/policy/models/errors/concepts/ErrorResponseUtilsTest.java @@ -0,0 +1,53 @@ +/*- + * ============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.errors.concepts; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; + +import org.junit.Test; + +/** + * Test the {@link ErrorResponseUtils} class. + * + * @author Liam Fallon (liam.fallon@est.tech) + */ +public class ErrorResponseUtilsTest { + @Test + public void testErrorResponseUtils() { + try { + try { + throw new NumberFormatException("Exception 0"); + } + catch (Exception nfe) { + throw new IOException("Exception 1", nfe); + } + } catch (Exception ioe) { + ErrorResponse errorResponse = new ErrorResponse(); + ErrorResponseUtils.getExceptionMessages(errorResponse, ioe); + + assertEquals("Exception 1", errorResponse.getErrorMessage()); + assertEquals("Exception 1", errorResponse.getErrorDetails().get(0)); + assertEquals("Exception 0", errorResponse.getErrorDetails().get(1)); + } + } +} diff --git a/models-examples/src/main/resources/policies/vCPE.policies.optimization.input.tosca.yaml b/models-examples/src/main/resources/policies/vCPE.policies.optimization.input.tosca.yaml new file mode 100644 index 000000000..378e8157e --- /dev/null +++ b/models-examples/src/main/resources/policies/vCPE.policies.optimization.input.tosca.yaml @@ -0,0 +1,130 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +topology_template: +policies: + - + OSDF_CASABLANCA.Affinity_vCPE_1: + type: onap.policies.optimization.AffinityPolicy + version: 1.0.0 + metadata: + policy-id: OSDF_CASABLANCA.Affinity_vCPE_1 + properties: + identity: affinity_vCPE + policyScope: [vCPE, US, INTERNATIONAL, ip, vGMuxInfra, vG] + affinityProperties: + qualifier: same + category: complex + policyType: zone + resources: [vGMuxInfra, vG] + - + OSDF_CASABLANCA.Capacity_vG_1: + type: onap.policies.optimization.Vim_fit + version: 1.0.0 + metadata: + policy-id: OSDF_CASABLANCA.Capacity_vG_1 + properties: + identity: capacity_vG + policyScope: [VCPE, US, INTERNATIONAL, ip, vG] + resources: [vG] + capacityProperty: + controller: multicloud + request: "{\"vCPU\": 10, \"Memory\": {\"quantity\": {\"get_param\": \"REQUIRED_MEM\"}, \"unit\": \"GB\"}, \"Storage\": {\"quantity\": {\"get_param\": \"REQUIRED_DISK\"}, \"unit\": \"GB\"}}" + policyType: vim_fit + applicableResources: any + - + OSDF_CASABLANCA.Distance_vG_1: + type: onap.policies.optimization.DistancePolicy + version: 1.0.0 + metadata: + policy-id: OSDF_CASABLANCA.Distance_vG_1 + properties: + distanceProperties: + locationInfo: customer_loc + distance: + value: 1500 + operator: "<" + unit: km + identity: "distance-vG" + resources: [vG] + policyScope: [vCPE, US, INTERNATIONAL, ip, vG] + policyType: distance_to_location + applicableResources: any + - + OSDF_CASABLANCA.hpa_policy_vG_1: + type: onap.policies.optimization.HpaPolicy + version: 1.0.0 + metadata: + policy-id: OSDF_CASABLANCA.hpa_policy_vG_1 + properties: + resources: [vG] + identity: "hpa-vG" + policyScope: [vCPE, US, INTERNATIONAL, ip, vG] + policyType: hpa + # NONE OF THE FLAVORFEATURES CAME OUT RIGHT + - + OSDF_CASABLANCA.queryPolicy_vCPE: + type: onap.policies.optimization.QueryPolicy + version: 1.0.0 + metadata: + policy-id: OSDF_CASABLANCA.queryPolicy_vCPE + properties: + queryProperties: + - + attribute: locationId + attribute_location: customerLocation + value: "" + - + attribute: id + attribute_location: "vpnInfo.vpnId" + value: "" + - + attribute: upstreamBW + attribute_location: "vpnInfo.upstreamBW" + value: "" + - + attribute: customerLatitude + attribute_location: customerLatitude + value: 1.1 + - + attribute: customerLongitude + attribute_location: customerLongitude + value: 2.2 + serviceName: vCPE + policyScope: [vCPE, US, INTERNATIONAL, ip, vGMuxInfra, vG] + policyType: request_param_query + identity: vCPE_Query_Policy + + - + OSDF_CASABLANCA.SubscriberPolicy_v1: + type: onap.policies.optimization.SubscriberPolicy + version: 1.0.0 + metadata: + policy-id: OSDF_CASABLANCA.SubscriberPolicy_v1 + properties: + identity: subscriber_vCPE + policyScope: [vCPE, subscriber_x, subscriber_y, subscriberPolicy] + properties: + subscriberName: [subscriber_x, subscriber_y] + subscriberRole: ["PVT Homing"] + provStatus: [CAPPED] + policyType: subscriberPolicy + serviceName: vCPE + - + OSDF_CASABLANCA.vnfPolicy_vG: + type: onap.policies.optimization.VnfPolicy + version: 1.0.0 + metadata: + policy-id: OSDF_CASABLANCA.vnfPolicy_vG + properties: + identity: vnf_vG + policyScope: [vCPE, US, INTERNATIONAL, ip, vG] + policyType: vnfPolicy + resources: [vG] + applicableResources: any + vnfProperties: + - + inventoryProvider: aai + serviceType: "" + inventoryType: cloud + customerId: "" + orchestrationStatus: "" + equipmentRole: ""
\ No newline at end of file diff --git a/models-examples/src/main/resources/policies/vDNS.policy.guard.frequency.output.tosca.yaml b/models-examples/src/main/resources/policies/vDNS.policy.guard.frequency.output.tosca.yaml new file mode 100644 index 000000000..9cd275e2c --- /dev/null +++ b/models-examples/src/main/resources/policies/vDNS.policy.guard.frequency.output.tosca.yaml @@ -0,0 +1,20 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +topology_template: + policies: + - + guard.frequency.scaleout: + type: onap.policies.controlloop.guard.FrequencyLimiter + version: 1.0.0 + metadata: + policy-id : guard.frequency.scaleout + policy-version: 1 + properties: + actor: SO + recipe: scaleOut + targets: .* + clname: ControlLoop-vDNS-6f37f56d-a87d-4b85-b6a9-cc953cf779b3 + limit: 1 + timeWindow: 10 + timeUnits: minute + guardActiveStart: 00:00:01-05:00 + guardActiveEnd: 23:59:59-05:00 diff --git a/models-examples/src/main/resources/policies/vDNS.policy.guard.minmax.input.json b/models-examples/src/main/resources/policies/vDNS.policy.guard.minmax.input.json index c62a229a6..2dbfe8ce9 100644 --- a/models-examples/src/main/resources/policies/vDNS.policy.guard.minmax.input.json +++ b/models-examples/src/main/resources/policies/vDNS.policy.guard.minmax.input.json @@ -1,5 +1,4 @@ { -{ "policy-id" : "guard.minmax.scaleout", "contents" : { "actor": "SO", diff --git a/models-examples/src/main/resources/policies/vDNS.policy.guard.minmax.input.tosca.yaml b/models-examples/src/main/resources/policies/vDNS.policy.guard.minmax.input.tosca.yaml new file mode 100644 index 000000000..6e0e9f24b --- /dev/null +++ b/models-examples/src/main/resources/policies/vDNS.policy.guard.minmax.input.tosca.yaml @@ -0,0 +1,18 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +topology_template: + policies: + - + guard.minmax.scaleout: + type: onap.policies.controlloop.guard.MinMax + version: 1.0.0 + metadata: + policy-id : guard.minmax.scaleout + properties: + actor: SO + recipe: scaleOut + targets: .* + clname: ControlLoop-vDNS-6f37f56d-a87d-4b85-b6a9-cc953cf779b3 + min: 1 + max: 5 + guardActiveStart: 00:00:01-05:00 + guardActiveEnd: 23:59:59-05:00 diff --git a/models-examples/src/main/resources/policies/vDNS.policy.guard.minmax.output.tosca.yaml b/models-examples/src/main/resources/policies/vDNS.policy.guard.minmax.output.tosca.yaml new file mode 100644 index 000000000..5ac760156 --- /dev/null +++ b/models-examples/src/main/resources/policies/vDNS.policy.guard.minmax.output.tosca.yaml @@ -0,0 +1,19 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +topology_template: + policies: + - + guard.minmax.scaleout: + type: onap.policies.controlloop.guard.MinMax + version: 1.0.0 + metadata: + policy-id : guard.minmax.scaleout + policy-version: 1 + properties: + actor: SO + recipe: scaleOut + targets: .* + clname: ControlLoop-vDNS-6f37f56d-a87d-4b85-b6a9-cc953cf779b3 + min: 1 + max: 5 + guardActiveStart: 00:00:01-05:00 + guardActiveEnd: 23:59:59-05:00 diff --git a/models-examples/src/main/resources/policies/vDNS.policy.monitoring.input.tosca.json b/models-examples/src/main/resources/policies/vDNS.policy.monitoring.input.tosca.json index 2188cb2e8..270613a93 100644 --- a/models-examples/src/main/resources/policies/vDNS.policy.monitoring.input.tosca.json +++ b/models-examples/src/main/resources/policies/vDNS.policy.monitoring.input.tosca.json @@ -1,48 +1,60 @@ { "tosca_definitions_version": "tosca_simple_yaml_1_0_0", - "policies": [ - { - "onap.scaleout.tca": { - "type": "onap.policies.monitoring.cdap.tca.hi.lo.app", - "version": "1.0.0", - "metadata": { - "policy-id": "onap.scaleout.tca" - }, - "properties": { - "tca_policy": { - "domain": "measurementsForVfScaling", - "metricsPerEventName": [ - { - "eventName": "vLoadBalancer", - "controlLoopSchemaType": "VNF", - "policyScope": "type=configuration", - "policyName": "onap.scaleout.tca", - "policyVersion": "v0.0.1", - "thresholds": [ - { - "closedLoopControlName": "ControlLoop-vDNS-6f37f56d-a87d-4b85-b6a9-cc953cf779b3", - "closedLoopEventStatus": "ONSET", - "version": "1.0.2", - "fieldPath": "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated", - "thresholdValue": 500, - "direction": "LESS_OR_EQUAL", - "severity": "MAJOR" - }, - { - "closedLoopControlName": "ControlLoop-vDNS-6f37f56d-a87d-4b85-b6a9-cc953cf779b3", - "closedLoopEventStatus": "ONSET", - "version": "1.0.2", - "fieldPath": "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated", - "thresholdValue": 5000, - "direction": "GREATER_OR_EQUAL", - "severity": "CRITICAL" - } - ] - } - ] + "topology_template": + { + "policies": + [ + { + "onap.scaleout.tca": + { + "type": "onap.policies.monitoring.cdap.tca.hi.lo.app", + "version": "1.0.0", + "metadata": + { + "policy-id": "onap.scaleout.tca" + }, + + "properties": + { + "tca_policy": + { + "domain": "measurementsForVfScaling", + "metricsPerEventName": + [ + { + "eventName": "vLoadBalancer", + "controlLoopSchemaType": "VNF", + "policyScope": "type=configuration", + "policyName": "onap.scaleout.tca", + "policyVersion": "v0.0.1", + "thresholds": + [ + { + "closedLoopControlName": "ControlLoop-vDNS-6f37f56d-a87d-4b85-b6a9-cc953cf779b3", + "closedLoopEventStatus": "ONSET", + "version": "1.0.2", + "fieldPath": "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated", + "thresholdValue": 500, + "direction": "LESS_OR_EQUAL", + "severity": "MAJOR" + }, + + { + "closedLoopControlName": "ControlLoop-vDNS-6f37f56d-a87d-4b85-b6a9-cc953cf779b3", + "closedLoopEventStatus": "ONSET", + "version": "1.0.2", + "fieldPath": "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated", + "thresholdValue": 5000, + "direction": "GREATER_OR_EQUAL", + "severity": "CRITICAL" + } + ] + } + ] + } } } } - } - ] + ] + } }
\ No newline at end of file diff --git a/models-examples/src/main/resources/policies/vFirewall.policy.monitoring.input.tosca.json b/models-examples/src/main/resources/policies/vFirewall.policy.monitoring.input.tosca.json index 93545a0dd..aef04c99c 100644 --- a/models-examples/src/main/resources/policies/vFirewall.policy.monitoring.input.tosca.json +++ b/models-examples/src/main/resources/policies/vFirewall.policy.monitoring.input.tosca.json @@ -1,45 +1,60 @@ { "tosca_definitions_version": "tosca_simple_yaml_1_0_0", - "policies": [ - { - "onap.vfirewall.tca": { - "type": "onap.policy.monitoring.cdap.tca.hi.lo.app", - "version": "1.0.0", - "properties": { - "tca_policy": { - "domain": "measurementsForVfScaling", - "metricsPerEventName": [ - { - "eventName": "vLoadBalancer", - "controlLoopSchemaType": "VNF", - "policyScope": "resource=vLoadBalancer;type=configuration", - "policyName": "onap.vfirewall.tca", - "policyVersion": "v0.0.1", - "thresholds": [ - { - "closedLoopControlName": "ControlLoop-vFirewall-d0a1dfc6-94f5-4fd4-a5b5-4630b438850a", - "closedLoopEventStatus": "ONSET", - "version": "1.0.2", - "fieldPath": "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated", - "thresholdValue": 500, - "direction": "LESS_OR_EQUAL", - "severity": "MAJOR" - }, - { - "closedLoopControlName": "ControlLoop-vFirewall-d0a1dfc6-94f5-4fd4-a5b5-4630b438850a", - "closedLoopEventStatus": "ONSET", - "version": "1.0.2", - "fieldPath": "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated", - "thresholdValue": 5000, - "direction": "GREATER_OR_EQUAL", - "severity": "CRITICAL" - } - ] - } - ] + "topology_template": + { + "policies": + [ + { + "onap.vfirewall.tca": + { + "type": "onap.policy.monitoring.cdap.tca.hi.lo.app", + "version": "1.0.0", + "metadata": + { + "policy-id": "onap.vfirewall.tca" + }, + + "properties": + { + "tca_policy": + { + "domain": "measurementsForVfScaling", + "metricsPerEventName": + [ + { + "eventName": "vLoadBalancer", + "controlLoopSchemaType": "VNF", + "policyScope": "resource=vLoadBalancer;type=configuration", + "policyName": "onap.vfirewall.tca", + "policyVersion": "v0.0.1", + "thresholds": + [ + { + "closedLoopControlName": "ControlLoop-vFirewall-d0a1dfc6-94f5-4fd4-a5b5-4630b438850a", + "closedLoopEventStatus": "ONSET", + "version": "1.0.2", + "fieldPath": "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated", + "thresholdValue": 500, + "direction": "LESS_OR_EQUAL", + "severity": "MAJOR" + }, + + { + "closedLoopControlName": "ControlLoop-vFirewall-d0a1dfc6-94f5-4fd4-a5b5-4630b438850a", + "closedLoopEventStatus": "ONSET", + "version": "1.0.2", + "fieldPath": "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated", + "thresholdValue": 5000, + "direction": "GREATER_OR_EQUAL", + "severity": "CRITICAL" + } + ] + } + ] + } } } } - } - ] + ] + } }
\ No newline at end of file diff --git a/models-examples/src/main/resources/policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.yaml b/models-examples/src/main/resources/policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.yaml index 5a093ddbf..63796fa3f 100644 --- a/models-examples/src/main/resources/policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.yaml +++ b/models-examples/src/main/resources/policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.yaml @@ -1,17 +1,18 @@ tosca_definitions_version: tosca_simple_yaml_1_0_0 policy_types: - version: 1.0.0 - onap.policies.Monitoring: - derived_from: tosca.policies.Root - description: a base policy type for all policies that govern monitoring provision - version: 1.0.0 - onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server: - derived_from: policy.nodes.Root - version: 1.0.0 - properties: - buscontroller_feed_publishing_endpoint: - type: string - description: DMAAP Bus Controller feed endpoint - datafile.policy: - type: string - description: datafile Policy JSON as string + - + onap.policies.Monitoring: + derived_from: tosca.policies.Root + description: a base policy type for all policies that govern monitoring provision + version: 1.0.0 + - + onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server: + derived_from: policy.nodes.Root + version: 1.0.0 + properties: + buscontroller_feed_publishing_endpoint: + type: string + description: DMAAP Bus Controller feed endpoint + datafile.policy: + type: string + description: datafile Policy JSON as string
\ No newline at end of file diff --git a/models-examples/src/main/resources/policytypes/onap.policies.optimization.AffinityPolicy.yaml b/models-examples/src/main/resources/policytypes/onap.policies.optimization.AffinityPolicy.yaml new file mode 100644 index 000000000..c2fd504e9 --- /dev/null +++ b/models-examples/src/main/resources/policytypes/onap.policies.optimization.AffinityPolicy.yaml @@ -0,0 +1,62 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +policy_types: + - onap.policies.Optimization: + derived_from: tosca.policies.Root + version: 1.0.0 + description: a base policy type for all policies that govern optimization + - onap.policies.optimization.AffinityPolicy: + derived_from: onap.policies.Optimization + properties: + policyScope: + type: list + description: scope where the policy is applicable + required: true + matchable: true + entry_schema: + type: string + policyType: + type: list + description: type of a policy + required: true + matchable: true + entry_schema: + type: string + consraints: + - valid_values: + - zone + identity: + type: string + required: true + applicableResources: + type: list + required: true + entry_schema: + type: string + constraints: + - valid_values: + - any + - all + affinityProperties: + type: policy.data.affinityProperties_properties + required: true + resources: + type: list + required: true + entry_schema: + type: string +data_types: + policy.data.affinityProperties_properties: + derived_from: tosca.nodes.Root + properties: + qualifier: + type: list + required: true + entry_schema: + type: string + constraints: + - valid_values: + - same + - different + category: + type: string + required: true diff --git a/models-examples/src/main/resources/policytypes/onap.policies.optimization.DistancePolicy.yaml b/models-examples/src/main/resources/policytypes/onap.policies.optimization.DistancePolicy.yaml new file mode 100644 index 000000000..93ddd631a --- /dev/null +++ b/models-examples/src/main/resources/policytypes/onap.policies.optimization.DistancePolicy.yaml @@ -0,0 +1,82 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +policy_types: + - onap.policies.Optimization: + derived_from: tosca.policies.Root + version: 1.0.0 + description: a base policy type for all policies that govern optimization + - onap.policies.optimization.DistancePolicy: + derived_from: onap.policies.Optimization + properties: + policyScope: + type: list + description: scope where the policy is applicable + required: true + matchable: true + entry_schema: + type: string + policyType: + type: list + description: type of a policy + required: true + matchable: true + entry_schema: + type: string + consraints: + - valid_values: + - distance_to_location + identity: + type: string + required: true + resources: + type: list + required: true + entry_schema: + type: string + applicableResources: + type: list + required: true + entry_schema: + type: string + constraints: + - valid_values: + - any + - all + distanceProperties: + type: policy.data.distanceProperties_properties + required: true +data_types: + policy.data.distanceProperties_properties: + derived_from: tosca.nodes.Root + properties: + locationInfo: + type: string + required: true + distance: + type: policy.data.distance_properties + required: true + policy.data.distance_properties: + derived_from: tosca.nodes.Root + properties: + value: + type: string + required: true + operator: + type: list + required: true + entry_schema: + type: string + constraints: + - valid_values: + - < + - <= + - '>' + - '>=' + - '=' + unit: + type: list + required: true + entry_schema: + type: string + constraints: + - valid_values: + - km diff --git a/models-examples/src/main/resources/policytypes/onap.policies.optimization.HpaPolicy.yaml b/models-examples/src/main/resources/policytypes/onap.policies.optimization.HpaPolicy.yaml new file mode 100644 index 000000000..63f0d8ada --- /dev/null +++ b/models-examples/src/main/resources/policytypes/onap.policies.optimization.HpaPolicy.yaml @@ -0,0 +1,131 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +policy_types: + - onap.policies.Optimization: + derived_from: tosca.policies.Root + version: 1.0.0 + description: a base policy type for all policies that govern optimization + - onap.policies.optimization.HpaPolicy: + derived_from: onap.policies.Optimization + properties: + policyScope: + type: list + description: scope where the policy is applicable + required: true + matchable: true + entry_schema: + type: string + policyType: + type: list + description: type of a policy + required: true + matchable: true + entry_schema: + type: string + consraints: + - valid_values: + - hpa + resources: + type: list + required: true + entry_schema: + type: string + identity: + type: string + required: true + flavorFeatures: + type: list + required: true + entry_schema: + type:policy.data.flavorFeatures_properties +data_types: + policy.data.flavorFeatures_properties: + derived_from: tosca.nodes.Root + properties: + id: + type: string + required: true + type: + type: string + required: true + directives: + type: list + required: true + entry_schema: + type: policy.data.directives_properties + flavorProperties: + type: list + required: true + entry_schema: + type: policy.data.flavorProperties_properties + policy.data.directives_properties: + derived_from: tosca.nodes.Root + properties: + type: + type: string + attributes: + type: list + entry_schema: + type: policy.data.directives_attributes_properties + policy.data.directives_attributes_properties: + derived_from: tosca.nodes.Root + properties: + attribute_name: + type: string + attribute_value: + type: string + policy.data.flavorProperties_properties: + derived_from: tosca.nodes.Root + properties: + hpa-feature: + type: string + required: true + mandatory: + type: string + required: true + score: + type: string + required: false + architecture: + type: string + required: true + hpa-version: + type: string + required: true + directives: + type: list + required: true + entry_schema: + type: policy.data.directives_properties + hpa-feature-attributes: + type: list + required: true + entry_schema: + type: policy.data.hpa-feature-attributes_properties + policy.data.hpa-feature-attributes_properties: + derived_from: tosca.nodes.Root + properties: + hpa-attribute-key: + type: string + required: true + hpa-attribute-value: + type: string + required: true + operator: + type: list + required: true + entry_schema: + type: string + constraints: + - valid_values: + - < + - <= + - '>' + - '>=' + - '=' + - '!=' + - any + - all + - subset + unit: + type: string + required: false diff --git a/models-examples/src/main/resources/policytypes/onap.policies.optimization.OptimizationPolicy.yaml b/models-examples/src/main/resources/policytypes/onap.policies.optimization.OptimizationPolicy.yaml new file mode 100644 index 000000000..edfac1496 --- /dev/null +++ b/models-examples/src/main/resources/policytypes/onap.policies.optimization.OptimizationPolicy.yaml @@ -0,0 +1,89 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +policy_types: + - onap.policies.Optimization: + derived_from: tosca.policies.Root + version: 1.0.0 + description: a base policy type for all policies that govern optimization + - onap.policies.optimization.OptimizationPolicy: + derived_from: onap.policies.Optimization + properties: + policyScope: + type: list + description: scope where the policy is applicable + required: true + matchable: true + entry_schema: + type: string + policyType: + type: list + description: type of a policy + required: true + matchable: true + entry_schema: + type: string + consraints: + - valid_values: + - placement_optimization + identity: + type: string + required: true + objective: + type: list + required: true + entry_schema: + type: string + constraints: + - valid_values: + - minimize + - maximize + objectiveParameter: + type: policy.data.objectiveParameter_properties + required: true +data_types: + policy.data.objectiveParameter_properties: + derived_from: tosca.nodes.Root + properties: + parameterAttributes: + type: list + required: true + entry_schema: + type: policy.data.parameterAttributes_properties + operator: + type: list + required: true + entry_schema: + type: string + constraints: + - valid_values: + - '*' + - + + - '-' + - / + - '%' + policy.data.parameterAttributes_properties: + derived_from: tosca.nodes.Root + properties: + resources: + type: string + required: true + customerLocationInfo: + type: string + required: true + parameter: + type: string + required: true + weight: + type: string + required: true + operator: + type: list + required: true + entry_schema: + type: string + constraints: + - valid_values: + - '*' + - + + - '-' + - / + - '%' diff --git a/models-examples/src/main/resources/policytypes/onap.policies.optimization.PciPolicy.yaml b/models-examples/src/main/resources/policytypes/onap.policies.optimization.PciPolicy.yaml new file mode 100644 index 000000000..1355eb031 --- /dev/null +++ b/models-examples/src/main/resources/policytypes/onap.policies.optimization.PciPolicy.yaml @@ -0,0 +1,58 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +policy_types: + - onap.policies.Optimization: + derived_from: tosca.policies.Root + version: 1.0.0 + description: a base policy type for all policies that govern optimization + - onap.policies.optimization.PciPolicy: + derived_from: onap.policies.Optimization + properties: + policyScope: + type: list + description: scope where the policy is applicable + required: true + matchable: true + entry_schema: + type: string + policyType: + type: list + description: type of a policy + required: true + matchable: true + entry_schema: + type: string + consraints: + - valid_values: + - pciPolicy + identity: + type: string + required: true + resources: + type: list + required: true + entry_schema: + type: string + pciProperties: + type: list + required: false + entry_schema: + - type:policy.data.pciProperties_properties +data_types: + policy.data.pciProperties_properties: + derived_from: tosca.nodes.Root + properties: + algoCategory: + type: string + required: false + pciOptmizationAlgoName: + type: string + required: false + pciOptimizationNwConstraint: + type: string + required: false + pciOptimizationPriority: + type: string + required: false + pciOptimizationTimeConstraint: + type: string + required: false diff --git a/models-examples/src/main/resources/policytypes/onap.policies.optimization.QueryPolicy.yaml b/models-examples/src/main/resources/policytypes/onap.policies.optimization.QueryPolicy.yaml new file mode 100644 index 000000000..f7036dc80 --- /dev/null +++ b/models-examples/src/main/resources/policytypes/onap.policies.optimization.QueryPolicy.yaml @@ -0,0 +1,47 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +policy_types: + - onap.policies.Optimization: + derived_from: tosca.policies.Root + version: 1.0.0 + description: a base policy type for all policies that govern optimization + - onap.policies.optimization.QueryPolicy: + derived_from: onap.policies.Optimization + properties: + policyScope: + type: list + description: scope where the policy is applicable + required: true + matchable: true + entry_schema: + type: string + policyType: + type: list + description: type of a policy + required: true + matchable: true + entry_schema: + type: string + consraints: + - valid_values: + - request_param_query + identity: + type: string + required: true + queryProperties: + type: list + required: true + entry_schema: + type:policy.data.queryProperties_properties +data_types: + policy.data.queryProperties_properties: + derived_from: tosca.nodes.Root + properties: + attribute: + type: string + required: true + value: + type: string + required: true + attribute_location: + type: string + required: true diff --git a/models-examples/src/main/resources/policytypes/onap.policies.optimization.SubscriberPolicy.yaml b/models-examples/src/main/resources/policytypes/onap.policies.optimization.SubscriberPolicy.yaml new file mode 100644 index 000000000..3c2c2b2c3 --- /dev/null +++ b/models-examples/src/main/resources/policytypes/onap.policies.optimization.SubscriberPolicy.yaml @@ -0,0 +1,51 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +policy_types: + - onap.policies.Optimization: + derived_from: tosca.policies.Root + version: 1.0.0 + description: a base policy type for all policies that govern optimization + - onap.policies.optimization.SubscriberPolicy: + derived_from: onap.policies.Optimization + properties: + policyScope: + type: list + description: scope where the policy is applicable + required: true + matchable: true + entry_schema: + type: string + policyType: + type: list + description: type of a policy + required: true + matchable: true + entry_schema: + type: string + consraints: + - valid_values: + - subscriberPolicy + identity: + type: string + required: true + properties: + type: policy.data.properties_properties + required: true +data_types: + policy.data.properties_properties: + derived_from: tosca.nodes.Root + properties: + subscriberName: + type: list + required: true + entry_schema: + type: string + subscriberRole: + type: list + required: true + entry_schema: + type: string + provStatus: + type: list + required: true + entry_schema: + type: string diff --git a/models-examples/src/main/resources/policytypes/onap.policies.optimization.Vim_fit.yaml b/models-examples/src/main/resources/policytypes/onap.policies.optimization.Vim_fit.yaml new file mode 100644 index 000000000..860c37fa0 --- /dev/null +++ b/models-examples/src/main/resources/policytypes/onap.policies.optimization.Vim_fit.yaml @@ -0,0 +1,56 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +policy_types: + - onap.policies.Optimization: + derived_from: tosca.policies.Root + version: 1.0.0 + description: a base policy type for all policies that govern optimization + - onap.policies.optimization.Vim_fit: + derived_from: onap.policies.Optimization + properties: + policyScope: + type: list + description: scope where the policy is applicable + required: true + matchable: true + entry_schema: + type: string + policyType: + type: list + description: type of a policy + required: true + matchable: true + entry_schema: + type: string + consraints: + - valid_values: + - vim_fit + identity: + type: string + required: true + applicableResources: + type: list + required: true + entry_schema: + type: string + constraints: + - valid_values: + - any + - all + resources: + type: list + required: true + entry_schema: + type: string + capacityProperties: + type: policy.data.capacityProperties_properties + required: true +data_types: + policy.data.capacityProperties_properties: + derived_from: tosca.nodes.Root + properties: + controller: + type: string + required: true + request: + type: string + required: true diff --git a/models-examples/src/main/resources/policytypes/onap.policies.optimization.VnfPolicy.yaml b/models-examples/src/main/resources/policytypes/onap.policies.optimization.VnfPolicy.yaml new file mode 100644 index 000000000..13d4f137c --- /dev/null +++ b/models-examples/src/main/resources/policytypes/onap.policies.optimization.VnfPolicy.yaml @@ -0,0 +1,73 @@ +tosca_definitions_version: tosca_simple_yaml_1_0_0 +policy_types: + - onap.policies.Optimization: + derived_from: tosca.policies.Root + version: 1.0.0 + description: a base policy type for all policies that govern optimization + - onap.policies.optimization.VnfPolicy: + derived_from: onap.policies.Optimization + properties: + policyScope: + type: list + description: scope where the policy is applicable + required: true + matchable: true + entry_schema: + type: string + policyType: + type: list + description: type of a policy + required: true + matchable: true + entry_schema: + type: string + consraints: + - valid_values: + - vnfPolicy + identity: + type: string + required: true + resources: + type: list + required: true + entry_schema: + type: string + applicableResources: + type: list + required: true + entry_schema: + type: string + constraints: + - valid_values: + - any + - all + vnfProperties: + type: list + required: true + entry_schema: + type:policy.data.vnfProperties_properties +data_types: + policy.data.vnfProperties_properties: + derived_from: tosca.nodes.Root + properties: + inventoryProvider: + type: string + required: true + serviceType: + type: string + required: true + inventoryType: + type: list + required: true + entry_schema: + type: string + constraints: + - valid_values: + - serviceInstanceId + - vnfName + - cloudRegionId + - vimId + customerId: + type: string + required: true + diff --git a/models-examples/src/main/resources/policytypes/onap.policy.monitoring.cdap.tca.hi.lo.app.yaml b/models-examples/src/main/resources/policytypes/onap.policy.monitoring.cdap.tca.hi.lo.app.yaml index 699cffd7e..f8e9b7521 100644 --- a/models-examples/src/main/resources/policytypes/onap.policy.monitoring.cdap.tca.hi.lo.app.yaml +++ b/models-examples/src/main/resources/policytypes/onap.policy.monitoring.cdap.tca.hi.lo.app.yaml @@ -1,8 +1,10 @@ tosca_definitions_version: tosca_simple_yaml_1_0_0 policy_types: + - onap.policies.Monitoring: derived_from: tosca.policies.Root description: a base policy type for all policies that governs monitoring provisioning + - onap.policy.monitoring.cdap.tca.hi.lo.app: derived_from: onap.policies.Monitoring version: 1.0.0 @@ -13,6 +15,7 @@ policy_types: entry_schema: type: onap.datatypes.monitoring.tca_policy data_types: + - onap.datatypes.monitoring.metricsPerEventName: derived_from: tosca.datatypes.Root properties: @@ -46,6 +49,7 @@ data_types: description: Thresholds associated with eventName entry_schema: type: onap.datatypes.monitoring.thresholds + - onap.datatypes.monitoring.tca_policy: derived_from: tosca.datatypes.Root properties: @@ -62,6 +66,7 @@ data_types: description: Contains eventName and threshold details that need to be applied to given eventName entry_schema: type: onap.datatypes.monitoring.metricsPerEventName + - onap.datatypes.monitoring.thresholds: derived_from: tosca.datatypes.Root properties: @@ -155,4 +160,4 @@ data_types: version: type: string required: true - description: Version number associated with the threshold + description: Version number associated with the threshold
\ No newline at end of file diff --git a/models-pap/src/test/java/org/onap/policy/models/pap/concepts/TestPolicy.java b/models-pap/src/main/java/org/onap/policy/models/pap/concepts/PdpDeployPolicies.java index 6a042d3be..1f4339f15 100644 --- a/models-pap/src/test/java/org/onap/policy/models/pap/concepts/TestPolicy.java +++ b/models-pap/src/main/java/org/onap/policy/models/pap/concepts/PdpDeployPolicies.java @@ -20,30 +20,20 @@ package org.onap.policy.models.pap.concepts; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; +import java.util.List; -import org.junit.Test; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; /** - * Test the copy constructor, as {@link TestModels} tests the other methods. + * Request deploy or update a set of policies using the <i>simple</i> PDP Group deployment + * REST API. Only the "name" and "policyVersion" fields of a Policy are used, and only the + * "name" field is actually required. */ -public class TestPolicy { - - @Test - public void testCopyConstructor() { - assertThatThrownBy(() -> new Policy(null)).isInstanceOf(NullPointerException.class); - - Policy orig = new Policy(); - - // verify with null values - assertEquals(orig.toString(), new Policy(orig).toString()); - - // verify with all values - orig.setName("my-name"); - orig.setPolicyType("my-type"); - orig.setPolicyTypeImpl("my-impl"); - orig.setPolicyTypeVersion("my-type-vers"); - assertEquals(orig.toString(), new Policy(orig).toString()); - } +@Getter +@Setter +@ToString +public class PdpDeployPolicies { + private List<PolicyIdentOptVersion> policies; } diff --git a/models-pap/src/main/java/org/onap/policy/models/pap/concepts/PdpGroup.java b/models-pap/src/main/java/org/onap/policy/models/pap/concepts/PdpGroup.java index d5e4191a2..29c4713db 100644 --- a/models-pap/src/main/java/org/onap/policy/models/pap/concepts/PdpGroup.java +++ b/models-pap/src/main/java/org/onap/policy/models/pap/concepts/PdpGroup.java @@ -21,14 +21,11 @@ package org.onap.policy.models.pap.concepts; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import lombok.Getter; -import lombok.NonNull; import lombok.Setter; import lombok.ToString; -import org.onap.policy.models.base.PfUtils; import org.onap.policy.models.pdp.enums.PdpState; /** @@ -47,25 +44,4 @@ public class PdpGroup { private String description; private Map<String, String> properties; private List<PdpSubGroup> pdpSubgroups; - - /** - * Constructs the object. - */ - public PdpGroup() { - super(); - } - - /** - * Constructs the object, making a deep copy from the source. - * - * @param source source from which to copy fields - */ - public PdpGroup(@NonNull PdpGroup source) { - this.name = source.name; - this.version = source.version; - this.pdpGroupState = source.pdpGroupState; - this.description = source.description; - this.properties = (source.properties == null ? null : new LinkedHashMap<>(source.properties)); - this.pdpSubgroups = PfUtils.mapList(source.pdpSubgroups, PdpSubGroup::new); - } } diff --git a/models-pap/src/main/java/org/onap/policy/models/pap/concepts/PdpInstanceDetails.java b/models-pap/src/main/java/org/onap/policy/models/pap/concepts/PdpInstanceDetails.java index c214c7409..d5846160c 100644 --- a/models-pap/src/main/java/org/onap/policy/models/pap/concepts/PdpInstanceDetails.java +++ b/models-pap/src/main/java/org/onap/policy/models/pap/concepts/PdpInstanceDetails.java @@ -22,7 +22,6 @@ package org.onap.policy.models.pap.concepts; import lombok.Getter; -import lombok.NonNull; import lombok.Setter; import lombok.ToString; import org.onap.policy.models.pdp.enums.PdpHealthStatus; @@ -42,23 +41,4 @@ public class PdpInstanceDetails { private PdpState pdpState; private PdpHealthStatus healthy; private String message; - - /** - * Constructs the object. - */ - public PdpInstanceDetails() { - super(); - } - - /** - * Constructs the object, making a deep copy from the source. - * - * @param source source from which to copy fields - */ - public PdpInstanceDetails(@NonNull PdpInstanceDetails source) { - this.instanceId = source.instanceId; - this.pdpState = source.pdpState; - this.healthy = source.healthy; - this.message = source.message; - } } diff --git a/models-pap/src/main/java/org/onap/policy/models/pap/concepts/PdpPolicies.java b/models-pap/src/main/java/org/onap/policy/models/pap/concepts/PdpPolicies.java index e5ae24d0f..3111becca 100644 --- a/models-pap/src/main/java/org/onap/policy/models/pap/concepts/PdpPolicies.java +++ b/models-pap/src/main/java/org/onap/policy/models/pap/concepts/PdpPolicies.java @@ -26,6 +26,7 @@ import lombok.Getter; import lombok.Setter; import lombok.ToString; +// TODO delete this once PAP has been modified to use PdpDeployPolicies /** * Request deploy or update a set of policies using the <i>simple</i> PDP Group deployment * REST API. Only the "name" and "policyVersion" fields of a Policy are used, and only the diff --git a/models-pap/src/main/java/org/onap/policy/models/pap/concepts/PdpSubGroup.java b/models-pap/src/main/java/org/onap/policy/models/pap/concepts/PdpSubGroup.java index 43356982e..9989d2516 100644 --- a/models-pap/src/main/java/org/onap/policy/models/pap/concepts/PdpSubGroup.java +++ b/models-pap/src/main/java/org/onap/policy/models/pap/concepts/PdpSubGroup.java @@ -21,15 +21,11 @@ package org.onap.policy.models.pap.concepts; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import lombok.Getter; -import lombok.NonNull; import lombok.Setter; import lombok.ToString; -import org.onap.policy.models.base.PfUtils; -import org.onap.policy.models.base.keys.PolicyTypeIdent; /** * Class to represent a group of all PDP's of the same pdp type running for a particular @@ -49,26 +45,4 @@ public class PdpSubGroup { private int desiredInstanceCount; private Map<String, String> properties; private List<PdpInstanceDetails> pdpInstances; - - /** - * Constructs the object. - */ - public PdpSubGroup() { - super(); - } - - /** - * Constructs the object, making a deep copy from the source. - * - * @param source source from which to copy fields - */ - public PdpSubGroup(@NonNull PdpSubGroup source) { - this.pdpType = source.pdpType; - this.supportedPolicyTypes = PfUtils.mapList(source.supportedPolicyTypes, PolicyTypeIdent::new); - this.policies = PfUtils.mapList(source.policies, Policy::new); - this.currentInstanceCount = source.currentInstanceCount; - this.desiredInstanceCount = source.desiredInstanceCount; - this.properties = (source.properties == null ? null : new LinkedHashMap<>(source.properties)); - this.pdpInstances = PfUtils.mapList(source.pdpInstances, PdpInstanceDetails::new); - } } diff --git a/models-pap/src/main/java/org/onap/policy/models/pap/concepts/Policy.java b/models-pap/src/main/java/org/onap/policy/models/pap/concepts/Policy.java index b83510e83..541eb2435 100644 --- a/models-pap/src/main/java/org/onap/policy/models/pap/concepts/Policy.java +++ b/models-pap/src/main/java/org/onap/policy/models/pap/concepts/Policy.java @@ -22,7 +22,6 @@ package org.onap.policy.models.pap.concepts; import lombok.Getter; -import lombok.NonNull; import lombok.Setter; import lombok.ToString; @@ -41,24 +40,4 @@ public class Policy { private String policyType; private String policyTypeVersion; private String policyTypeImpl; - - /** - * Constructs the object. - */ - public Policy() { - super(); - } - - /** - * Constructs the object, making a deep copy from the source. - * - * @param source source from which to copy fields - */ - public Policy(@NonNull Policy source) { - this.name = source.name; - this.policyVersion = source.policyVersion; - this.policyType = source.policyType; - this.policyTypeVersion = source.policyTypeVersion; - this.policyTypeImpl = source.policyTypeImpl; - } } diff --git a/models-pap/src/main/java/org/onap/policy/models/pap/concepts/PolicyIdent.java b/models-pap/src/main/java/org/onap/policy/models/pap/concepts/PolicyIdent.java new file mode 100644 index 000000000..2eb9df136 --- /dev/null +++ b/models-pap/src/main/java/org/onap/policy/models/pap/concepts/PolicyIdent.java @@ -0,0 +1,36 @@ +/* + * ============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.pap.concepts; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * Identifies a policy. Both the name and version must be non-null. + */ +@Getter +@Setter +@ToString +public class PolicyIdent { + private String name; + private String version; +} diff --git a/models-pap/src/main/java/org/onap/policy/models/pap/concepts/PolicyIdentOptVersion.java b/models-pap/src/main/java/org/onap/policy/models/pap/concepts/PolicyIdentOptVersion.java new file mode 100644 index 000000000..ecac2a27e --- /dev/null +++ b/models-pap/src/main/java/org/onap/policy/models/pap/concepts/PolicyIdentOptVersion.java @@ -0,0 +1,39 @@ +/* + * ============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.pap.concepts; + +import lombok.Getter; +import lombok.NonNull; +import lombok.Setter; +import lombok.ToString; + +/** + * Policy identifier with an optional version; only the "name" is required. + */ +@Getter +@Setter +@ToString +public class PolicyIdentOptVersion { + @NonNull + private String name; + + private String version; +} diff --git a/models-pap/src/main/java/org/onap/policy/models/pap/concepts/PolicyTypeIdent.java b/models-pap/src/main/java/org/onap/policy/models/pap/concepts/PolicyTypeIdent.java new file mode 100644 index 000000000..3d466b7f5 --- /dev/null +++ b/models-pap/src/main/java/org/onap/policy/models/pap/concepts/PolicyTypeIdent.java @@ -0,0 +1,38 @@ +/* + * ============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.pap.concepts; + +import lombok.Getter; +import lombok.NonNull; +import lombok.Setter; +import lombok.ToString; + +/** + * Identifies a policy type. Both the name and version must be non-null. + */ +@Getter +@Setter +@ToString +@NonNull +public class PolicyTypeIdent { + private String name; + private String version; +} diff --git a/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpGroup.java b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpGroup.java new file mode 100644 index 000000000..4a26b16dd --- /dev/null +++ b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpGroup.java @@ -0,0 +1,70 @@ +/* + * ============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.pdp.concepts; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.ToString; +import org.onap.policy.models.base.PfUtils; +import org.onap.policy.models.pdp.enums.PdpState; +import org.onap.policy.models.tosca.simple.concepts.ToscaEntityType; + +/** + * Class to represent a PDPGroup, which groups multiple PDPSubGroup entities together for + * a particular domain. + * + * @author Ram Krishna Verma (ram.krishna.verma@est.tech) + */ +@Getter +@Setter +@ToString +@NoArgsConstructor +public class PdpGroup extends ToscaEntityType { + private static final long serialVersionUID = 1L; + + private PdpState pdpGroupState; + private Map<String, String> properties; + private List<PdpSubGroup> pdpSubgroups; + + /* + * Note: removed "@NotNull" annotation from the constructor argument, because it + * cannot be covered by a junit test, as the superclass does the check and throws an + * exception first. + */ + + /** + * Constructs the object, making a deep copy from the source. + * + * @param source source from which to copy fields + */ + public PdpGroup(PdpGroup source) { + super(source); + this.pdpGroupState = source.pdpGroupState; + this.properties = (source.properties == null ? null : new LinkedHashMap<>(source.properties)); + this.pdpSubgroups = PfUtils.mapList(source.pdpSubgroups, PdpSubGroup::new); + } +} diff --git a/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpGroups.java b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpGroups.java new file mode 100644 index 000000000..ea1c8ff55 --- /dev/null +++ b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpGroups.java @@ -0,0 +1,37 @@ +/* + * ============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.pdp.concepts; + +import java.util.List; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * Request deploy or update a set of groups via the PDP Group deployment + * REST API. + */ +@Getter +@Setter +@ToString +public class PdpGroups { + private List<PdpGroup> groups; +} diff --git a/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpInstanceDetails.java b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpInstanceDetails.java new file mode 100644 index 000000000..6cf122e19 --- /dev/null +++ b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpInstanceDetails.java @@ -0,0 +1,63 @@ +/* + * ============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.pdp.concepts; + +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.NonNull; +import lombok.Setter; +import lombok.ToString; +import org.onap.policy.models.pdp.enums.PdpHealthStatus; +import org.onap.policy.models.pdp.enums.PdpState; + +/** + * Class to represent details of a running instance of PDP. + * + * @author Ram Krishna Verma (ram.krishna.verma@est.tech) + */ +@Getter +@Setter +@ToString +@NoArgsConstructor +public class PdpInstanceDetails { + + @NonNull + private String instanceId; + + @NonNull + private PdpState pdpState; + + private PdpHealthStatus healthy; + private String message; + + /** + * Constructs the object, creating a deep copy of the fields from the source. + * + * @param source source from which to copy the fields + */ + public PdpInstanceDetails(PdpInstanceDetails source) { + this.instanceId = source.instanceId; + this.pdpState = source.pdpState; + this.healthy = source.healthy; + this.message = source.message; + } +} diff --git a/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpStatus.java b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpStatus.java index f7b911fc4..814d35732 100644 --- a/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpStatus.java +++ b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpStatus.java @@ -25,7 +25,6 @@ import java.util.List; import lombok.Getter; import lombok.Setter; import lombok.ToString; -import org.onap.policy.models.base.keys.PolicyTypeIdent; import org.onap.policy.models.pdp.enums.PdpHealthStatus; import org.onap.policy.models.pdp.enums.PdpMessageType; import org.onap.policy.models.pdp.enums.PdpState; diff --git a/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpSubGroup.java b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpSubGroup.java new file mode 100644 index 000000000..0466c6300 --- /dev/null +++ b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PdpSubGroup.java @@ -0,0 +1,76 @@ +/* + * ============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.pdp.concepts; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import lombok.Getter; +import lombok.NonNull; +import lombok.Setter; +import lombok.ToString; +import org.onap.policy.models.base.PfUtils; +import org.onap.policy.models.tosca.simple.concepts.ToscaPolicy; + +/** + * Class to represent a group of all PDP's of the same pdp type running for a particular + * domain. + * + * @author Ram Krishna Verma (ram.krishna.verma@est.tech) + */ +@Getter +@Setter +@ToString +public class PdpSubGroup { + + // TODO subclass from ToscaEntityType + + private String pdpType; + private List<PolicyTypeIdent> supportedPolicyTypes; + private List<ToscaPolicy> policies; + private int currentInstanceCount; + private int desiredInstanceCount; + private Map<String, String> properties; + private List<PdpInstanceDetails> pdpInstances; + + /** + * Constructs the object. + */ + public PdpSubGroup() { + super(); + } + + /** + * Constructs the object, making a deep copy from the source. + * + * @param source source from which to copy fields + */ + public PdpSubGroup(@NonNull PdpSubGroup source) { + this.pdpType = source.pdpType; + this.supportedPolicyTypes = PfUtils.mapList(source.supportedPolicyTypes, PolicyTypeIdent::new); + this.policies = PfUtils.mapList(source.policies, ToscaPolicy::new); + this.currentInstanceCount = source.currentInstanceCount; + this.desiredInstanceCount = source.desiredInstanceCount; + this.properties = (source.properties == null ? null : new LinkedHashMap<>(source.properties)); + this.pdpInstances = PfUtils.mapList(source.pdpInstances, PdpInstanceDetails::new); + } +} diff --git a/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PolicyIdent.java b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PolicyIdent.java new file mode 100644 index 000000000..6d6b6fedd --- /dev/null +++ b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PolicyIdent.java @@ -0,0 +1,50 @@ +/* + * ============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.pdp.concepts; + +import lombok.NoArgsConstructor; +import lombok.NonNull; +import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.base.PfValidationResult; +import org.onap.policy.models.base.Validated; + +/** + * Identifies a policy. Both the name and version must be non-null. + */ +@NonNull +@NoArgsConstructor +public class PolicyIdent extends PfConceptKey { + private static final long serialVersionUID = 1L; + private static final Validated validator = new Validated(); + + public PolicyIdent(String name, String version) { + super(name, version); + } + + public PolicyIdent(PolicyIdent source) { + super(source); + } + + @Override + public PfValidationResult validate(PfValidationResult result) { + return super.validate(validator.validateNotNull(this, result)); + } +} diff --git a/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PolicyIdentOptVersion.java b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PolicyIdentOptVersion.java new file mode 100644 index 000000000..a68a271f2 --- /dev/null +++ b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PolicyIdentOptVersion.java @@ -0,0 +1,61 @@ +/* + * ============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.pdp.concepts; + +import lombok.NoArgsConstructor; +import lombok.NonNull; +import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.base.PfKey; +import org.onap.policy.models.base.PfValidationResult; +import org.onap.policy.models.base.Validated; + +/** + * Policy identifier with an optional version; only the "name" is required. + */ +@NonNull +@NoArgsConstructor +public class PolicyIdentOptVersion extends PfConceptKey { + private static final long serialVersionUID = 1L; + private static final Validated validator = new Validated(); + + + public PolicyIdentOptVersion(PolicyIdentOptVersion source) { + super(source); + } + + /** + * Validates the object. + * + * @param resultIn where to place any errors + * @return a validation result + */ + public PfValidationResult validate(@NonNull final PfValidationResult resultIn) { + PfValidationResult result = resultIn; + + String name = getName(); + if (PfConceptKey.NULL_KEY_NAME.equals(name)) { + validator.addError(this, "name", result, "null"); + } + result = validator.validateText(this, "name", name, PfKey.NAME_REGEXP, result); + + return validator.validateText(this, "version", getVersion(), PfKey.VERSION_REGEXP, result); + } +} diff --git a/models-base/src/main/java/org/onap/policy/models/base/keys/PolicyTypeIdent.java b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PolicyTypeIdent.java index 09e03816e..ef67de86e 100644 --- a/models-base/src/main/java/org/onap/policy/models/base/keys/PolicyTypeIdent.java +++ b/models-pdp/src/main/java/org/onap/policy/models/pdp/concepts/PolicyTypeIdent.java @@ -18,11 +18,13 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.models.base.keys; +package org.onap.policy.models.pdp.concepts; import lombok.NoArgsConstructor; import lombok.NonNull; import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.base.PfValidationResult; +import org.onap.policy.models.base.Validated; /** * Identifies a policy type. Both the name and version must be non-null. @@ -31,6 +33,7 @@ import org.onap.policy.models.base.PfConceptKey; @NoArgsConstructor public class PolicyTypeIdent extends PfConceptKey { private static final long serialVersionUID = 1L; + private static final Validated validator = new Validated(); public PolicyTypeIdent(String name, String version) { super(name, version); @@ -39,4 +42,9 @@ public class PolicyTypeIdent extends PfConceptKey { public PolicyTypeIdent(PolicyTypeIdent source) { super(source); } + + @Override + public PfValidationResult validate(PfValidationResult result) { + return super.validate(validator.validateNotNull(this, result)); + } } diff --git a/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/IdentTestBase.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/IdentTestBase.java new file mode 100644 index 000000000..10bc9a997 --- /dev/null +++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/IdentTestBase.java @@ -0,0 +1,81 @@ +/* + * ============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.pdp.concepts; + +import org.onap.policy.common.utils.coder.Coder; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.common.utils.coder.StandardCoder; + +/** + * Super class to test identity keys. + * + * @param <T> type of key being tested + */ +public class IdentTestBase<T> { + + private static final Coder coder = new StandardCoder(); + + private final Class<T> clazz; + + + /** + * Constructs the object. + * @param clazz the type of class being tested + */ + public IdentTestBase(Class<T> clazz) { + this.clazz = clazz; + } + + /** + * Makes an identifier. Uses JSON which does no error checking. + * + * @param name name to put into the identifier + * @param version version to put into the identifier + * @return a new identifier + * @throws CoderException if the JSON cannot be decoded + */ + public T makeIdent(String name, String version) throws CoderException { + StringBuilder bldr = new StringBuilder(); + bldr.append("{"); + + if (name != null) { + bldr.append("'name':'"); + bldr.append(name); + bldr.append("'"); + } + + if (version != null) { + if (name != null) { + bldr.append(','); + } + + bldr.append("'version':'"); + bldr.append(version); + bldr.append("'"); + } + + bldr.append("}"); + + String json = bldr.toString().replace('\'', '"'); + + return coder.decode(json, clazz); + } +} diff --git a/models-pap/src/test/java/org/onap/policy/models/pap/concepts/TestPdpGroup.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/TestPdpGroup.java index ee52d82fb..51bb66c97 100644 --- a/models-pap/src/test/java/org/onap/policy/models/pap/concepts/TestPdpGroup.java +++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/TestPdpGroup.java @@ -1,8 +1,9 @@ -/* +/*- * ============LICENSE_START======================================================= * ONAP Policy Models * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications 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. @@ -18,10 +19,11 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.models.pap.concepts; +package org.onap.policy.models.pdp.concepts; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.Map; @@ -41,11 +43,11 @@ public class TestPdpGroup { PdpGroup orig = new PdpGroup(); // verify with null values - assertEquals(orig.toString(), new PdpGroup(orig).toString()); + assertEquals("PdpGroup(pdpGroupState=null, properties=null, pdpSubgroups=[])", new PdpGroup(orig).toString()); // verify with all values orig.setDescription("my-descript"); - orig.setName("my-name"); + orig.getKey().setName("my-name"); orig.setPdpGroupState(PdpState.SAFE); PdpSubGroup sub1 = new PdpSubGroup(); @@ -59,8 +61,22 @@ public class TestPdpGroup { props.put("key-B", "value-B"); orig.setProperties(props); - System.out.println("orig=" + orig); + assertEquals("PdpGroup(pdpGroupState=SAFE, properties={key-A=value-A, key-B=value-B}, " + + "pdpSubgroups=[PdpSubGroup(pdpType=null, supportedPolicyTypes=[], policies=[], " + + "currentInstanceCount=10, desiredInstanceCount=0, properties=null, pdpInstances=[]), " + + "PdpSubGroup(pdpType=null, supportedPolicyTypes=[], policies=[], currentInstanceCount=11, " + + "desiredInstanceCount=0, properties=null, pdpInstances=[])])", new PdpGroup(orig).toString()); + } + + @Test + public void testHashCode() { + PdpGroup group = new PdpGroup(); + group.setDescription("A"); + int hash = group.hashCode(); + + assertEquals(hash, group.hashCode()); - assertEquals(orig.toString(), new PdpGroup(orig).toString()); + group.setDescription("B"); + assertTrue(hash != group.hashCode()); } } diff --git a/models-pap/src/test/java/org/onap/policy/models/pap/concepts/TestPdpInstanceDetails.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/TestPdpInstanceDetails.java index 65fbef612..2220ae126 100644 --- a/models-pap/src/test/java/org/onap/policy/models/pap/concepts/TestPdpInstanceDetails.java +++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/TestPdpInstanceDetails.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.models.pap.concepts; +package org.onap.policy.models.pdp.concepts; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; @@ -43,9 +43,10 @@ public class TestPdpInstanceDetails { // verify with all values orig.setHealthy(PdpHealthStatus.TEST_IN_PROGRESS); - orig.setInstanceId("my-id"); + orig.setInstanceId("my-instance"); orig.setMessage("my-message"); orig.setPdpState(PdpState.SAFE); + assertEquals(orig.toString(), new PdpInstanceDetails(orig).toString()); } } diff --git a/models-pap/src/test/java/org/onap/policy/models/pap/concepts/TestPdpSubGroup.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/TestPdpSubGroup.java index 9af2f4e9d..bc6363fae 100644 --- a/models-pap/src/test/java/org/onap/policy/models/pap/concepts/TestPdpSubGroup.java +++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/TestPdpSubGroup.java @@ -1,8 +1,9 @@ -/* +/*- * ============LICENSE_START======================================================= * ONAP Policy Models * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications 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. @@ -18,7 +19,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.models.pap.concepts; +package org.onap.policy.models.pdp.concepts; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; @@ -27,7 +28,7 @@ import java.util.Arrays; import java.util.Map; import java.util.TreeMap; import org.junit.Test; -import org.onap.policy.models.base.keys.PolicyTypeIdent; +import org.onap.policy.models.tosca.simple.concepts.ToscaPolicy; /** * Test the copy constructor, as {@link TestModels} tests the other methods. @@ -41,7 +42,10 @@ public class TestPdpSubGroup { PdpSubGroup orig = new PdpSubGroup(); // verify with null values - assertEquals(orig.toString(), new PdpSubGroup(orig).toString()); + assertEquals( + "PdpSubGroup(pdpType=null, supportedPolicyTypes=[], policies=[], " + + "currentInstanceCount=0, desiredInstanceCount=0, properties=null, pdpInstances=[])", + new PdpSubGroup(orig).toString()); // verify with all values orig.setCurrentInstanceCount(10); @@ -55,10 +59,10 @@ public class TestPdpSubGroup { orig.setPdpType("my-type"); - Policy pol1 = new Policy(); - pol1.setName("policy-A"); - Policy pol2 = new Policy(); - pol2.setName("policy-B"); + ToscaPolicy pol1 = new ToscaPolicy(); + pol1.setDescription("policy-A"); + ToscaPolicy pol2 = new ToscaPolicy(); + pol2.setDescription("policy-B"); orig.setPolicies(Arrays.asList(pol1, pol2)); Map<String, String> props = new TreeMap<>(); diff --git a/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/TestPolicyIdent.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/TestPolicyIdent.java new file mode 100644 index 000000000..4cd5570e2 --- /dev/null +++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/TestPolicyIdent.java @@ -0,0 +1,90 @@ +/* + * ============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.pdp.concepts; + +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.assertTrue; + +import org.junit.Test; +import org.onap.policy.models.base.PfValidationResult; + +/** + * Test the other constructors, as {@link TestModels} tests the other methods. + */ +public class TestPolicyIdent extends IdentTestBase<PolicyIdent> { + private static final String NAME = "my-name"; + private static final String VERSION = "1.2.3"; + + public TestPolicyIdent() { + super(PolicyIdent.class); + } + + @Test + public void testAllArgsConstructor() { + assertThatThrownBy(() -> new PolicyIdent(null, VERSION)).isInstanceOf(NullPointerException.class); + assertThatThrownBy(() -> new PolicyIdent(NAME, null)).isInstanceOf(NullPointerException.class); + + PolicyIdent orig = new PolicyIdent(NAME, VERSION); + assertEquals(NAME, orig.getName()); + assertEquals(VERSION, orig.getVersion()); + } + + @Test + public void testCopyConstructor() { + assertThatThrownBy(() -> new PolicyIdent(null)).isInstanceOf(NullPointerException.class); + + PolicyIdent orig = new PolicyIdent(); + + // verify with null values + assertEquals(orig.toString(), new PolicyIdent(orig).toString()); + + // verify with all values + orig = new PolicyIdent(NAME, VERSION); + assertEquals(orig.toString(), new PolicyIdent(orig).toString()); + } + + @Test + public void testValidate() throws Exception { + assertTrue(makeIdent(NAME, VERSION).validate(new PfValidationResult()).isValid()); + + // everything is null + PfValidationResult result = makeIdent(null, null).validate(new PfValidationResult()); + assertFalse(result.isValid()); + assertEquals(2, result.getMessageList().size()); + + // name is null + result = makeIdent(null, VERSION).validate(new PfValidationResult()); + assertFalse(result.isValid()); + assertEquals(1, result.getMessageList().size()); + + // version is null + result = makeIdent(NAME, null).validate(new PfValidationResult()); + assertFalse(result.isValid()); + assertEquals(1, result.getMessageList().size()); + + // version is invalid + result = makeIdent(NAME, "!!!" + VERSION).validate(new PfValidationResult()); + assertFalse(result.isValid()); + assertEquals(1, result.getMessageList().size()); + } +} diff --git a/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/TestPolicyIdentOptVersion.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/TestPolicyIdentOptVersion.java new file mode 100644 index 000000000..3428ac1be --- /dev/null +++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/TestPolicyIdentOptVersion.java @@ -0,0 +1,87 @@ +/* + * ============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.pdp.concepts; + +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.assertTrue; + +import org.junit.Test; +import org.onap.policy.models.base.PfValidationResult; + +/** + * Test the other constructors, as {@link TestModels} tests the other methods. + */ +public class TestPolicyIdentOptVersion extends IdentTestBase<PolicyIdentOptVersion> { + private static final String NAME = "my-name"; + private static final String VERSION = "1.2.3"; + + public TestPolicyIdentOptVersion() { + super(PolicyIdentOptVersion.class); + } + + @Test + public void testCopyConstructor() throws Exception { + assertThatThrownBy(() -> new PolicyIdentOptVersion(null)).isInstanceOf(NullPointerException.class); + + PolicyIdentOptVersion orig = new PolicyIdentOptVersion(); + + // verify with null values + assertEquals(orig.toString(), new PolicyIdentOptVersion(orig).toString()); + + // verify with all values + orig = makeIdent(NAME, VERSION); + assertEquals(orig.toString(), new PolicyIdentOptVersion(orig).toString()); + } + + @Test + public void testValidate() throws Exception { + assertThatThrownBy(() -> makeIdent(NAME, VERSION).validate(null)).isInstanceOf(NullPointerException.class); + assertTrue(makeIdent(NAME, VERSION).validate(new PfValidationResult()).isValid()); + assertTrue(makeIdent(NAME, null).validate(new PfValidationResult()).isValid()); + + // everything is null + PfValidationResult result = makeIdent(null, null).validate(new PfValidationResult()); + assertFalse(result.isValid()); + assertEquals(1, result.getMessageList().size()); + + // name is null + result = makeIdent(null, VERSION).validate(new PfValidationResult()); + assertFalse(result.isValid()); + assertEquals(1, result.getMessageList().size()); + + // name is null, version is invalid + result = makeIdent(null, "$$$" + VERSION).validate(new PfValidationResult()); + assertFalse(result.isValid()); + assertEquals(2, result.getMessageList().size()); + + // name is invalid + result = makeIdent("!!!invalid name$$$", VERSION).validate(new PfValidationResult()); + assertFalse(result.isValid()); + assertEquals(1, result.getMessageList().size()); + + // version is invalid + result = makeIdent(NAME, "!!!" + VERSION).validate(new PfValidationResult()); + assertFalse(result.isValid()); + assertEquals(1, result.getMessageList().size()); + } +} diff --git a/models-base/src/test/java/org/onap/policy/models/base/keys/TestPolicyTypeIdent.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/TestPolicyTypeIdent.java index 1638a87da..5b7494ebf 100644 --- a/models-base/src/test/java/org/onap/policy/models/base/keys/TestPolicyTypeIdent.java +++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/concepts/TestPolicyTypeIdent.java @@ -18,22 +18,27 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.models.base.keys; +package org.onap.policy.models.pdp.concepts; 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.assertTrue; import org.junit.Test; -import org.onap.policy.models.base.keys.PolicyTypeIdent; -import org.onap.policy.models.base.keys.TestModels; +import org.onap.policy.models.base.PfValidationResult; /** * Test the other constructors, as {@link TestModels} tests the other methods. */ -public class TestPolicyTypeIdent { +public class TestPolicyTypeIdent extends IdentTestBase<PolicyTypeIdent> { private static final String NAME = "my-name"; private static final String VERSION = "1.2.3"; + public TestPolicyTypeIdent() { + super(PolicyTypeIdent.class); + } + @Test public void testAllArgsConstructor() { assertThatThrownBy(() -> new PolicyTypeIdent(null, VERSION)).isInstanceOf(NullPointerException.class); @@ -57,4 +62,30 @@ public class TestPolicyTypeIdent { orig = new PolicyTypeIdent(NAME, VERSION); assertEquals(orig.toString(), new PolicyTypeIdent(orig).toString()); } + + @Test + public void testValidate() throws Exception { + assertTrue(makeIdent(NAME, VERSION).validate(new PfValidationResult()).isValid()); + + // everything is null + PfValidationResult result = makeIdent(null, null).validate(new PfValidationResult()); + assertFalse(result.isValid()); + assertEquals(2, result.getMessageList().size()); + + // name is null + result = makeIdent(null, VERSION).validate(new PfValidationResult()); + assertFalse(result.isValid()); + assertEquals(1, result.getMessageList().size()); + + // version is null + result = makeIdent(NAME, null).validate(new PfValidationResult()); + assertFalse(result.isValid()); + assertEquals(1, result.getMessageList().size()); + + // version is invalid + result = makeIdent(NAME, "!!!" + VERSION).validate(new PfValidationResult()); + assertFalse(result.isValid()); + assertEquals(1, result.getMessageList().size()); + } + } diff --git a/models-provider/src/main/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderImpl.java b/models-provider/src/main/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderImpl.java index 970aa8fef..43f75d2a9 100644 --- a/models-provider/src/main/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderImpl.java +++ b/models-provider/src/main/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderImpl.java @@ -41,7 +41,7 @@ import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.provider.PolicyModelsProviderParameters; import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicy; import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy; -import org.onap.policy.models.tosca.legacy.provider.LegacyToscaProvider; +import org.onap.policy.models.tosca.legacy.provider.LegacyProvider; import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate; import org.onap.policy.models.tosca.simple.provider.SimpleToscaProvider; import org.slf4j.Logger; @@ -190,53 +190,53 @@ public class DatabasePolicyModelsProviderImpl implements PolicyModelsProvider { @Override public LegacyOperationalPolicy getOperationalPolicy(@NonNull final String policyId) throws PfModelException { assertInitilized(); - return new LegacyToscaProvider().getOperationalPolicy(pfDao, policyId); + return new LegacyProvider().getOperationalPolicy(pfDao, policyId); } @Override public LegacyOperationalPolicy createOperationalPolicy( @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException { assertInitilized(); - return new LegacyToscaProvider().createOperationalPolicy(pfDao, legacyOperationalPolicy); + return new LegacyProvider().createOperationalPolicy(pfDao, legacyOperationalPolicy); } @Override public LegacyOperationalPolicy updateOperationalPolicy( @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException { assertInitilized(); - return new LegacyToscaProvider().updateOperationalPolicy(pfDao, legacyOperationalPolicy); + return new LegacyProvider().updateOperationalPolicy(pfDao, legacyOperationalPolicy); } @Override public LegacyOperationalPolicy deleteOperationalPolicy(@NonNull final String policyId) throws PfModelException { assertInitilized(); - return new LegacyToscaProvider().deleteOperationalPolicy(pfDao, policyId); + return new LegacyProvider().deleteOperationalPolicy(pfDao, policyId); } @Override public LegacyGuardPolicy getGuardPolicy(@NonNull final String policyId) throws PfModelException { assertInitilized(); - return new LegacyToscaProvider().getGuardPolicy(pfDao, policyId); + return new LegacyProvider().getGuardPolicy(pfDao, policyId); } @Override public LegacyGuardPolicy createGuardPolicy(@NonNull final LegacyGuardPolicy legacyGuardPolicy) throws PfModelException { assertInitilized(); - return new LegacyToscaProvider().createGuardPolicy(pfDao, legacyGuardPolicy); + return new LegacyProvider().createGuardPolicy(pfDao, legacyGuardPolicy); } @Override public LegacyGuardPolicy updateGuardPolicy(@NonNull final LegacyGuardPolicy legacyGuardPolicy) throws PfModelException { assertInitilized(); - return new LegacyToscaProvider().updateGuardPolicy(pfDao, legacyGuardPolicy); + return new LegacyProvider().updateGuardPolicy(pfDao, legacyGuardPolicy); } @Override public LegacyGuardPolicy deleteGuardPolicy(@NonNull final String policyId) throws PfModelException { assertInitilized(); - return new LegacyToscaProvider().deleteGuardPolicy(pfDao, policyId); + return new LegacyProvider().deleteGuardPolicy(pfDao, policyId); } @Override diff --git a/models-provider/src/main/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderImpl.java b/models-provider/src/main/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderImpl.java index d8750192c..8d833a53d 100644 --- a/models-provider/src/main/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderImpl.java +++ b/models-provider/src/main/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderImpl.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. + * 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. @@ -23,10 +24,8 @@ package org.onap.policy.models.provider.impl; import com.google.gson.Gson; import javax.ws.rs.core.Response; - import lombok.NonNull; - -import org.onap.policy.common.utils.resources.TextFileUtils; +import org.onap.policy.common.utils.resources.ResourceUtils; import org.onap.policy.models.base.PfConceptKey; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.base.PfModelRuntimeException; @@ -42,6 +41,7 @@ import org.onap.policy.models.tosca.simple.serialization.ToscaServiceTemplateMes * This class provides a dummy implementation of the Policy Models Provider for the ONAP Policy Framework. * * @author Liam Fallon (liam.fallon@est.tech) + * @author Chenfei Gao (cgao@research.att.com) */ public class DummyPolicyModelsProviderImpl implements PolicyModelsProvider { /** @@ -64,7 +64,7 @@ public class DummyPolicyModelsProviderImpl implements PolicyModelsProvider { @Override public ToscaServiceTemplate getPolicyTypes(@NonNull final PfConceptKey policyTypeKey) throws PfModelException { - return getDummyResponse("src/main/resources/dummyimpl/DummyToscaPolicyTypeGetResponse.json"); + return getDummyResponse("dummyimpl/DummyToscaPolicyTypeGetResponse.json"); } @Override @@ -81,12 +81,12 @@ public class DummyPolicyModelsProviderImpl implements PolicyModelsProvider { @Override public ToscaServiceTemplate deletePolicyTypes(@NonNull final PfConceptKey policyTypeKey) throws PfModelException { - return getDummyResponse("src/main/resources/dummyimpl/DummyToscaPolicyTypeDeleteResponse.json"); + return getDummyResponse("dummyimpl/DummyToscaPolicyTypeDeleteResponse.json"); } @Override public ToscaServiceTemplate getPolicies(@NonNull final PfConceptKey policyKey) throws PfModelException { - return getDummyResponse("src/main/resources/dummyimpl/DummyToscaPolicyGetResponse.json"); + return getDummyResponse("dummyimpl/DummyToscaPolicyGetResponse.json"); } @Override @@ -103,7 +103,7 @@ public class DummyPolicyModelsProviderImpl implements PolicyModelsProvider { @Override public ToscaServiceTemplate deletePolicies(@NonNull final PfConceptKey policyKey) throws PfModelException { - return getDummyResponse("src/main/resources/dummyimpl/DummyToscaPolicyDeleteResponse.json"); + return getDummyResponse("dummyimpl/DummyToscaPolicyDeleteResponse.json"); } @Override @@ -182,7 +182,10 @@ public class DummyPolicyModelsProviderImpl implements PolicyModelsProvider { ToscaServiceTemplate serviceTemplate; try { - serviceTemplate = gson.fromJson(TextFileUtils.getTextFileAsString(fileName), ToscaServiceTemplate.class); + serviceTemplate = gson.fromJson(ResourceUtils.getResourceAsString(fileName), ToscaServiceTemplate.class); + if (serviceTemplate == null) { + throw new PfModelException(Response.Status.INTERNAL_SERVER_ERROR, "error reading specified file"); + } } catch (Exception exc) { throw new PfModelRuntimeException(Response.Status.INTERNAL_SERVER_ERROR, "error serializing object", exc); } diff --git a/models-provider/src/main/resources/dummyimpl/DummyToscaPolicyTypeGetResponse.json b/models-provider/src/main/resources/dummyimpl/DummyToscaPolicyTypeGetResponse.json index 27de380c2..c28c2d2f2 100644 --- a/models-provider/src/main/resources/dummyimpl/DummyToscaPolicyTypeGetResponse.json +++ b/models-provider/src/main/resources/dummyimpl/DummyToscaPolicyTypeGetResponse.json @@ -1,48 +1,223 @@ { - "tosca_definitions_version": "tosca_simple_yaml_1_0_0", - "topology_template": { - "policies": [ - { - "onap.vcpe.tca": { - "type": "onap.policies.monitoring.cdap.tca.hi.lo.app", - "version": "1.0.0", - "metadata": { - "policy-id": "onap.vcpe.tca" - }, - "properties": { - "domain": "measurementsForVfScaling", - "metricsPerEventName": [ - { - "eventName": "Measurement_vGMUX", - "controlLoopSchemaType": "VNF", - "policyScope": "DCAE", - "policyName": "DCAE.Config_tca-hi-lo", - "policyVersion": "v0.0.1", - "thresholds": [ - { - "closedLoopControlName": "ControlLoop-vCPE-48f0c2c3-a172-4192-9ae3-052274181b6e", - "version": "1.0.2", - "fieldPath": "$.event.measurementsForVfScalingFields.additionalMeasurements[*].arrayOfFields[0].value", - "thresholdValue": 0, - "direction": "EQUAL", - "severity": "MAJOR", - "closedLoopEventStatus": "ABATED" - }, - { - "closedLoopControlName": "ControlLoop-vCPE-48f0c2c3-a172-4192-9ae3-052274181b6e", - "version": "1.0.2", - "fieldPath": "$.event.measurementsForVfScalingFields.additionalMeasurements[*].arrayOfFields[0].value", - "thresholdValue": 0, - "direction": "GREATER", - "severity": "CRITICAL", - "closedLoopEventStatus": "ONSET" - } - ] - } + "tosca_definitions_version": "tosca_simple_yaml_1_0_0", + "policy_types": [ + { + "onap.policies.Monitoring": { + "derived_from": "tosca.policies.Root", + "description": "a base policy type for all policies that governs monitoring provisioning" + } + }, + { + "onap.policy.monitoring.cdap.tca.hi.lo.app": { + "derived_from": "onap.policies.Monitoring", + "version": "1.0.0", + "properties": { + "tca_policy": { + "type": "map", + "description": "TCA Policy JSON", + "entry_schema": { + "type": "onap.datatypes.monitoring.tca_policy" + } + } + } + } + } + ], + "data_types": [ + { + "onap.datatypes.monitoring.metricsPerEventName": { + "derived_from": "tosca.datatypes.Root", + "properties": { + "controlLoopSchemaType": { + "type": "string", + "required": true, + "description": "Specifies Control Loop Schema Type for the event Name e.g. VNF, VM", + "constraints": [ + { + "valid_values": [ + "VM", + "VNF" + ] + } + ] + }, + "eventName": { + "type": "string", + "required": true, + "description": "Event name to which thresholds need to be applied" + }, + "policyName": { + "type": "string", + "required": true, + "description": "TCA Policy Scope Name" + }, + "policyScope": { + "type": "string", + "required": true, + "description": "TCA Policy Scope" + }, + "policyVersion": { + "type": "string", + "required": true, + "description": "TCA Policy Scope Version" + }, + "thresholds": { + "type": "list", + "required": true, + "description": "Thresholds associated with eventName", + "entry_schema": { + "type": "onap.datatypes.monitoring.thresholds" + } + } + } + } + }, + { + "onap.datatypes.monitoring.tca_policy": { + "derived_from": "tosca.datatypes.Root", + "properties": { + "domain": { + "type": "string", + "required": true, + "description": "Domain name to which TCA needs to be applied", + "default": "measurementsForVfScaling", + "constraints": [ + { + "equal": "measurementsForVfScaling" + } + ] + }, + "metricsPerEventName": { + "type": "list", + "required": true, + "description": "Contains eventName and threshold details that need to be applied to given eventName", + "entry_schema": { + "type": "onap.datatypes.monitoring.metricsPerEventName" + } + } + } + } + }, + { + "onap.datatypes.monitoring.thresholds": { + "derived_from": "tosca.datatypes.Root", + "properties": { + "closedLoopControlName": { + "type": "string", + "required": true, + "description": "Closed Loop Control Name associated with the threshold" + }, + "closedLoopEventStatus": { + "type": "string", + "required": true, + "description": "Closed Loop Event Status of the threshold", + "constraints": [ + { + "valid_values": [ + "ONSET", + "ABATED" + ] + } + ] + }, + "direction": { + "type": "string", + "required": true, + "description": "Direction of the threshold", + "constraints": [ + { + "valid_values": [ + "LESS", + "LESS_OR_EQUAL", + "GREATER", + "GREATER_OR_EQUAL", + "EQUAL" + ] + } + ] + }, + "fieldPath": { + "type": "string", + "required": true, + "description": "Json field Path as per CEF message which needs to be analyzed for TCA", + "constraints": [ + { + "valid_values": [ + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedTotalPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedOctetsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedUnicastPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedMulticastPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedDiscardedPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedErrorPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedTotalPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedOctetsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedUnicastPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedMulticastPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedBroadcastPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedDiscardedPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].receivedErrorPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedTotalPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedOctetsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedUnicastPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedMulticastPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedBroadcastPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedDiscardedPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedErrorPacketsDelta", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedTotalPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedOctetsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedUnicastPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedMulticastPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedBroadcastPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedDiscardedPacketsAccumulated", + "$.event.measurementsForVfScalingFields.vNicPerformanceArray[*].transmittedErrorPacketsAccumulated", + "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuIdle", + "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageInterrupt", + "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageNice", + "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageSoftIrq", + "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageSteal", + "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuUsageSystem", + "$.event.measurementsForVfScalingFields.cpuUsageArray[*].cpuWait", + "$.event.measurementsForVfScalingFields.cpuUsageArray[*].percentUsage", + "$.event.measurementsForVfScalingFields.meanRequestLatency", + "$.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryBuffered", + "$.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryCached", + "$.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryConfigured", + "$.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryFree", + "$.event.measurementsForVfScalingFields.memoryUsageArray[*].memoryUsed", + "$.event.measurementsForVfScalingFields.additionalMeasurements[*].arrayOfFields[0].value" + ] + } + ] + }, + "severity": { + "type": "string", + "required": true, + "description": "Threshold Event Severity", + "constraints": [ + { + "valid_values": [ + "CRITICAL", + "MAJOR", + "MINOR", + "WARNING", + "NORMAL" ] - } - } + } + ] + }, + "thresholdValue": { + "type": "integer", + "required": true, + "description": "Threshold value for the field Path inside CEF message" + }, + "version": { + "type": "string", + "required": true, + "description": "Version number associated with the threshold" + } } - ] - } + } + } + ] }
\ No newline at end of file diff --git a/models-provider/src/test/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderTest.java b/models-provider/src/test/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderTest.java index 3b30f98f5..e4ecb9d1d 100644 --- a/models-provider/src/test/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderTest.java +++ b/models-provider/src/test/java/org/onap/policy/models/provider/impl/DatabasePolicyModelsProviderTest.java @@ -37,6 +37,8 @@ import org.onap.policy.models.provider.PolicyModelsProviderParameters; import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicy; import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy; import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Test the database models provider implementation. @@ -44,6 +46,8 @@ import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate; * @author Liam Fallon (liam.fallon@est.tech) */ public class DatabasePolicyModelsProviderTest { + private static final Logger LOGGER = LoggerFactory.getLogger(DatabasePolicyModelsProviderTest.class); + PolicyModelsProviderParameters parameters; /** @@ -266,20 +270,76 @@ public class DatabasePolicyModelsProviderTest { new PolicyModelsProviderFactory().createPolicyModelsProvider(parameters)) { databaseProvider.init(); - assertNull(databaseProvider.getPolicyTypes(new PfConceptKey())); - assertNull(databaseProvider.createPolicyTypes(new ToscaServiceTemplate())); - assertNull(databaseProvider.updatePolicyTypes(new ToscaServiceTemplate())); - assertNull(databaseProvider.deletePolicyTypes(new PfConceptKey())); + try { + databaseProvider.getPolicyTypes(new PfConceptKey()); + fail("test should throw an exception"); + } catch (Exception npe) { + assertEquals("policy type not found: NULL:0.0.0", npe.getMessage()); + } + try { + databaseProvider.createPolicyTypes(new ToscaServiceTemplate()); + } catch (Exception npe) { + assertEquals("no policy types specified on service template", npe.getMessage()); + } + try { + databaseProvider.updatePolicyTypes(new ToscaServiceTemplate()); + } catch (Exception npe) { + assertEquals("no policy types specified on service template", npe.getMessage()); + } + try { + databaseProvider.deletePolicyTypes(new PfConceptKey()); + fail("test should throw an exception"); + } catch (Exception npe) { + assertEquals("policy type not found: NULL:0.0.0", npe.getMessage()); + } - assertNull(databaseProvider.getPolicies(new PfConceptKey())); - assertNull(databaseProvider.createPolicies(new ToscaServiceTemplate())); - assertNull(databaseProvider.updatePolicies(new ToscaServiceTemplate())); - assertNull(databaseProvider.deletePolicies(new PfConceptKey())); + try { + databaseProvider.getPolicies(new PfConceptKey()); + fail("test should throw an exception"); + } catch (Exception npe) { + assertEquals("policy not found: NULL:0.0.0", npe.getMessage()); + } + try { + databaseProvider.createPolicies(new ToscaServiceTemplate()); + } catch (Exception npe) { + assertEquals("topology template not specified on service template", npe.getMessage()); + } + try { + databaseProvider.updatePolicies(new ToscaServiceTemplate()); + } catch (Exception npe) { + assertEquals("topology template not specified on service template", npe.getMessage()); + } + try { + databaseProvider.deletePolicies(new PfConceptKey()); + fail("test should throw an exception"); + } catch (Exception npe) { + assertEquals("policy not found: NULL:0.0.0", npe.getMessage()); + } - assertNull(databaseProvider.getOperationalPolicy("policy_id")); - assertNull(databaseProvider.createOperationalPolicy(new LegacyOperationalPolicy())); - assertNull(databaseProvider.updateOperationalPolicy(new LegacyOperationalPolicy())); - assertNull(databaseProvider.deleteOperationalPolicy("policy_id")); + try { + assertNull(databaseProvider.getOperationalPolicy("policy_id")); + fail("test should throw an exception"); + } catch (Exception npe) { + assertEquals("no policy found for policy ID: policy_id", npe.getMessage()); + } + try { + assertNull(databaseProvider.createOperationalPolicy(new LegacyOperationalPolicy())); + fail("test should throw an exception"); + } catch (Exception npe) { + assertEquals("name is marked @NonNull but is null", npe.getMessage()); + } + try { + assertNull(databaseProvider.updateOperationalPolicy(new LegacyOperationalPolicy())); + fail("test should throw an exception"); + } catch (Exception npe) { + assertEquals("no policy found for policy ID: null", npe.getMessage()); + } + try { + assertNull(databaseProvider.deleteOperationalPolicy("policy_id")); + fail("test should throw an exception"); + } catch (Exception npe) { + assertEquals("no policy found for policy ID: policy_id", npe.getMessage()); + } assertNull(databaseProvider.getGuardPolicy("policy_id")); assertNull(databaseProvider.createGuardPolicy(new LegacyGuardPolicy())); @@ -292,6 +352,7 @@ public class DatabasePolicyModelsProviderTest { assertNotNull(databaseProvider.deletePdpGroups("filter")); } catch (Exception exc) { + LOGGER.warn("test should not throw an exception", exc); fail("test should not throw an exception"); } } diff --git a/models-provider/src/test/java/org/onap/policy/models/provider/impl/MonitoringPolicyPersistenceTest.java b/models-provider/src/test/java/org/onap/policy/models/provider/impl/MonitoringPolicyPersistenceTest.java deleted file mode 100644 index b26e762af..000000000 --- a/models-provider/src/test/java/org/onap/policy/models/provider/impl/MonitoringPolicyPersistenceTest.java +++ /dev/null @@ -1,118 +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.provider.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import com.google.gson.Gson; -import com.google.gson.JsonSyntaxException; - -import java.io.IOException; -import java.sql.Connection; -import java.sql.DriverManager; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.common.utils.resources.ResourceUtils; -import org.onap.policy.models.base.PfConceptKey; -import org.onap.policy.models.base.PfValidationResult; -import org.onap.policy.models.dao.DaoParameters; -import org.onap.policy.models.dao.PfDao; -import org.onap.policy.models.dao.PfDaoFactory; -import org.onap.policy.models.dao.impl.DefaultPfDao; -import org.onap.policy.models.tosca.simple.concepts.ToscaPolicy; -import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate; -import org.onap.policy.models.tosca.simple.serialization.ToscaServiceTemplateMessageBodyHandler; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Test persistence of monitoring policies to and from the database. - * - * @author Liam Fallon (liam.fallon@est.tech) - */ -public class MonitoringPolicyPersistenceTest { - // Logger for this class - private static final Logger LOGGER = LoggerFactory.getLogger(MonitoringPolicyPersistenceTest.class); - - private Gson gson; - - private Connection connection; - private PfDao pfDao; - - /** - * Set up the DAO towards the database. - * - * @throws Exception on database errors - */ - @Before - public void setupDao() throws Exception { - // Use the JDBC UI "jdbc:h2:mem:testdb" to test towards the h2 database - // Use the JDBC UI "jdbc:mariadb://localhost:3306/policy" to test towards a locally installed mariadb instance - connection = DriverManager.getConnection("jdbc:h2:mem:testdb", "policy", "P01icY"); - - final DaoParameters daoParameters = new DaoParameters(); - daoParameters.setPluginClass(DefaultPfDao.class.getCanonicalName()); - - // Use the persistence unit ToscaConceptTest to test towards the h2 database - // Use the persistence unit ToscaConceptMariaDBTest to test towards a locally installed mariadb instance - daoParameters.setPersistenceUnit("ToscaConceptTest"); - - pfDao = new PfDaoFactory().createPfDao(daoParameters); - pfDao.init(daoParameters); - } - - /** - * Set up GSON. - */ - @Before - public void setupGson() { - gson = new ToscaServiceTemplateMessageBodyHandler().getGson(); - } - - @After - public void teardown() throws Exception { - pfDao.close(); - connection.close(); - } - - @Test - public void testJsonDeserialization() throws JsonSyntaxException, IOException { - ToscaServiceTemplate serviceTemplate = - gson.fromJson(ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json"), - ToscaServiceTemplate.class); - - assertNotNull(serviceTemplate); - LOGGER.info(serviceTemplate.validate(new PfValidationResult()).toString()); - assertTrue(serviceTemplate.validate(new PfValidationResult()).isValid()); - - ToscaPolicy policyBeforeDb = serviceTemplate.getTopologyTemplate().getPolicies().get("onap.restart.tca"); - - pfDao.create(policyBeforeDb); - - ToscaPolicy policyAfterDb = pfDao.get(ToscaPolicy.class, new PfConceptKey("onap.restart.tca:1.0.0")); - - assertEquals(policyBeforeDb, policyAfterDb); - } -} diff --git a/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyLegacyOperationalPersistenceTest.java b/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyLegacyOperationalPersistenceTest.java new file mode 100644 index 000000000..90d00fc58 --- /dev/null +++ b/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyLegacyOperationalPersistenceTest.java @@ -0,0 +1,143 @@ +/*- + * ============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.provider.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +import com.google.gson.Gson; + +import java.util.Base64; + +import lombok.NonNull; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.provider.PolicyModelsProvider; +import org.onap.policy.models.provider.PolicyModelsProviderFactory; +import org.onap.policy.models.provider.PolicyModelsProviderParameters; +import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Test persistence of monitoring policies to and from the database. + * + * @author Liam Fallon (liam.fallon@est.tech) + */ +public class PolicyLegacyOperationalPersistenceTest { + // Logger for this class + private static final Logger LOGGER = LoggerFactory.getLogger(PolicyLegacyOperationalPersistenceTest.class); + + private Gson gson; + + private PolicyModelsProvider databaseProvider; + + // @formatter:off + private String[] policyInputResourceNames = { + "policies/vCPE.policy.operational.input.json", + "policies/vDNS.policy.operational.input.json", + "policies/vFirewall.policy.operational.input.json" + }; + + private String[] policyOutputResourceNames = { + "policies/vCPE.policy.operational.output.json", + "policies/vDNS.policy.operational.output.json", + "policies/vFirewall.policy.operational.output.json" + }; + // @formatter:on + + /** + * Initialize provider. + * + * @throws PfModelException on exceptions in the tests + */ + @Before + public void setupParameters() throws PfModelException { + PolicyModelsProviderParameters parameters = new PolicyModelsProviderParameters(); + parameters.setDatabaseUrl("jdbc:h2:mem:testdb"); + parameters.setDatabaseUser("policy"); + parameters.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes())); + parameters.setPersistenceUnit("ToscaConceptTest"); + + databaseProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(parameters); + databaseProvider.init(); + } + + /** + * Set up GSON. + */ + @Before + public void setupGson() { + gson = new Gson(); + } + + @After + public void teardown() throws Exception { + databaseProvider.close(); + } + + @Test + public void testPolicyPersistence() { + try { + for (int i = 0; i < policyInputResourceNames.length; i++) { + String policyInputString = ResourceUtils.getResourceAsString(policyInputResourceNames[i]); + String policyOutputString = ResourceUtils.getResourceAsString(policyOutputResourceNames[i]); + testJsonStringPolicyPersistence(policyInputString, policyOutputString); + } + } catch (Exception exc) { + LOGGER.warn("error processing policies", exc); + fail("test should not throw an exception"); + } + } + + /** + * Check persistence of a policy. + * + * @param policyInputString the policy as a string + * @param policyOutputString the expected output string + * @throws Exception any exception thrown + */ + public void testJsonStringPolicyPersistence(@NonNull final String policyInputString, + final String policyOutputString) throws Exception { + LegacyOperationalPolicy lop = gson.fromJson(policyInputString, LegacyOperationalPolicy.class); + + assertNotNull(lop); + + LegacyOperationalPolicy createdLop = databaseProvider.createOperationalPolicy(lop); + assertEquals(createdLop, lop); + + LegacyOperationalPolicy gotLop = databaseProvider.getOperationalPolicy(lop.getPolicyId()); + assertEquals(gotLop, lop); + + String actualRetrievedJson = gson.toJson(gotLop); + + // All of this dash/underscore stuff is to avoid a checkstyle error around escaping unicode characters + assertEquals( + policyOutputString.replaceAll("\\s+", "").replaceAll("u0027", "_-_-_-_").replaceAll("\\\\_-_-_-_", "'"), + actualRetrievedJson.replaceAll("\\s+", "").replaceAll("u0027", "_-_-_-_").replaceAll("\\\\_-_-_-_", + "'")); + } +} diff --git a/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyPersistenceTest.java b/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyPersistenceTest.java new file mode 100644 index 000000000..de299772f --- /dev/null +++ b/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyPersistenceTest.java @@ -0,0 +1,159 @@ +/*- + * ============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.provider.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import java.util.Base64; + +import lombok.NonNull; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.base.PfValidationResult; +import org.onap.policy.models.provider.PolicyModelsProvider; +import org.onap.policy.models.provider.PolicyModelsProviderFactory; +import org.onap.policy.models.provider.PolicyModelsProviderParameters; +import org.onap.policy.models.tosca.simple.concepts.ToscaPolicy; +import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate; +import org.onap.policy.models.tosca.simple.serialization.ToscaServiceTemplateMessageBodyHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.yaml.snakeyaml.Yaml; + +/** + * Test persistence of monitoring policies to and from the database. + * + * @author Liam Fallon (liam.fallon@est.tech) + */ +public class PolicyPersistenceTest { + // Logger for this class + private static final Logger LOGGER = LoggerFactory.getLogger(PolicyPersistenceTest.class); + + private Gson gson; + + private PolicyModelsProvider databaseProvider; + + // @formatter:off + private String[] policyResourceNames = { + "policies/vCPE.policy.monitoring.input.tosca.json", + "policies/vCPE.policy.monitoring.input.tosca.yaml", + "policies/vCPE.policy.operational.input.tosca.yaml", + "policies/vDNS.policy.guard.frequency.input.tosca.json", + "policies/vDNS.policy.guard.frequency.input.tosca.yaml", + "policies/vDNS.policy.monitoring.input.tosca.json", + "policies/vDNS.policy.monitoring.input.tosca.yaml", + "policies/vDNS.policy.operational.input.tosca.yaml", + "policies/vFirewall.policy.monitoring.input.tosca.json", + "policies/vFirewall.policy.monitoring.input.tosca.yaml", + "policies/vFirewall.policy.operational.input.tosca.json", + "policies/vFirewall.policy.operational.input.tosca.yaml" + }; + // @formatter:on + + /** + * Initialize provider. + * + * @throws PfModelException on exceptions in the tests + */ + @Before + public void setupParameters() throws PfModelException { + PolicyModelsProviderParameters parameters = new PolicyModelsProviderParameters(); + parameters.setDatabaseUrl("jdbc:h2:mem:testdb"); + parameters.setDatabaseUser("policy"); + parameters.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes())); + parameters.setPersistenceUnit("ToscaConceptTest"); + + databaseProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(parameters); + databaseProvider.init(); + } + + /** + * Set up GSON. + */ + @Before + public void setupGson() { + gson = new ToscaServiceTemplateMessageBodyHandler().getGson(); + } + + @After + public void teardown() throws Exception { + databaseProvider.close(); + } + + @Test + public void testPolicyPersistence() { + try { + for (String policyResourceName : policyResourceNames) { + String policyString = ResourceUtils.getResourceAsString(policyResourceName); + + if (policyResourceName.endsWith("yaml")) { + testYamlStringPolicyPersistence(policyString); + } else { + testJsonStringPolicyPersistence(policyString); + } + } + } catch (Exception exc) { + LOGGER.warn("error processing policies", exc); + fail("test should not throw an exception"); + } + } + + private void testYamlStringPolicyPersistence(final String policyString) throws Exception { + Object yamlObject = new Yaml().load(policyString); + String yamlAsJsonString = new GsonBuilder().setPrettyPrinting().create().toJson(yamlObject); + + testJsonStringPolicyPersistence(yamlAsJsonString); + } + + /** + * Check persistence of a policy. + * + * @param policyString the policy as a string + * @throws Exception any exception thrown + */ + public void testJsonStringPolicyPersistence(@NonNull final String policyString) throws Exception { + ToscaServiceTemplate serviceTemplate = gson.fromJson(policyString, ToscaServiceTemplate.class); + + assertNotNull(serviceTemplate); + LOGGER.info(serviceTemplate.validate(new PfValidationResult()).toString()); + assertTrue(serviceTemplate.validate(new PfValidationResult()).isValid()); + + databaseProvider.createPolicies(serviceTemplate); + + for (PfConceptKey policyKey : serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().keySet()) { + ToscaPolicy incomingPolicy = serviceTemplate.getTopologyTemplate().getPolicies().get(policyKey); + ToscaPolicy databasePolicy = + databaseProvider.getPolicies(policyKey).getTopologyTemplate().getPolicies().get(policyKey); + assertEquals(incomingPolicy, databasePolicy); + } + } +} diff --git a/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyToscaPersistenceTest.java b/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyToscaPersistenceTest.java new file mode 100644 index 000000000..a4b1dcd03 --- /dev/null +++ b/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyToscaPersistenceTest.java @@ -0,0 +1,159 @@ +/*- + * ============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.provider.impl; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import java.util.Base64; + +import lombok.NonNull; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.base.PfValidationResult; +import org.onap.policy.models.provider.PolicyModelsProvider; +import org.onap.policy.models.provider.PolicyModelsProviderFactory; +import org.onap.policy.models.provider.PolicyModelsProviderParameters; +import org.onap.policy.models.tosca.simple.concepts.ToscaPolicy; +import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate; +import org.onap.policy.models.tosca.simple.serialization.ToscaServiceTemplateMessageBodyHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.yaml.snakeyaml.Yaml; + +/** + * Test persistence of monitoring policies to and from the database. + * + * @author Liam Fallon (liam.fallon@est.tech) + */ +public class PolicyToscaPersistenceTest { + // Logger for this class + private static final Logger LOGGER = LoggerFactory.getLogger(PolicyToscaPersistenceTest.class); + + private Gson gson; + + private PolicyModelsProvider databaseProvider; + + // @formatter:off + private String[] policyResourceNames = { + "policies/vCPE.policy.monitoring.input.tosca.json", + "policies/vCPE.policy.monitoring.input.tosca.yaml", + "policies/vCPE.policy.operational.input.tosca.yaml", + "policies/vDNS.policy.guard.frequency.input.tosca.json", + "policies/vDNS.policy.guard.frequency.input.tosca.yaml", + "policies/vDNS.policy.monitoring.input.tosca.json", + "policies/vDNS.policy.monitoring.input.tosca.yaml", + "policies/vDNS.policy.operational.input.tosca.yaml", + "policies/vFirewall.policy.monitoring.input.tosca.json", + "policies/vFirewall.policy.monitoring.input.tosca.yaml", + "policies/vFirewall.policy.operational.input.tosca.json", + "policies/vFirewall.policy.operational.input.tosca.yaml" + }; + // @formatter:on + + /** + * Initialize provider. + * + * @throws PfModelException on exceptions in the tests + */ + @Before + public void setupParameters() throws PfModelException { + PolicyModelsProviderParameters parameters = new PolicyModelsProviderParameters(); + parameters.setDatabaseUrl("jdbc:h2:mem:testdb"); + parameters.setDatabaseUser("policy"); + parameters.setDatabasePassword(Base64.getEncoder().encodeToString("P01icY".getBytes())); + parameters.setPersistenceUnit("ToscaConceptTest"); + + databaseProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(parameters); + databaseProvider.init(); + } + + /** + * Set up GSON. + */ + @Before + public void setupGson() { + gson = new ToscaServiceTemplateMessageBodyHandler().getGson(); + } + + @After + public void teardown() throws Exception { + databaseProvider.close(); + } + + @Test + public void testPolicyPersistence() { + try { + for (String policyResourceName : policyResourceNames) { + String policyString = ResourceUtils.getResourceAsString(policyResourceName); + + if (policyResourceName.endsWith("yaml")) { + testYamlStringPolicyPersistence(policyString); + } else { + testJsonStringPolicyPersistence(policyString); + } + } + } catch (Exception exc) { + LOGGER.warn("error processing policies", exc); + fail("test should not throw an exception"); + } + } + + private void testYamlStringPolicyPersistence(final String policyString) throws Exception { + Object yamlObject = new Yaml().load(policyString); + String yamlAsJsonString = new GsonBuilder().setPrettyPrinting().create().toJson(yamlObject); + + testJsonStringPolicyPersistence(yamlAsJsonString); + } + + /** + * Check persistence of a policy. + * + * @param policyString the policy as a string + * @throws Exception any exception thrown + */ + public void testJsonStringPolicyPersistence(@NonNull final String policyString) throws Exception { + ToscaServiceTemplate serviceTemplate = gson.fromJson(policyString, ToscaServiceTemplate.class); + + assertNotNull(serviceTemplate); + LOGGER.info(serviceTemplate.validate(new PfValidationResult()).toString()); + assertTrue(serviceTemplate.validate(new PfValidationResult()).isValid()); + + databaseProvider.createPolicies(serviceTemplate); + + for (PfConceptKey policyKey : serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().keySet()) { + ToscaPolicy incomingPolicy = serviceTemplate.getTopologyTemplate().getPolicies().get(policyKey); + ToscaPolicy databasePolicy = + databaseProvider.getPolicies(policyKey).getTopologyTemplate().getPolicies().get(policyKey); + assertEquals(incomingPolicy, databasePolicy); + } + } +} diff --git a/models-provider/src/test/resources/META-INF/persistence.xml b/models-provider/src/test/resources/META-INF/persistence.xml index 491505341..68340901b 100644 --- a/models-provider/src/test/resources/META-INF/persistence.xml +++ b/models-provider/src/test/resources/META-INF/persistence.xml @@ -26,6 +26,7 @@ <class>org.onap.policy.models.dao.converters.CDataConditioner</class> <class>org.onap.policy.models.dao.converters.Uuid2String</class> <class>org.onap.policy.models.base.PfConceptKey</class> + <class>org.onap.policy.models.tosca.simple.concepts.ToscaPolicyType</class> <class>org.onap.policy.models.tosca.simple.concepts.ToscaPolicy</class> <properties> diff --git a/models-tosca/pom.xml b/models-tosca/pom.xml index 5658a1c0e..c8fa2520a 100644 --- a/models-tosca/pom.xml +++ b/models-tosca/pom.xml @@ -56,5 +56,18 @@ <artifactId>gson</artifactId> <version>${policy.common.version}</version> </dependency> + + <dependency> + <groupId>com.h2database</groupId> + <artifactId>h2</artifactId> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>org.mariadb.jdbc</groupId> + <artifactId>mariadb-java-client</artifactId> + <scope>test</scope> + </dependency> + </dependencies> </project> diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/PlainToscaConstraint.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/PlainToscaConstraint.java new file mode 100644 index 000000000..85d0b5009 --- /dev/null +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/PlainToscaConstraint.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Model + * ================================================================================ + * 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.tosca.authorative.concepts; + +import com.google.gson.annotations.SerializedName; +import java.util.List; +import lombok.Data; + +/** + * Class to represent TOSCA constraint matching input/output from/to client. + * + * @author Chenfei Gao (cgao@research.att.com) + */ +@Data +public class PlainToscaConstraint { + + @SerializedName("valid_values") + private List<String> validValues; + + private String equal; +} diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/PlainToscaDataType.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/PlainToscaDataType.java new file mode 100644 index 000000000..0581a7da1 --- /dev/null +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/PlainToscaDataType.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Model + * ================================================================================ + * 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.tosca.authorative.concepts; + +import com.google.gson.annotations.SerializedName; +import java.util.Map; +import lombok.Data; + +/** + * Class to represent TOSCA data type matching input/output from/to client. + * + * @author Chenfei Gao (cgao@research.att.com) + */ +@Data +public class PlainToscaDataType { + + @SerializedName("derived_from") + private String derivedFrom; + + private String version; + + private Map<String, String> metadata; + + private String description; + + private Map<String, PlainToscaProperty> properties; +} diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/PlainToscaEntrySchema.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/PlainToscaEntrySchema.java new file mode 100644 index 000000000..ab9051aa9 --- /dev/null +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/PlainToscaEntrySchema.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Model + * ================================================================================ + * 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.tosca.authorative.concepts; + +import java.util.List; +import lombok.Data; + +/** + * Class to represent TOSCA entry schema matching input/output from/to client. + * + * @author Chenfei Gao (cgao@research.att.com) + */ +@Data +public class PlainToscaEntrySchema { + + private String type; + + private String description; + + private List<PlainToscaConstraint> constraints; +} diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/PlainToscaPolicy.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/PlainToscaPolicy.java new file mode 100644 index 000000000..02ebe6537 --- /dev/null +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/PlainToscaPolicy.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Model + * ================================================================================ + * 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.tosca.authorative.concepts; + +import java.util.Map; +import lombok.Data; + +/** + * Class to represent TOSCA policy matching input/output from/to client. + * + * @author Chenfei Gao (cgao@research.att.com) + */ +@Data +public class PlainToscaPolicy { + + private String type; + + private String version; + + private String description; + + private Map<String, String> metadata; + + private Map<String, Object> properties; +} diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/PlainToscaPolicyType.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/PlainToscaPolicyType.java new file mode 100644 index 000000000..499e2dd25 --- /dev/null +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/PlainToscaPolicyType.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Model + * ================================================================================ + * 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.tosca.authorative.concepts; + +import com.google.gson.annotations.SerializedName; +import java.util.Map; +import lombok.Data; + +/** + * Class to represent TOSCA policy type matching input/output from/to client. + * + * @author Chenfei Gao (cgao@research.att.com) + */ +@Data +public class PlainToscaPolicyType { + + @SerializedName("derived_from") + private String derivedFrom; + + private String version; + + private Map<String, String> metadata; + + private String description; + + private Map<String, PlainToscaProperty> properties; +} diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/PlainToscaProperty.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/PlainToscaProperty.java new file mode 100644 index 000000000..e5e282a95 --- /dev/null +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/PlainToscaProperty.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Model + * ================================================================================ + * 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.tosca.authorative.concepts; + +import com.google.gson.annotations.SerializedName; +import java.util.List; +import lombok.Data; + +/** + * Class to represent TOSCA property matching input/output from/to client. + * + * @author Chenfei Gao (cgao@research.att.com) + */ +@Data +public class PlainToscaProperty { + + private String type; + + private String description; + + private boolean required = false; + + @SerializedName("default") + private String defaultValue; + + @SerializedName("entry_schema") + private PlainToscaEntrySchema entrySchema; + + private List<PlainToscaConstraint> constraints; +} diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/PlainToscaServiceTemplate.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/PlainToscaServiceTemplate.java new file mode 100644 index 000000000..cf5e2d9d6 --- /dev/null +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/PlainToscaServiceTemplate.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Model + * ================================================================================ + * 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.tosca.authorative.concepts; + +import com.google.gson.annotations.SerializedName; +import java.util.List; +import java.util.Map; +import lombok.Data; + +/** + * Class to represent TOSCA service template matching input/output from/to client. + * + * @author Chenfei Gao (cgao@research.att.com) + */ +@Data +public class PlainToscaServiceTemplate { + + @SerializedName("tosca_definitions_version") + private String toscaDefinitionsVersion; + + @SerializedName("topology_template") + private PlainToscaTopologyTemplate toscaTopologyTemplate; + + @SerializedName("policy_types") + private List<Map<String, PlainToscaPolicyType>> policyTypes; + + @SerializedName("data_types") + private List<Map<String, PlainToscaDataType>> dataTypes; +}
\ No newline at end of file diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/PlainToscaTopologyTemplate.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/PlainToscaTopologyTemplate.java new file mode 100644 index 000000000..16c1da05e --- /dev/null +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/PlainToscaTopologyTemplate.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Model + * ================================================================================ + * 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.tosca.authorative.concepts; + +import java.util.List; +import java.util.Map; +import lombok.Data; + +/** + * Class to represent TOSCA topology template matching input/output from/to client. + * + * @author Chenfei Gao (cgao@research.att.com) + */ +@Data +public class PlainToscaTopologyTemplate { + + private String description; + + private List<Map<String, PlainToscaPolicy>> policies; +} diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/package-info.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/package-info.java new file mode 100644 index 000000000..2b98f9bc7 --- /dev/null +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/concepts/package-info.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Model + * ================================================================================ + * 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========================================================= + */ + +/** + * This package includes all TOSCA concept POJOs that can be parsed correctly by swagger-core and rendered + * as expected in swagger-ui. + */ +/** + * @author Chenfei Gao (cgao@research.att.com) + * + */ +package org.onap.policy.models.tosca.authorative.concepts;
\ No newline at end of file diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/mapping/PlainToscaServiceTemplateMapper.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/mapping/PlainToscaServiceTemplateMapper.java new file mode 100644 index 000000000..aa7ca23b2 --- /dev/null +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/mapping/PlainToscaServiceTemplateMapper.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Model + * ================================================================================ + * 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.tosca.authorative.mapping; + +import com.google.gson.Gson; +import org.onap.policy.models.tosca.authorative.concepts.PlainToscaServiceTemplate; +import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate; +import org.onap.policy.models.tosca.simple.mapping.ToscaServiceTemplateMapper; +import org.onap.policy.models.tosca.simple.serialization.ToscaServiceTemplateMessageBodyHandler; + +/** + * This class maps a TOSCA service template from client input form to internal representation and vice verse. + * + * @author Chenfei Gao (cgao@research.att.com) + */ +public class PlainToscaServiceTemplateMapper + implements ToscaServiceTemplateMapper<PlainToscaServiceTemplate, PlainToscaServiceTemplate> { + + private Gson defaultGson = new Gson(); + private Gson customGson = new ToscaServiceTemplateMessageBodyHandler().getGson(); + + @Override + public ToscaServiceTemplate toToscaServiceTemplate(PlainToscaServiceTemplate otherPolicy) { + + String serializedServiceTemplate = defaultGson.toJson(otherPolicy); + return customGson.fromJson(serializedServiceTemplate, ToscaServiceTemplate.class); + + } + + @Override + public PlainToscaServiceTemplate fromToscaServiceTemplate(ToscaServiceTemplate serviceTemplate) { + + String serializedServiceTemplate = customGson.toJson(serviceTemplate); + return defaultGson.fromJson(serializedServiceTemplate, PlainToscaServiceTemplate.class); + } +} diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/mapping/package-info.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/mapping/package-info.java new file mode 100644 index 000000000..e9b87c6ab --- /dev/null +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/authorative/mapping/package-info.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Model + * ================================================================================ + * 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========================================================= + */ + +/** + * This package includes all the mappers used to transform plain TOSCA POJOs into internal representation + * of TOSCA concepts with JPA annotations added. + */ +/** + * @author Chenfei Gao (cgao@research.att.com) + * + */ +package org.onap.policy.models.tosca.authorative.mapping;
\ No newline at end of file diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/concepts/LegacyGuardPolicy.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/concepts/LegacyGuardPolicy.java index 2454b51be..59715e4f9 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/concepts/LegacyGuardPolicy.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/concepts/LegacyGuardPolicy.java @@ -21,7 +21,6 @@ package org.onap.policy.models.tosca.legacy.concepts; -import java.util.List; import java.util.Map; import lombok.Data; @@ -30,6 +29,7 @@ import lombok.Data; * Definition of a legacy guard policy stored as a TOSCA policy. * * @author Liam Fallon (liam.fallon@est.tech) + * @author Chenfei Gao (cgao@research.att.com) */ @Data public class LegacyGuardPolicy { @@ -38,6 +38,6 @@ public class LegacyGuardPolicy { private String policyVersion; - private List<Map<String, String>> content; + private Map<String, String> content; } diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/concepts/LegacyOperationalPolicy.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/concepts/LegacyOperationalPolicy.java index 60a1e454d..1db4d6e20 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/concepts/LegacyOperationalPolicy.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/concepts/LegacyOperationalPolicy.java @@ -36,6 +36,7 @@ public class LegacyOperationalPolicy { @SerializedName("policy-id") private String policyId; + @SerializedName("policy-version") private String policyVersion; private String content; diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/mapping/LegacyOperationalPolicyMapper.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/mapping/LegacyOperationalPolicyMapper.java index 2f87020be..65f477572 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/mapping/LegacyOperationalPolicyMapper.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/mapping/LegacyOperationalPolicyMapper.java @@ -23,14 +23,19 @@ package org.onap.policy.models.tosca.legacy.mapping; import java.util.HashMap; import java.util.Map; +import javax.ws.rs.core.Response; + import org.onap.policy.models.base.PfConceptKey; -import org.onap.policy.models.base.PfReferenceKey; +import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy; import org.onap.policy.models.tosca.simple.concepts.ToscaPolicies; import org.onap.policy.models.tosca.simple.concepts.ToscaPolicy; import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate; import org.onap.policy.models.tosca.simple.concepts.ToscaTopologyTemplate; import org.onap.policy.models.tosca.simple.mapping.ToscaServiceTemplateMapper; +import org.onap.policy.models.tosca.utils.ToscaUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * This class maps a legacy operational policy to and from a TOSCA service template. @@ -39,51 +44,72 @@ import org.onap.policy.models.tosca.simple.mapping.ToscaServiceTemplateMapper; */ public class LegacyOperationalPolicyMapper implements ToscaServiceTemplateMapper<LegacyOperationalPolicy, LegacyOperationalPolicy> { + private static final Logger LOGGER = LoggerFactory.getLogger(LegacyOperationalPolicyMapper.class); - // TODO: Do this correctly with an atomic integer - private static int nextVersion = 1; + private static final PfConceptKey LEGACY_OPERATIONAL_TYPE = + new PfConceptKey("onap.policies.controlloop.Operational", "1.0.0"); @Override - public ToscaServiceTemplate toToscaServiceTemplate(LegacyOperationalPolicy legacyOperationalPolicy) { - PfConceptKey policyKey = - new PfConceptKey(legacyOperationalPolicy.getPolicyId(), getNextVersion()); + public ToscaServiceTemplate toToscaServiceTemplate(final LegacyOperationalPolicy legacyOperationalPolicy) { + String incomingVersion = legacyOperationalPolicy.getPolicyVersion(); + if (incomingVersion == null) { + incomingVersion = "1"; + } + + PfConceptKey policyKey = new PfConceptKey(legacyOperationalPolicy.getPolicyId(), incomingVersion + ".0.0"); - ToscaPolicy toscaPolicy = new ToscaPolicy(policyKey); + final ToscaPolicy toscaPolicy = new ToscaPolicy(policyKey); - // TODO: Find out how to parse the PolicyType from the content - // TODO: Check if this is the correct way to set the policy type version - toscaPolicy.setType(new PfConceptKey("SomeDerivedPolicyType", "1.0.1")); + toscaPolicy.setType(LEGACY_OPERATIONAL_TYPE); - Map<String, String> propertyMap = new HashMap<>(); + final Map<String, String> propertyMap = new HashMap<>(); toscaPolicy.setProperties(propertyMap); toscaPolicy.getProperties().put("Content", legacyOperationalPolicy.getContent()); - PfConceptKey serviceTemplateKey = new PfConceptKey("ServiceTemplate", "1.0.2"); - ToscaServiceTemplate serviceTemplate = new ToscaServiceTemplate(serviceTemplateKey); + final ToscaServiceTemplate serviceTemplate = new ToscaServiceTemplate(); serviceTemplate.setToscaDefinitionsVersion("tosca_simple_yaml_1_0"); - PfReferenceKey topologyTemplateKey = new PfReferenceKey(serviceTemplateKey, "TopolocyTemplate"); - serviceTemplate.setTopologyTemplate(new ToscaTopologyTemplate(topologyTemplateKey)); + serviceTemplate.setTopologyTemplate(new ToscaTopologyTemplate()); - PfConceptKey policiesKey = new PfConceptKey("Policies", "1.0.3"); - serviceTemplate.getTopologyTemplate().setPolicies(new ToscaPolicies(policiesKey)); + serviceTemplate.getTopologyTemplate().setPolicies(new ToscaPolicies()); serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().put(policyKey, toscaPolicy); return serviceTemplate; } @Override - public LegacyOperationalPolicy fromToscaServiceTemplate(ToscaServiceTemplate serviceTemplate) { - // TODO Auto-generated method stub - return null; - } + public LegacyOperationalPolicy fromToscaServiceTemplate(final ToscaServiceTemplate serviceTemplate) { + ToscaUtils.assertPoliciesExist(serviceTemplate); + + if (serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().size() > 1) { + String errorMessage = "more than one policy found in service template"; + LOGGER.warn(errorMessage); + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage); + } + + // Get the policy + final ToscaPolicy toscaPolicy = + serviceTemplate.getTopologyTemplate().getPolicies().getAll(null).iterator().next(); + + final LegacyOperationalPolicy legacyOperationalPolicy = new LegacyOperationalPolicy(); + legacyOperationalPolicy.setPolicyId(toscaPolicy.getKey().getName()); + legacyOperationalPolicy.setPolicyVersion(Integer.toString(toscaPolicy.getKey().getMajorVersion())); + + if (toscaPolicy.getProperties() == null) { + String errorMessage = "no properties defined on TOSCA policy"; + LOGGER.warn(errorMessage); + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage); + } + + final String content = toscaPolicy.getProperties().get("Content"); + if (toscaPolicy.getProperties() == null) { + String errorMessage = "property \"Content\" not defined on TOSCA policy"; + LOGGER.warn(errorMessage); + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage); + } + + legacyOperationalPolicy.setContent(content); - /** - * Get the next policy version. - * - * @return the next version - */ - private static String getNextVersion() { - return "1.0." + nextVersion++; + return legacyOperationalPolicy; } } diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider.java new file mode 100644 index 000000000..42343e1df --- /dev/null +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/provider/LegacyProvider.java @@ -0,0 +1,268 @@ +/*- + * ============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.tosca.legacy.provider; + +import java.util.ArrayList; +import java.util.List; + +import javax.ws.rs.core.Response; + +import lombok.NonNull; + +import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.base.PfModelRuntimeException; +import org.onap.policy.models.dao.PfDao; +import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicy; +import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy; +import org.onap.policy.models.tosca.legacy.mapping.LegacyOperationalPolicyMapper; +import org.onap.policy.models.tosca.simple.concepts.ToscaPolicies; +import org.onap.policy.models.tosca.simple.concepts.ToscaPolicy; +import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate; +import org.onap.policy.models.tosca.simple.concepts.ToscaTopologyTemplate; +import org.onap.policy.models.tosca.simple.provider.SimpleToscaProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class provides the provision of information on TOSCA concepts in the database to callers in legacy formats. + * + * @author Liam Fallon (liam.fallon@est.tech) + */ +public class LegacyProvider { + private static final Logger LOGGER = LoggerFactory.getLogger(LegacyProvider.class); + + private static final String FIRST_POLICY_VERSION = "1"; + + // Recurring constants + private static final String NO_POLICY_FOUND_FOR_POLICY_ID = "no policy found for policy ID: "; + + /** + * Get legacy operational policy. + * + * @param dao the DAO to use to access the database + * @param policyId ID of the policy. + * @return the policies found + * @throws PfModelException on errors getting policies + */ + public LegacyOperationalPolicy getOperationalPolicy(@NonNull final PfDao dao, @NonNull final String policyId) + throws PfModelException { + + ToscaPolicy newestPolicy = getLatestPolicy(dao, policyId); + + if (newestPolicy == null) { + String errorMessage = NO_POLICY_FOUND_FOR_POLICY_ID + policyId; + LOGGER.warn(errorMessage); + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage); + } + + // Create the structure of the TOSCA service template to contain the policy type + ToscaServiceTemplate serviceTemplate = new ToscaServiceTemplate(); + serviceTemplate.setTopologyTemplate(new ToscaTopologyTemplate()); + serviceTemplate.getTopologyTemplate().setPolicies(new ToscaPolicies()); + serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().put(newestPolicy.getKey(), newestPolicy); + + return new LegacyOperationalPolicyMapper().fromToscaServiceTemplate(serviceTemplate); + } + + /** + * Create legacy operational policy. + * + * @param dao the DAO to use to access the database + * @param legacyOperationalPolicy the definition of the policy to be created. + * @return the created policy + * @throws PfModelException on errors creating policies + */ + public LegacyOperationalPolicy createOperationalPolicy(@NonNull final PfDao dao, + @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException { + + // We need to find the latest policy and update the major version, if there is no policy with this ID, then + // we set it to the first version + ToscaPolicy newestPolicy = getLatestPolicy(dao, legacyOperationalPolicy.getPolicyId()); + + if (newestPolicy == null) { + legacyOperationalPolicy.setPolicyVersion(FIRST_POLICY_VERSION); + } else { + legacyOperationalPolicy.setPolicyVersion(Integer.toString(newestPolicy.getKey().getMajorVersion() + 1)); + } + + ToscaServiceTemplate incomingServiceTemplate = + new LegacyOperationalPolicyMapper().toToscaServiceTemplate(legacyOperationalPolicy); + ToscaServiceTemplate outgoingingServiceTemplate = + new SimpleToscaProvider().createPolicies(dao, incomingServiceTemplate); + + return new LegacyOperationalPolicyMapper().fromToscaServiceTemplate(outgoingingServiceTemplate); + } + + /** + * Update legacy operational policy. + * + * @param dao the DAO to use to access the database + * @param legacyOperationalPolicy the definition of the policy to be updated + * @return the updated policy + * @throws PfModelException on errors updating policies + */ + public LegacyOperationalPolicy updateOperationalPolicy(@NonNull final PfDao dao, + @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException { + + // We need to find the latest policy and use the major version, if there is no policy with this ID, then + // we have an error + ToscaPolicy newestPolicy = getLatestPolicy(dao, legacyOperationalPolicy.getPolicyId()); + + if (newestPolicy == null) { + String errorMessage = NO_POLICY_FOUND_FOR_POLICY_ID + legacyOperationalPolicy.getPolicyId(); + LOGGER.warn(errorMessage); + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage); + } else { + legacyOperationalPolicy.setPolicyVersion(Integer.toString(newestPolicy.getKey().getMajorVersion())); + } + + ToscaServiceTemplate incomingServiceTemplate = + new LegacyOperationalPolicyMapper().toToscaServiceTemplate(legacyOperationalPolicy); + ToscaServiceTemplate outgoingingServiceTemplate = + new SimpleToscaProvider().createPolicies(dao, incomingServiceTemplate); + + return new LegacyOperationalPolicyMapper().fromToscaServiceTemplate(outgoingingServiceTemplate); + } + + /** + * Delete legacy operational policy. + * + * @param dao the DAO to use to access the database + * @param policyId ID of the policy. + * @return the deleted policy + * @throws PfModelException on errors deleting policies + */ + public LegacyOperationalPolicy deleteOperationalPolicy(@NonNull final PfDao dao, @NonNull final String policyId) + throws PfModelException { + + // Get all the policies in the database and check the policy ID against the policies returned + List<ToscaPolicy> policyList = dao.getAll(ToscaPolicy.class); + + // Find the latest policy that matches the ID + List<ToscaPolicy> policyDeleteList = new ArrayList<>(); + + for (ToscaPolicy policy : policyList) { + if (policyId.equals(policy.getKey().getName())) { + policyDeleteList.add(policy); + } + } + + if (policyDeleteList.isEmpty()) { + String errorMessage = NO_POLICY_FOUND_FOR_POLICY_ID + policyId; + LOGGER.warn(errorMessage); + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage); + } + + // Create the structure of the TOSCA service template to contain the policy type + ToscaServiceTemplate serviceTemplate = new ToscaServiceTemplate(); + serviceTemplate.setTopologyTemplate(new ToscaTopologyTemplate()); + serviceTemplate.getTopologyTemplate().setPolicies(new ToscaPolicies()); + + for (ToscaPolicy deletePolicy : policyDeleteList) { + dao.delete(deletePolicy); + serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().put(deletePolicy.getKey(), + deletePolicy); + } + + return new LegacyOperationalPolicyMapper().fromToscaServiceTemplate(serviceTemplate); + } + + /** + * Get legacy guard policy. + * + * @param dao the DAO to use to access the database + * @param policyId ID of the policy. + * @return the policies found + * @throws PfModelException on errors getting policies + */ + public LegacyGuardPolicy getGuardPolicy(@NonNull final PfDao dao, @NonNull final String policyId) + throws PfModelException { + return null; + } + + /** + * Create legacy guard policy. + * + * @param dao the DAO to use to access the database + * @param legacyGuardPolicy the definition of the policy to be created. + * @return the created policy + * @throws PfModelException on errors creating policies + */ + public LegacyGuardPolicy createGuardPolicy(@NonNull final PfDao dao, + @NonNull final LegacyGuardPolicy legacyGuardPolicy) throws PfModelException { + return null; + } + + /** + * Update legacy guard policy. + * + * @param dao the DAO to use to access the database + * @param legacyGuardPolicy the definition of the policy to be updated + * @return the updated policy + * @throws PfModelException on errors updating policies + */ + public LegacyGuardPolicy updateGuardPolicy(@NonNull final PfDao dao, + @NonNull final LegacyGuardPolicy legacyGuardPolicy) throws PfModelException { + return null; + } + + + /** + * Delete legacy guard policy. + * + * @param dao the DAO to use to access the database + * @param policyId ID of the policy. + * @return the deleted policy + * @throws PfModelException on errors deleting policies + */ + public LegacyGuardPolicy deleteGuardPolicy(@NonNull final PfDao dao, @NonNull final String policyId) + throws PfModelException { + return null; + } + + /** + * Get the latest policy for a policy ID. + * + * @param dao The DAO to read from + * @param policyId the ID of the policy + * @return the policy + */ + private ToscaPolicy getLatestPolicy(final PfDao dao, final String policyId) { + // Get all the policies in the database and check the policy ID against the policies returned + List<ToscaPolicy> policyList = dao.getAll(ToscaPolicy.class); + + // Find the latest policy that matches the ID + ToscaPolicy newestPolicy = null; + + for (ToscaPolicy policy : policyList) { + if (!policyId.equals(policy.getKey().getName())) { + continue; + } + + // We found a matching policy + if (newestPolicy == null || policy.getKey().isNewerThan(newestPolicy.getKey())) { + // First policy found + newestPolicy = policy; + } + } + return newestPolicy; + } +} diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/provider/LegacyToscaProvider.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/provider/LegacyToscaProvider.java deleted file mode 100644 index da9d929df..000000000 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/legacy/provider/LegacyToscaProvider.java +++ /dev/null @@ -1,139 +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.tosca.legacy.provider; - -import lombok.NonNull; - -import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.dao.PfDao; -import org.onap.policy.models.tosca.legacy.concepts.LegacyGuardPolicy; -import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy; - -/** - * This class provides the provision of information on TOSCA concepts in the database to callers in legacy formats. - * - * @author Liam Fallon (liam.fallon@est.tech) - */ -public class LegacyToscaProvider { - /** - * Get legacy operational policy. - * - * @param dao the DAO to use to access the database - * @param policyId ID of the policy. - * @return the policies found - * @throws PfModelException on errors getting policies - */ - public LegacyOperationalPolicy getOperationalPolicy(@NonNull final PfDao dao, @NonNull final String policyId) - throws PfModelException { - return null; - } - - /** - * Create legacy operational policy. - * - * @param dao the DAO to use to access the database - * @param legacyOperationalPolicy the definition of the policy to be created. - * @return the created policy - * @throws PfModelException on errors creating policies - */ - public LegacyOperationalPolicy createOperationalPolicy(@NonNull final PfDao dao, - @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException { - return null; - } - - /** - * Update legacy operational policy. - * - * @param dao the DAO to use to access the database - * @param legacyOperationalPolicy the definition of the policy to be updated - * @return the updated policy - * @throws PfModelException on errors updating policies - */ - public LegacyOperationalPolicy updateOperationalPolicy(@NonNull final PfDao dao, - @NonNull final LegacyOperationalPolicy legacyOperationalPolicy) throws PfModelException { - return null; - } - - /** - * Delete legacy operational policy. - * - * @param dao the DAO to use to access the database - * @param policyId ID of the policy. - * @return the deleted policy - * @throws PfModelException on errors deleting policies - */ - public LegacyOperationalPolicy deleteOperationalPolicy(@NonNull final PfDao dao, @NonNull final String policyId) - throws PfModelException { - return null; - } - - /** - * Get legacy guard policy. - * - * @param dao the DAO to use to access the database - * @param policyId ID of the policy. - * @return the policies found - * @throws PfModelException on errors getting policies - */ - public LegacyGuardPolicy getGuardPolicy(@NonNull final PfDao dao, @NonNull final String policyId) - throws PfModelException { - return null; - } - - /** - * Create legacy guard policy. - * - * @param dao the DAO to use to access the database - * @param legacyGuardPolicy the definition of the policy to be created. - * @return the created policy - * @throws PfModelException on errors creating policies - */ - public LegacyGuardPolicy createGuardPolicy(@NonNull final PfDao dao, - @NonNull final LegacyGuardPolicy legacyGuardPolicy) throws PfModelException { - return null; - } - - /** - * Update legacy guard policy. - * - * @param dao the DAO to use to access the database - * @param legacyGuardPolicy the definition of the policy to be updated - * @return the updated policy - * @throws PfModelException on errors updating policies - */ - public LegacyGuardPolicy updateGuardPolicy(@NonNull final PfDao dao, - @NonNull final LegacyGuardPolicy legacyGuardPolicy) throws PfModelException { - return null; - } - - /** - * Delete legacy guard policy. - * - * @param dao the DAO to use to access the database - * @param policyId ID of the policy. - * @return the deleted policy - * @throws PfModelException on errors deleting policies - */ - public LegacyGuardPolicy deleteGuardPolicy(@NonNull final PfDao dao, @NonNull final String policyId) - throws PfModelException { - return null; - } -} diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaConstraintValidValues.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaConstraintValidValues.java new file mode 100644 index 000000000..98629a603 --- /dev/null +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaConstraintValidValues.java @@ -0,0 +1,121 @@ +/*- + * ============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.tosca.simple.concepts; + +import com.google.gson.annotations.SerializedName; + +import java.util.LinkedList; +import java.util.List; +import javax.persistence.ElementCollection; +import javax.ws.rs.core.Response; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NonNull; + +import org.onap.policy.models.base.PfConcept; +import org.onap.policy.models.base.PfModelRuntimeException; +import org.onap.policy.models.base.PfReferenceKey; + +/** + * This class represents valid_values TOSCA constraint. + * + * @author Chenfei Gao (cgao@research.att.com) + */ +@EqualsAndHashCode(callSuper = false) +@Data +public class ToscaConstraintValidValues extends ToscaConstraint { + private static final long serialVersionUID = 3152323457560746844L; + + @SerializedName("valid_values") + @NonNull + @ElementCollection + private final List<String> validValues; + + /** + * The Default Constructor creates a {@link ToscaConstraintValidValues} object with a null key. + */ + public ToscaConstraintValidValues() { + this(new PfReferenceKey()); + } + + /** + * The Key Constructor creates a {@link ToscaConstraintValidValues} object with the given concept key. + * + * @param key the key of the constraint + */ + public ToscaConstraintValidValues(final PfReferenceKey key) { + super(key); + validValues = new LinkedList<>(); + } + + /** + * The Key Constructor creates a {@link ToscaConstraintLogical} object with the given concept key + * and valid values list. + * + * @param key the key of the constraint + * @param validValues the valid values list of the constraint + * + */ + public ToscaConstraintValidValues(final PfReferenceKey key, @NonNull final List<String> validValues) { + super(key); + this.validValues = validValues; + } + + /** + * Copy constructor. + * + * @param copyConcept the concept to copy from + */ + public ToscaConstraintValidValues(@NonNull final ToscaConstraintValidValues copyConcept) { + throw new PfModelRuntimeException(Response.Status.INTERNAL_SERVER_ERROR, "cannot copy an immutable constraint"); + } + + @Override + public int compareTo(final PfConcept otherConcept) { + if (otherConcept == null) { + return -1; + } + if (this == otherConcept) { + return 0; + } + if (getClass() != otherConcept.getClass()) { + return this.hashCode() - otherConcept.hashCode(); + } + + final ToscaConstraintValidValues other = (ToscaConstraintValidValues) otherConcept; + + int result = super.compareTo(other); + if (result != 0) { + return result; + } + + if (validValues.equals(other.validValues)) { + return 0; + } + return -1; + } + + @Override + public PfConcept copyTo(@NonNull final PfConcept target) { + throw new PfModelRuntimeException(Response.Status.INTERNAL_SERVER_ERROR, "cannot copy an immutable constraint"); + } +} diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaDataTypes.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaDataTypes.java index cbf0e3844..eae98a1bc 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaDataTypes.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaDataTypes.java @@ -47,12 +47,15 @@ import org.onap.policy.models.base.PfConceptKey; public class ToscaDataTypes extends PfConceptContainer<ToscaDataType> { private static final long serialVersionUID = 2941102271022190348L; + public static final String DEFAULT_NAME = "ToscaDataTypesSimple"; + public static final String DEFAULT_VERSION = "1.0.0"; + /** * The Default Constructor creates a {@link ToscaDataTypes} object with a null artifact key * and creates an empty concept map. */ public ToscaDataTypes() { - super(new PfConceptKey()); + super(new PfConceptKey(DEFAULT_NAME, DEFAULT_VERSION)); } /** diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaPolicies.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaPolicies.java index 9dd12ec88..f318bb6be 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaPolicies.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaPolicies.java @@ -47,12 +47,15 @@ import org.onap.policy.models.base.PfConceptKey; public class ToscaPolicies extends PfConceptContainer<ToscaPolicy> { private static final long serialVersionUID = -7526648702327776101L; + public static final String DEFAULT_NAME = "ToscaPoliciesSimple"; + public static final String DEFAULT_VERSION = "1.0.0"; + /** * The Default Constructor creates a {@link ToscaPolicies} object with a null artifact key and * creates an empty concept map. */ public ToscaPolicies() { - super(new PfConceptKey()); + super(new PfConceptKey(DEFAULT_NAME, DEFAULT_VERSION)); } /** diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaPolicyTypes.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaPolicyTypes.java index 23159ccfa..277291364 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaPolicyTypes.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaPolicyTypes.java @@ -47,12 +47,15 @@ import org.onap.policy.models.base.PfConceptKey; public class ToscaPolicyTypes extends PfConceptContainer<ToscaPolicyType> { private static final long serialVersionUID = -4157979965271220098L; + public static final String DEFAULT_NAME = "ToscaPolicyTypesSimple"; + public static final String DEFAULT_VERSION = "1.0.0"; + /** * The Default Constructor creates a {@link ToscaPolicyTypes} object with a null artifact key * and creates an empty concept map. */ public ToscaPolicyTypes() { - super(new PfConceptKey()); + super(new PfConceptKey(DEFAULT_NAME, DEFAULT_VERSION)); } /** diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaProperty.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaProperty.java index da13877c6..2276f5a7a 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaProperty.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaProperty.java @@ -82,7 +82,7 @@ public class ToscaProperty extends PfConcept { @Column(name = "default") @SerializedName("default") - private PfKey defaultValue; + private String defaultValue; @Column @NonNull @@ -137,10 +137,6 @@ public class ToscaProperty extends PfConcept { keyList.addAll(type.getKeys()); - if (defaultValue != null) { - keyList.addAll(defaultValue.getKeys()); - } - if (constraints != null) { for (ToscaConstraint constraint : constraints) { keyList.addAll(constraint.getKeys()); @@ -165,7 +161,7 @@ public class ToscaProperty extends PfConcept { } if (defaultValue != null) { - defaultValue.clean(); + defaultValue = defaultValue.trim(); } if (constraints != null) { @@ -212,7 +208,7 @@ public class ToscaProperty extends PfConcept { "property description may not be blank")); } - if (defaultValue != null && defaultValue.isNullKey()) { + if (defaultValue != null && defaultValue.trim().length() == 0) { result.addValidationMessage(new PfValidationMessage(key, this.getClass(), ValidationResult.INVALID, "property default value may not be null")); } diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaServiceTemplate.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaServiceTemplate.java index fd8b134ce..c3bb9165e 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaServiceTemplate.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaServiceTemplate.java @@ -60,6 +60,9 @@ import org.onap.policy.models.base.PfValidationResult.ValidationResult; public class ToscaServiceTemplate extends ToscaEntityType { private static final long serialVersionUID = 8084846046148349401L; + public static final String DEFAULT_NAME = "ToscaServiceTemplateSimple"; + public static final String DEFAULT_VERSION = "1.0.0"; + @Column @SerializedName("tosca_definitions_version") private String toscaDefinitionsVersion; @@ -80,7 +83,7 @@ public class ToscaServiceTemplate extends ToscaEntityType { * The Default Constructor creates a {@link ToscaServiceTemplate} object with a null key. */ public ToscaServiceTemplate() { - this(new PfConceptKey()); + this(new PfConceptKey(DEFAULT_NAME, DEFAULT_VERSION)); } /** diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaTopologyTemplate.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaTopologyTemplate.java index 9d156c3df..5b21ca0c1 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaTopologyTemplate.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/concepts/ToscaTopologyTemplate.java @@ -45,8 +45,8 @@ import org.onap.policy.models.base.PfValidationResult; import org.onap.policy.models.base.PfValidationResult.ValidationResult; /** - * This class holds a TOSCA topology template. Note: Only the policy specific parts of the TOSCA - * topology template are implemented. + * This class holds a TOSCA topology template. Note: Only the policy specific parts of the TOSCA topology template are + * implemented. * * @author Liam Fallon (liam.fallon@est.tech) */ @@ -58,6 +58,8 @@ import org.onap.policy.models.base.PfValidationResult.ValidationResult; public class ToscaTopologyTemplate extends PfConcept { private static final long serialVersionUID = 8969698734673232603L; + public static final String DEFAULT_LOCAL_NAME = "ToscaTopologyTemplateSimple"; + @EmbeddedId private PfReferenceKey key; @@ -71,7 +73,8 @@ public class ToscaTopologyTemplate extends PfConcept { * The Default Constructor creates a {@link ToscaTopologyTemplate} object with a null key. */ public ToscaTopologyTemplate() { - this(new PfReferenceKey()); + this(new PfReferenceKey(ToscaServiceTemplate.DEFAULT_NAME, ToscaServiceTemplate.DEFAULT_VERSION, + DEFAULT_LOCAL_NAME)); } /** diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProvider.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProvider.java index 3d563a1cc..c7984c5ea 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProvider.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProvider.java @@ -20,12 +20,23 @@ package org.onap.policy.models.tosca.simple.provider; +import javax.ws.rs.core.Response; + import lombok.NonNull; import org.onap.policy.models.base.PfConceptKey; import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.dao.PfDao; +import org.onap.policy.models.tosca.simple.concepts.ToscaPolicies; +import org.onap.policy.models.tosca.simple.concepts.ToscaPolicy; +import org.onap.policy.models.tosca.simple.concepts.ToscaPolicyType; +import org.onap.policy.models.tosca.simple.concepts.ToscaPolicyTypes; import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate; +import org.onap.policy.models.tosca.simple.concepts.ToscaTopologyTemplate; +import org.onap.policy.models.tosca.utils.ToscaUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * This class provides the provision of information on TOSCA concepts in the database to callers. @@ -33,6 +44,8 @@ import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate; * @author Liam Fallon (liam.fallon@est.tech) */ public class SimpleToscaProvider { + private static final Logger LOGGER = LoggerFactory.getLogger(SimpleToscaProvider.class); + /** * Get policy types. * @@ -44,7 +57,21 @@ public class SimpleToscaProvider { */ public ToscaServiceTemplate getPolicyTypes(@NonNull final PfDao dao, @NonNull final PfConceptKey policyTypeKey) throws PfModelException { - return null; + + // Create the structure of the TOSCA service template to contain the policy type + ToscaServiceTemplate serviceTemplate = new ToscaServiceTemplate(); + serviceTemplate.setPolicyTypes(new ToscaPolicyTypes()); + + // Add the policy type to the TOSCA service template + ToscaPolicyType policyType = dao.get(ToscaPolicyType.class, policyTypeKey); + if (policyType != null) { + serviceTemplate.getPolicyTypes().getConceptMap().put(policyTypeKey, policyType); + return serviceTemplate; + } else { + String errorMessage = "policy type not found: " + policyTypeKey.getId(); + LOGGER.warn(errorMessage); + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage); + } } /** @@ -57,7 +84,24 @@ public class SimpleToscaProvider { */ public ToscaServiceTemplate createPolicyTypes(@NonNull final PfDao dao, @NonNull final ToscaServiceTemplate serviceTemplate) throws PfModelException { - return null; + + ToscaUtils.assertPolicyTypesExist(serviceTemplate); + + for (ToscaPolicyType policyType : serviceTemplate.getPolicyTypes().getAll(null)) { + dao.create(policyType); + } + + // Return the created policy types + ToscaPolicyTypes returnPolicyTypes = new ToscaPolicyTypes(); + + for (PfConceptKey policyTypeKey : serviceTemplate.getPolicyTypes().getConceptMap().keySet()) { + returnPolicyTypes.getConceptMap().put(policyTypeKey, dao.get(ToscaPolicyType.class, policyTypeKey)); + } + + ToscaServiceTemplate returnServiceTemplate = new ToscaServiceTemplate(); + returnServiceTemplate.setPolicyTypes(returnPolicyTypes); + + return returnServiceTemplate; } /** @@ -70,7 +114,24 @@ public class SimpleToscaProvider { */ public ToscaServiceTemplate updatePolicyTypes(@NonNull final PfDao dao, @NonNull final ToscaServiceTemplate serviceTemplate) throws PfModelException { - return null; + + ToscaUtils.assertPolicyTypesExist(serviceTemplate); + + for (ToscaPolicyType policyType : serviceTemplate.getPolicyTypes().getAll(null)) { + dao.update(policyType); + } + + // Return the created policy types + ToscaPolicyTypes returnPolicyTypes = new ToscaPolicyTypes(); + + for (PfConceptKey policyTypeKey : serviceTemplate.getPolicyTypes().getConceptMap().keySet()) { + returnPolicyTypes.getConceptMap().put(policyTypeKey, dao.get(ToscaPolicyType.class, policyTypeKey)); + } + + ToscaServiceTemplate returnServiceTemplate = new ToscaServiceTemplate(); + returnServiceTemplate.setPolicyTypes(returnPolicyTypes); + + return returnServiceTemplate; } /** @@ -84,7 +145,12 @@ public class SimpleToscaProvider { */ public ToscaServiceTemplate deletePolicyTypes(@NonNull final PfDao dao, @NonNull final PfConceptKey policyTypeKey) throws PfModelException { - return null; + + ToscaServiceTemplate serviceTemplate = getPolicyTypes(dao, policyTypeKey); + + dao.delete(ToscaPolicyType.class, policyTypeKey); + + return serviceTemplate; } /** @@ -98,7 +164,22 @@ public class SimpleToscaProvider { */ public ToscaServiceTemplate getPolicies(@NonNull final PfDao dao, @NonNull final PfConceptKey policyKey) throws PfModelException { - return null; + + // Create the structure of the TOSCA service template to contain the policy type + ToscaServiceTemplate serviceTemplate = new ToscaServiceTemplate(); + serviceTemplate.setTopologyTemplate(new ToscaTopologyTemplate()); + serviceTemplate.getTopologyTemplate().setPolicies(new ToscaPolicies()); + + // Add the policy to the TOSCA service template + ToscaPolicy policy = dao.get(ToscaPolicy.class, policyKey); + if (policy != null) { + serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().put(policyKey, policy); + return serviceTemplate; + } else { + String errorMessage = "policy not found: " + policyKey.getId(); + LOGGER.warn(errorMessage); + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage); + } } /** @@ -111,7 +192,24 @@ public class SimpleToscaProvider { */ public ToscaServiceTemplate createPolicies(@NonNull final PfDao dao, @NonNull final ToscaServiceTemplate serviceTemplate) throws PfModelException { - return null; + + ToscaUtils.assertPoliciesExist(serviceTemplate); + + for (ToscaPolicy policy : serviceTemplate.getTopologyTemplate().getPolicies().getAll(null)) { + dao.create(policy); + } + + // Return the created policy types + ToscaPolicies returnPolicies = new ToscaPolicies(); + returnPolicies.setKey(serviceTemplate.getTopologyTemplate().getPolicies().getKey()); + + for (PfConceptKey policyKey : serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().keySet()) { + returnPolicies.getConceptMap().put(policyKey, dao.get(ToscaPolicy.class, policyKey)); + } + + serviceTemplate.getTopologyTemplate().setPolicies(returnPolicies); + + return serviceTemplate; } /** @@ -124,7 +222,24 @@ public class SimpleToscaProvider { */ public ToscaServiceTemplate updatePolicies(@NonNull final PfDao dao, @NonNull final ToscaServiceTemplate serviceTemplate) throws PfModelException { - return null; + + ToscaUtils.assertPoliciesExist(serviceTemplate); + + for (ToscaPolicy policy : serviceTemplate.getTopologyTemplate().getPolicies().getAll(null)) { + dao.update(policy); + } + + // Return the created policy types + ToscaPolicies returnPolicies = new ToscaPolicies(); + returnPolicies.setKey(serviceTemplate.getTopologyTemplate().getPolicies().getKey()); + + for (PfConceptKey policyKey : serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().keySet()) { + returnPolicies.getConceptMap().put(policyKey, dao.get(ToscaPolicy.class, policyKey)); + } + + serviceTemplate.getTopologyTemplate().setPolicies(returnPolicies); + + return serviceTemplate; } /** @@ -132,11 +247,16 @@ public class SimpleToscaProvider { * * @param dao the DAO to use to access the database * @param policyKey the policy key - * @return the TOSCA service template containing the policy types that were deleted + * @return the TOSCA service template containing the policies that were deleted * @throws PfModelException on errors deleting policies */ public ToscaServiceTemplate deletePolicies(@NonNull final PfDao dao, @NonNull final PfConceptKey policyKey) throws PfModelException { - return null; + + ToscaServiceTemplate serviceTemplate = getPolicies(dao, policyKey); + + dao.delete(ToscaPolicy.class, policyKey); + + return serviceTemplate; } } diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaDataTypeJsonAdapter.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaDataTypeJsonAdapter.java new file mode 100644 index 000000000..65e3d4ebf --- /dev/null +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaDataTypeJsonAdapter.java @@ -0,0 +1,139 @@ +/*- + * ============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.tosca.simple.serialization; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; + +import java.lang.reflect.Type; +import javax.ws.rs.core.Response; + +import lombok.NonNull; + +import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.base.PfModelRuntimeException; +import org.onap.policy.models.tosca.simple.concepts.ToscaDataType; +import org.onap.policy.models.tosca.simple.concepts.ToscaProperty; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * GSON type adapter for TOSCA data types. + * + * @author Chenfei Gao (cgao@research.att.com) + */ +public class ToscaDataTypeJsonAdapter implements JsonSerializer<ToscaDataType>, JsonDeserializer<ToscaDataType> { + + private static final Logger LOGGER = LoggerFactory.getLogger(ToscaDataTypeJsonAdapter.class); + + private static final String DERIVED_FROM = "derived_from"; + private static final String DESCRIPTION = "description"; + private static final String VERSION = "version"; + private static final String PROPERTIES = "properties"; + private static final String DEFAULT_VERSION = "1.0.0"; + + @Override + public ToscaDataType deserialize(@NonNull final JsonElement dataTypeElement, @NonNull final Type type, + @NonNull final JsonDeserializationContext context) { + + // The incoming JSON + final JsonObject dataTypeJsonMapObject = dataTypeElement.getAsJsonObject(); + + // We should only have a single entry for the policy type + if (dataTypeJsonMapObject.entrySet().size() != 1) { + String errorMessage = "a policy type list entry may only contain one and only one policy type"; + LOGGER.debug(errorMessage); + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage); + } + + final String dataTypeName = dataTypeJsonMapObject.entrySet().iterator().next().getKey(); + final JsonObject dataTypeJsonObject = dataTypeJsonMapObject.entrySet().iterator().next() + .getValue().getAsJsonObject(); + + // Set keys + PfConceptKey dataTypeKey; + if (dataTypeJsonObject.get(VERSION) == null) { + dataTypeKey = new PfConceptKey(dataTypeName, DEFAULT_VERSION); + } else { + dataTypeKey = new PfConceptKey(dataTypeName, dataTypeJsonObject.get(VERSION).getAsString()); + } + ToscaDataType dataType = new ToscaDataType(dataTypeKey); + + // Set derived_from + dataType.setDerivedFrom(new PfConceptKey(dataTypeJsonObject.get(DERIVED_FROM).getAsString(), + DEFAULT_VERSION)); + + // Set description + if (dataTypeJsonObject.has(DESCRIPTION)) { + final String dataTypeDescription = dataTypeJsonObject.get(DESCRIPTION).getAsString(); + dataType.setDescription(dataTypeDescription); + } + + // Set properties + if (dataTypeJsonObject.has(PROPERTIES)) { + dataType.setProperties( + new ToscaPropertiesJsonAdapter().deserializeProperties(dataTypeJsonObject.get(PROPERTIES))); + for (ToscaProperty property : dataType.getProperties()) { + property.getKey().setParentConceptKey(dataTypeKey); + property.getType().setVersion(dataType.getKey().getVersion()); + } + } + + return dataType; + } + + @Override + public JsonElement serialize(@NonNull final ToscaDataType dataType, @NonNull final Type type, + @NonNull final JsonSerializationContext context) { + + JsonObject dataTypeValJsonObject = new JsonObject(); + + // Add derived_from + if (dataType.getDerivedFrom() != null) { + dataTypeValJsonObject.addProperty(DERIVED_FROM, dataType.getDerivedFrom().getName()); + } + + // Add description + if (dataType.getDescription() != null) { + dataTypeValJsonObject.addProperty(DESCRIPTION, dataType.getDescription()); + } + + // Add version + if (dataType.getKey().getVersion() != null) { + dataTypeValJsonObject.addProperty(VERSION, dataType.getKey().getVersion()); + } + + // Add properties + if (dataType.getProperties() != null) { + JsonElement propertiesJsonElement = new ToscaPropertiesJsonAdapter() + .serializeProperties(dataType.getProperties()); + dataTypeValJsonObject.add(PROPERTIES, propertiesJsonElement); + } + + JsonObject dataTypeJsonObject = new JsonObject(); + dataTypeJsonObject.add(dataType.getKey().getName(), dataTypeValJsonObject); + return dataTypeJsonObject; + } +} diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaDataTypesJsonAdapter.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaDataTypesJsonAdapter.java new file mode 100644 index 000000000..387b499cf --- /dev/null +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaDataTypesJsonAdapter.java @@ -0,0 +1,93 @@ +/*- + * ============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.tosca.simple.serialization; + +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; + +import java.lang.reflect.Type; +import java.util.Iterator; +import javax.ws.rs.core.Response; +import lombok.NonNull; + +import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.base.PfModelRuntimeException; +import org.onap.policy.models.tosca.simple.concepts.ToscaDataType; +import org.onap.policy.models.tosca.simple.concepts.ToscaDataTypes; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * GSON type adapter for TOSCA data types. + * + * @author Chenfei Gao (cgao@research.att.com) + */ +public class ToscaDataTypesJsonAdapter implements JsonSerializer<ToscaDataTypes>, JsonDeserializer<ToscaDataTypes> { + + private static final Logger LOGGER = LoggerFactory.getLogger(ToscaDataTypesJsonAdapter.class); + + @Override + public ToscaDataTypes deserialize(@NonNull final JsonElement dataTypesElement, @NonNull final Type type, + @NonNull final JsonDeserializationContext context) { + + // The incoming JSON + final JsonArray dataTypesJsonArray = dataTypesElement.getAsJsonArray(); + + // The outgoing object + final PfConceptKey dataTypesKey = new PfConceptKey("IncomingDataTypes", "0.0.1"); + final ToscaDataTypes dataTypes = new ToscaDataTypes(dataTypesKey); + + // Get the dataTypes + Iterator<JsonElement> dataTypesIterator = dataTypesJsonArray.iterator(); + while (dataTypesIterator.hasNext()) { + ToscaDataType dataType = new ToscaDataTypeJsonAdapter() + .deserialize(dataTypesIterator.next(), ToscaDataType.class, context); + + dataTypes.getConceptMap().put(dataType.getKey(), dataType); + } + + return dataTypes; + } + + @Override + public JsonElement serialize(@NonNull final ToscaDataTypes dataTypes, @NonNull final Type type, + @NonNull final JsonSerializationContext context) { + + JsonArray dataTypesJsonArray = new JsonArray(); + + if (dataTypes.getConceptMap().isEmpty()) { + String errorMessage = "data type list is empty"; + LOGGER.debug(errorMessage); + throw new PfModelRuntimeException(Response.Status.INTERNAL_SERVER_ERROR, errorMessage); + } + + for (ToscaDataType dataType: dataTypes.getConceptMap().values()) { + JsonElement dataTypeEntry = new ToscaDataTypeJsonAdapter().serialize(dataType, type, context); + dataTypesJsonArray.add(dataTypeEntry); + } + + return dataTypesJsonArray; + } +} diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaPoliciesJsonAdapter.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaPoliciesJsonAdapter.java index 53088d637..4b1b53c79 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaPoliciesJsonAdapter.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaPoliciesJsonAdapter.java @@ -43,6 +43,7 @@ import org.onap.policy.models.tosca.simple.concepts.ToscaPolicy; * @author Chenfei Gao (cgao@research.att.com) */ public class ToscaPoliciesJsonAdapter implements JsonSerializer<ToscaPolicies>, JsonDeserializer<ToscaPolicies> { + @Override public ToscaPolicies deserialize(@NonNull final JsonElement policiesElement, @NonNull final Type type, @NonNull final JsonDeserializationContext context) { @@ -73,7 +74,6 @@ public class ToscaPoliciesJsonAdapter implements JsonSerializer<ToscaPolicies>, for (ToscaPolicy policy: policies.getConceptMap().values()) { policiesJsonArray.add(new ToscaPolicyJsonAdapter().serialize(policy, type, context)); } - return policiesJsonArray; } } diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaPolicyJsonAdapter.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaPolicyJsonAdapter.java index 95b4b3bba..b52634b83 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaPolicyJsonAdapter.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaPolicyJsonAdapter.java @@ -151,7 +151,7 @@ public class ToscaPolicyJsonAdapter implements JsonSerializer<ToscaPolicy>, Json JsonObject propertiesMapObject = new JsonObject(); for (Entry<String, String> entry : policy.getProperties().entrySet()) { // TODO: This is the other direction of the HACK - JsonObject valueObject = gson.fromJson(entry.getValue(), JsonObject.class); + JsonElement valueObject = gson.fromJson(entry.getValue(), JsonElement.class); propertiesMapObject.add(entry.getKey(), valueObject); } policyValJsonObject.add(PROPERTIES, propertiesMapObject); diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaPolicyTypeJsonAdapter.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaPolicyTypeJsonAdapter.java new file mode 100644 index 000000000..3bf98572f --- /dev/null +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaPolicyTypeJsonAdapter.java @@ -0,0 +1,138 @@ +/*- + * ============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.tosca.simple.serialization; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import java.lang.reflect.Type; +import javax.ws.rs.core.Response; + +import lombok.NonNull; + +import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.base.PfModelRuntimeException; +import org.onap.policy.models.tosca.simple.concepts.ToscaPolicyType; +import org.onap.policy.models.tosca.simple.concepts.ToscaProperty; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * GSON type adapter for TOSCA policy types. + * + * @author Chenfei Gao (cgao@research.att.com) + */ +public class ToscaPolicyTypeJsonAdapter implements JsonSerializer<ToscaPolicyType>, JsonDeserializer<ToscaPolicyType> { + + private static final Logger LOGGER = LoggerFactory.getLogger(ToscaPolicyTypeJsonAdapter.class); + + private static final String DERIVED_FROM = "derived_from"; + private static final String DESCRIPTION = "description"; + private static final String VERSION = "version"; + private static final String PROPERTIES = "properties"; + private static final String DEFAULT_VERSION = "1.0.0"; + + @Override + public ToscaPolicyType deserialize(@NonNull final JsonElement policyTypeElement, @NonNull final Type type, + @NonNull final JsonDeserializationContext context) { + + // The incoming JSON + final JsonObject policyTypeJsonMapObject = policyTypeElement.getAsJsonObject(); + + // We should only have a single entry for the policy type + if (policyTypeJsonMapObject.entrySet().size() != 1) { + String errorMessage = "a policy type list entry may only contain one and only one policy type"; + LOGGER.debug(errorMessage); + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage); + } + + final String policyTypeName = policyTypeJsonMapObject.entrySet().iterator().next().getKey(); + final JsonObject policyTypeJsonObject = policyTypeJsonMapObject.entrySet().iterator().next() + .getValue().getAsJsonObject(); + + // Set keys + PfConceptKey policyTypeKey; + if (policyTypeJsonObject.get(VERSION) == null) { + policyTypeKey = new PfConceptKey(policyTypeName, DEFAULT_VERSION); + } else { + policyTypeKey = new PfConceptKey(policyTypeName, policyTypeJsonObject.get(VERSION).getAsString()); + } + ToscaPolicyType policyType = new ToscaPolicyType(policyTypeKey); + + // Set derived_from + policyType.setDerivedFrom(new PfConceptKey(policyTypeJsonObject.get(DERIVED_FROM).getAsString(), + DEFAULT_VERSION)); + + // Set description + if (policyTypeJsonObject.has(DESCRIPTION)) { + final String policyTypeDescription = policyTypeJsonObject.get(DESCRIPTION).getAsString(); + policyType.setDescription(policyTypeDescription); + } + + // Set properties + if (policyTypeJsonObject.has(PROPERTIES)) { + policyType.setProperties( + new ToscaPropertiesJsonAdapter().deserializeProperties(policyTypeJsonObject.get(PROPERTIES))); + for (ToscaProperty property : policyType.getProperties()) { + property.getKey().setParentConceptKey(policyTypeKey); + property.getType().setVersion(policyType.getKey().getVersion()); + } + } + + return policyType; + } + + @Override + public JsonElement serialize(@NonNull final ToscaPolicyType policyType, @NonNull final Type type, + @NonNull final JsonSerializationContext context) { + + JsonObject policyTypeValJsonObject = new JsonObject(); + + // Add derived_from + if (policyType.getDerivedFrom() != null) { + policyTypeValJsonObject.addProperty(DERIVED_FROM, policyType.getDerivedFrom().getName()); + } + + // Add description + if (policyType.getDescription() != null) { + policyTypeValJsonObject.addProperty(DESCRIPTION, policyType.getDescription()); + } + + // Add version + if (policyType.getKey().getVersion() != null) { + policyTypeValJsonObject.addProperty(VERSION, policyType.getKey().getVersion()); + } + + // Add properties + if (policyType.getProperties() != null) { + JsonElement propertiesJsonElement = new ToscaPropertiesJsonAdapter() + .serializeProperties(policyType.getProperties()); + policyTypeValJsonObject.add(PROPERTIES, propertiesJsonElement); + } + + JsonObject policyTypeJsonObject = new JsonObject(); + policyTypeJsonObject.add(policyType.getKey().getName(), policyTypeValJsonObject); + return policyTypeJsonObject; + } +}
\ No newline at end of file diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaPolicyTypesJsonAdapter.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaPolicyTypesJsonAdapter.java new file mode 100644 index 000000000..c9e65117e --- /dev/null +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaPolicyTypesJsonAdapter.java @@ -0,0 +1,94 @@ +/*- + * ============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.tosca.simple.serialization; + +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; + +import java.lang.reflect.Type; +import java.util.Iterator; +import javax.ws.rs.core.Response; +import lombok.NonNull; + +import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.base.PfModelRuntimeException; +import org.onap.policy.models.tosca.simple.concepts.ToscaPolicyType; +import org.onap.policy.models.tosca.simple.concepts.ToscaPolicyTypes; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * GSON type adapter for TOSCA policy types. + * + * @author Chenfei Gao (cgao@research.att.com) + */ +public class ToscaPolicyTypesJsonAdapter implements JsonSerializer<ToscaPolicyTypes>, + JsonDeserializer<ToscaPolicyTypes> { + + private static final Logger LOGGER = LoggerFactory.getLogger(ToscaPolicyTypesJsonAdapter.class); + + @Override + public ToscaPolicyTypes deserialize(@NonNull final JsonElement policyTypesElement, @NonNull final Type type, + @NonNull final JsonDeserializationContext context) { + + // The incoming JSON + final JsonArray policyTypesJsonArray = policyTypesElement.getAsJsonArray(); + + // The outgoing object + final PfConceptKey policyTypesKey = new PfConceptKey("IncomingPolicyTypes", "0.0.1"); + final ToscaPolicyTypes policyTypes = new ToscaPolicyTypes(policyTypesKey); + + // Get the policyTypes + Iterator<JsonElement> policyTypesIterator = policyTypesJsonArray.iterator(); + while (policyTypesIterator.hasNext()) { + ToscaPolicyType policyType = new ToscaPolicyTypeJsonAdapter() + .deserialize(policyTypesIterator.next(), ToscaPolicyType.class, context); + + policyTypes.getConceptMap().put(policyType.getKey(), policyType); + } + + return policyTypes; + } + + @Override + public JsonElement serialize(@NonNull final ToscaPolicyTypes policyTypes, @NonNull final Type type, + @NonNull final JsonSerializationContext context) { + + JsonArray policyTypesJsonArray = new JsonArray(); + + if (policyTypes.getConceptMap().isEmpty()) { + String errorMessage = "policy type list is empty"; + LOGGER.debug(errorMessage); + throw new PfModelRuntimeException(Response.Status.INTERNAL_SERVER_ERROR, errorMessage); + } + + for (ToscaPolicyType policyType: policyTypes.getConceptMap().values()) { + JsonElement policyTypeEntry = new ToscaPolicyTypeJsonAdapter().serialize(policyType, type, context); + policyTypesJsonArray.add(policyTypeEntry); + } + + return policyTypesJsonArray; + } +}
\ No newline at end of file diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaPropertiesJsonAdapter.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaPropertiesJsonAdapter.java new file mode 100644 index 000000000..da15a800f --- /dev/null +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaPropertiesJsonAdapter.java @@ -0,0 +1,284 @@ +/*- + * ============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.tosca.simple.serialization; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map.Entry; +import javax.ws.rs.core.Response; + +import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.base.PfModelRuntimeException; +import org.onap.policy.models.base.PfReferenceKey; +import org.onap.policy.models.tosca.simple.concepts.ToscaConstraint; +import org.onap.policy.models.tosca.simple.concepts.ToscaConstraintLogical.Operation; +import org.onap.policy.models.tosca.simple.concepts.ToscaConstraintLogicalString; +import org.onap.policy.models.tosca.simple.concepts.ToscaConstraintValidValues; +import org.onap.policy.models.tosca.simple.concepts.ToscaEntrySchema; +import org.onap.policy.models.tosca.simple.concepts.ToscaProperty; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * GSON type adapter for TOSCA properties. + * + * @author Chenfei Gao (cgao@research.att.com) + */ +public class ToscaPropertiesJsonAdapter { + + private static final Logger LOGGER = LoggerFactory.getLogger(ToscaPropertiesJsonAdapter.class); + + private static final String DESCRIPTION = "description"; + private static final String REQUIRED = "required"; + private static final String DEFAULT = "default"; + private static final String TYPE = "type"; + private static final String ENTRY_SCHEMA = "entry_schema"; + private static final String CONSTRAINTS = "constraints"; + private static final String EQUAL = "equal"; + private static final String VALID_VALUES = "valid_values"; + private static final String DEFAULT_VERSION = "1.0.0"; + + /** + * Deserializes the properties. + * + * @param propertiesElement the properties in JsonElement + * + * @return deserialized ToscaProperty list + */ + public List<ToscaProperty> deserializeProperties(JsonElement propertiesElement) { + + final JsonObject propertiesMapObject = propertiesElement.getAsJsonObject(); + List<ToscaProperty> properties = new LinkedList<>(); + + for (Entry<String, JsonElement> entry : propertiesMapObject.entrySet()) { + final String propertyEntryKey = entry.getKey(); + final JsonElement propertyEntryVal = entry.getValue(); + + // Set property: key and type + ToscaProperty property = new ToscaProperty( + new PfReferenceKey(new PfConceptKey(), propertyEntryKey), + new PfConceptKey(propertyEntryVal.getAsJsonObject().get(TYPE).getAsString(), DEFAULT_VERSION)); + + // Set property: description + JsonObject propertyJsonObject = propertyEntryVal.getAsJsonObject(); + if (propertyJsonObject.has(DESCRIPTION)) { + property.setDescription(propertyJsonObject.get(DESCRIPTION).getAsString()); + } + + // Set property: required + if (propertyJsonObject.has(REQUIRED)) { + property.setRequired(propertyJsonObject.get(REQUIRED).getAsBoolean()); + } + + // Set property: default + if (propertyJsonObject.has(DEFAULT)) { + property.setDefaultValue(propertyJsonObject.get(DEFAULT).getAsString()); + } + + // Set property: entry_schema + if (propertyJsonObject.has(ENTRY_SCHEMA)) { + checkEntrySchemaCompatibility(property.getType().getName()); + property.setEntrySchema(deserializeEntrySchema(propertyJsonObject.get(ENTRY_SCHEMA))); + property.getEntrySchema().getKey().setParentConceptKey(property.getType()); + property.getEntrySchema().getType().setVersion(property.getType().getVersion()); + } + + // Set property: constraints + if (propertyJsonObject.has(CONSTRAINTS)) { + property.setConstraints(deserializeConstraints(propertyJsonObject.get(CONSTRAINTS))); + for (ToscaConstraint c : property.getConstraints()) { + c.getKey().setParentConceptKey(property.getType()); + } + } + + // Add property to properties list + properties.add(property); + } + + return properties; + } + + /** + * Serializes the properties. + * + * @param properties the list of ToscaProperty + * + * @return serialized JsonElement + */ + public JsonElement serializeProperties(List<ToscaProperty> properties) { + + JsonObject propertiesJsonObject = new JsonObject(); + + for (ToscaProperty property : properties) { + JsonObject propertyValJsonObject = new JsonObject(); + + // Add type + propertyValJsonObject.addProperty(TYPE, property.getType().getName()); + + // Add description + if (property.getDescription() != null) { + propertyValJsonObject.addProperty(DESCRIPTION, property.getDescription()); + } + + // Add required + propertyValJsonObject.addProperty(REQUIRED, property.isRequired()); + + // Add defaultValue + if (property.getDefaultValue() != null) { + propertyValJsonObject.addProperty(DEFAULT, property.getDefaultValue()); + } + + // Add constraints + if (property.getConstraints() != null) { + propertyValJsonObject.add(CONSTRAINTS, serializeConstraints(property.getConstraints())); + } + + // Add entry_schema + if (property.getEntrySchema() != null) { + propertyValJsonObject.add(ENTRY_SCHEMA, serializeEntrySchema(property.getEntrySchema())); + } + + propertiesJsonObject.add(property.getKey().getLocalName(), propertyValJsonObject); + } + + return propertiesJsonObject; + } + + private JsonElement serializeConstraints(List<ToscaConstraint> constraints) { + + JsonArray constraintsValJsonArray = new JsonArray(); + + for (ToscaConstraint c : constraints) { + JsonObject constraintJsonObject = new JsonObject(); + + // Check which type of constraint it is + // TODO: here we only support valid_values and equal + if (c instanceof ToscaConstraintValidValues) { + JsonArray validValuesJsonArray = new JsonArray(); + for (String validValue : ((ToscaConstraintValidValues)c).getValidValues()) { + validValuesJsonArray.add(validValue); + } + constraintJsonObject.add(VALID_VALUES, validValuesJsonArray); + } else if (c instanceof ToscaConstraintLogicalString) { + constraintJsonObject.addProperty(EQUAL, ((ToscaConstraintLogicalString)c).getCompareToString()); + } else { + String errorMessage = "constraint is neither valid_values nor equal"; + LOGGER.debug(errorMessage); + throw new PfModelRuntimeException(Response.Status.INTERNAL_SERVER_ERROR, errorMessage); + } + + constraintsValJsonArray.add(constraintJsonObject); + } + + return constraintsValJsonArray; + } + + private JsonElement serializeEntrySchema(ToscaEntrySchema entrySchema) { + + JsonObject entrySchemaValJsonObject = new JsonObject(); + + // Add type + entrySchemaValJsonObject.addProperty(TYPE, entrySchema.getType().getName()); + + // Add description + if (entrySchema.getDescription() != null) { + entrySchemaValJsonObject.addProperty(DESCRIPTION, entrySchema.getDescription()); + } + + // Add constraints + if (entrySchema.getConstraints() != null) { + entrySchemaValJsonObject.add(CONSTRAINTS, serializeConstraints(entrySchema.getConstraints())); + } + + return entrySchemaValJsonObject; + } + + private ToscaEntrySchema deserializeEntrySchema(JsonElement entrySchemaElement) { + + JsonObject entrySchemaJsonObject = entrySchemaElement.getAsJsonObject(); + + // Set entry_schema: key and type + ToscaEntrySchema entrySchema = new ToscaEntrySchema( + new PfReferenceKey(new PfConceptKey(), ENTRY_SCHEMA), + new PfConceptKey(entrySchemaJsonObject.get(TYPE).getAsString(), DEFAULT_VERSION)); + + // Set entry_schema: description + if (entrySchemaJsonObject.has(DESCRIPTION)) { + entrySchema.setDescription(entrySchemaJsonObject.get(DESCRIPTION).getAsString()); + } + + // Set entry_schema: constraints + if (entrySchemaJsonObject.has(CONSTRAINTS)) { + entrySchema.setConstraints(deserializeConstraints(entrySchemaJsonObject.get(CONSTRAINTS))); + for (ToscaConstraint c : entrySchema.getConstraints()) { + c.getKey().setParentConceptKey(entrySchema.getType()); + } + } + + return entrySchema; + } + + private List<ToscaConstraint> deserializeConstraints(JsonElement constraintsElement) { + + JsonArray constraintsJsonArray = constraintsElement.getAsJsonArray(); + List<ToscaConstraint> constraints = new LinkedList<>(); + + for (Iterator<JsonElement> constraintsIter = constraintsJsonArray.iterator(); constraintsIter.hasNext(); ) { + JsonObject constraintJsonObject = constraintsIter.next().getAsJsonObject(); + // Check which type of constraint it is + // TODO: here we only check 'valid_values' and 'equal' + if (constraintJsonObject.get(VALID_VALUES) != null) { + List<String> validValues = new LinkedList<>(); + for (Iterator<JsonElement> validValuesIter = constraintJsonObject.get(VALID_VALUES).getAsJsonArray() + .iterator(); validValuesIter.hasNext(); ) { + validValues.add(validValuesIter.next().getAsString()); + } + ToscaConstraint constraint = new ToscaConstraintValidValues( + new PfReferenceKey(new PfConceptKey(), VALID_VALUES), validValues); + constraints.add(constraint); + } else if (constraintJsonObject.get(EQUAL) != null) { + ToscaConstraint constraint = new ToscaConstraintLogicalString(new PfReferenceKey( + new PfConceptKey(), EQUAL), Operation.EQ, constraintJsonObject.get(EQUAL).getAsString()); + constraints.add(constraint); + } else { + String errorMessage = "specified constraint is neither valid_values nor equal"; + LOGGER.debug(errorMessage); + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage); + } + } + + return constraints; + } + + private void checkEntrySchemaCompatibility(String type) { + if (!("list".equalsIgnoreCase(type)) && !("map".equalsIgnoreCase(type))) { + String errorMessage = "entry schema can only be specified for list or map property"; + LOGGER.debug(errorMessage); + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage); + } + } +} diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaServiceTemplateJsonAdapter.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaServiceTemplateJsonAdapter.java index 613b0e292..78f3153e2 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaServiceTemplateJsonAdapter.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaServiceTemplateJsonAdapter.java @@ -32,7 +32,8 @@ import java.lang.reflect.Type; import lombok.NonNull; -import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.tosca.simple.concepts.ToscaDataTypes; +import org.onap.policy.models.tosca.simple.concepts.ToscaPolicyTypes; import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate; import org.onap.policy.models.tosca.simple.concepts.ToscaTopologyTemplate; @@ -47,6 +48,8 @@ public class ToscaServiceTemplateJsonAdapter private static final String TOPOLOGY_TEMPLATE = "topology_template"; private static final String TOSCA_DEFINITIONS_VERSION = "tosca_definitions_version"; + private static final String POLICY_TYPES = "policy_types"; + private static final String DATA_TYPES = "data_types"; @Override public ToscaServiceTemplate deserialize(@NonNull final JsonElement serviceTemplateElement, @NonNull final Type type, @@ -56,18 +59,27 @@ public class ToscaServiceTemplateJsonAdapter final JsonObject serviceTemplateJsonObject = serviceTemplateElement.getAsJsonObject(); // The outgoing object - final PfConceptKey serviceTemplateKey = new PfConceptKey("IncomingServiceTemplate", "0.0.1"); - final ToscaServiceTemplate serviceTemplate = new ToscaServiceTemplate(serviceTemplateKey); + final ToscaServiceTemplate serviceTemplate = new ToscaServiceTemplate(); serviceTemplate .setToscaDefinitionsVersion(serviceTemplateJsonObject.get(TOSCA_DEFINITIONS_VERSION).getAsString()); + // Set topology_template if (serviceTemplateJsonObject.has(TOPOLOGY_TEMPLATE)) { serviceTemplate.setTopologyTemplate(new ToscaTopologyTemplateJsonAdapter().deserialize( serviceTemplateJsonObject.get(TOPOLOGY_TEMPLATE), ToscaTopologyTemplate.class, context)); } - // Set the parent key of the topology template to be this service template - serviceTemplate.getTopologyTemplate().getKey().setParentConceptKey(serviceTemplateKey); + // Set policy_types + if (serviceTemplateJsonObject.has(POLICY_TYPES)) { + serviceTemplate.setPolicyTypes(new ToscaPolicyTypesJsonAdapter() + .deserialize(serviceTemplateJsonObject.get(POLICY_TYPES), ToscaPolicyTypes.class, context)); + } + + // Set data_types + if (serviceTemplateJsonObject.has(DATA_TYPES)) { + serviceTemplate.setDataTypes(new ToscaDataTypesJsonAdapter() + .deserialize(serviceTemplateJsonObject.get(DATA_TYPES), ToscaDataTypes.class, context)); + } return serviceTemplate; } @@ -77,11 +89,33 @@ public class ToscaServiceTemplateJsonAdapter @NonNull final JsonSerializationContext context) { JsonObject serviceTemplateJsonObject = new JsonObject(); - JsonElement topologyTemplateJsonElement = new ToscaTopologyTemplateJsonAdapter() - .serialize(serviceTemplate.getTopologyTemplate(), type, context); - serviceTemplateJsonObject.addProperty(TOSCA_DEFINITIONS_VERSION, serviceTemplate.getToscaDefinitionsVersion()); - serviceTemplateJsonObject.add(TOPOLOGY_TEMPLATE, topologyTemplateJsonElement); + // Serialize tosca_definitions_version + if (serviceTemplate.getToscaDefinitionsVersion() != null) { + serviceTemplateJsonObject.addProperty(TOSCA_DEFINITIONS_VERSION, + serviceTemplate.getToscaDefinitionsVersion()); + } + + // Serialize topoligy_template + if (serviceTemplate.getTopologyTemplate() != null) { + JsonElement topologyTemplateJsonElement = new ToscaTopologyTemplateJsonAdapter() + .serialize(serviceTemplate.getTopologyTemplate(), type, context); + serviceTemplateJsonObject.add(TOPOLOGY_TEMPLATE, topologyTemplateJsonElement); + } + + // Serialize policy_types + if (serviceTemplate.getPolicyTypes() != null) { + JsonElement policyTypesJsonElement = + new ToscaPolicyTypesJsonAdapter().serialize(serviceTemplate.getPolicyTypes(), type, context); + serviceTemplateJsonObject.add(POLICY_TYPES, policyTypesJsonElement); + } + + // Serialize data_types + if (serviceTemplate.getDataTypes() != null) { + JsonElement dataTypesJsonElement = + new ToscaDataTypesJsonAdapter().serialize(serviceTemplate.getDataTypes(), type, context); + serviceTemplateJsonObject.add(DATA_TYPES, dataTypesJsonElement); + } return serviceTemplateJsonObject; } diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaServiceTemplateMessageBodyHandler.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaServiceTemplateMessageBodyHandler.java index cf3e668b3..c7e78a524 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaServiceTemplateMessageBodyHandler.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaServiceTemplateMessageBodyHandler.java @@ -21,8 +21,12 @@ package org.onap.policy.models.tosca.simple.serialization; import com.google.gson.GsonBuilder; import org.onap.policy.common.gson.GsonMessageBodyHandler; +import org.onap.policy.models.tosca.simple.concepts.ToscaDataType; +import org.onap.policy.models.tosca.simple.concepts.ToscaDataTypes; import org.onap.policy.models.tosca.simple.concepts.ToscaPolicies; import org.onap.policy.models.tosca.simple.concepts.ToscaPolicy; +import org.onap.policy.models.tosca.simple.concepts.ToscaPolicyType; +import org.onap.policy.models.tosca.simple.concepts.ToscaPolicyTypes; import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate; import org.onap.policy.models.tosca.simple.concepts.ToscaTopologyTemplate; import org.slf4j.Logger; @@ -56,6 +60,10 @@ public class ToscaServiceTemplateMessageBodyHandler extends GsonMessageBodyHandl .registerTypeAdapter(ToscaTopologyTemplate.class, new ToscaTopologyTemplateJsonAdapter()) .registerTypeAdapter(ToscaPolicies.class, new ToscaPoliciesJsonAdapter()) .registerTypeAdapter(ToscaPolicy.class, new ToscaPolicyJsonAdapter()) + .registerTypeAdapter(ToscaPolicyTypes.class, new ToscaPolicyTypesJsonAdapter()) + .registerTypeAdapter(ToscaPolicyType.class, new ToscaPolicyTypeJsonAdapter()) + .registerTypeAdapter(ToscaDataTypes.class, new ToscaDataTypesJsonAdapter()) + .registerTypeAdapter(ToscaDataType.class, new ToscaDataTypeJsonAdapter()) .setPrettyPrinting() .create() ); diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaTopologyTemplateJsonAdapter.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaTopologyTemplateJsonAdapter.java index a2974fdbd..d302b7e6c 100644 --- a/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaTopologyTemplateJsonAdapter.java +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/simple/serialization/ToscaTopologyTemplateJsonAdapter.java @@ -47,6 +47,7 @@ public class ToscaTopologyTemplateJsonAdapter implements JsonSerializer<ToscaTopologyTemplate>, JsonDeserializer<ToscaTopologyTemplate> { private static final String POLICIES = "policies"; + private static final String DESCRIPTION = "description"; @Override public ToscaTopologyTemplate deserialize(@NonNull final JsonElement toplogyTemplateElement, @@ -59,6 +60,10 @@ public class ToscaTopologyTemplateJsonAdapter final PfReferenceKey topologyTemplateKey = new PfReferenceKey(new PfConceptKey(), "IncomingTopologyTemplate"); final ToscaTopologyTemplate topologyTemplate = new ToscaTopologyTemplate(topologyTemplateKey); + if (topologyTemplateJsonObject.has(DESCRIPTION)) { + topologyTemplate.setDescription(topologyTemplateJsonObject.get(DESCRIPTION).getAsString()); + } + if (topologyTemplateJsonObject.has(POLICIES)) { topologyTemplate.setPolicies(new ToscaPoliciesJsonAdapter() .deserialize(topologyTemplateJsonObject.get(POLICIES), ToscaPolicies.class, context)); @@ -76,6 +81,11 @@ public class ToscaTopologyTemplateJsonAdapter .serialize(topologyTemplate.getPolicies(), type, context); topologyTemplateJsonObject.add(POLICIES, policiesJsonElement); + + if (topologyTemplate.getDescription() != null) { + topologyTemplateJsonObject.addProperty(DESCRIPTION, topologyTemplate.getDescription()); + } + return topologyTemplateJsonObject; } } diff --git a/models-tosca/src/main/java/org/onap/policy/models/tosca/utils/ToscaUtils.java b/models-tosca/src/main/java/org/onap/policy/models/tosca/utils/ToscaUtils.java new file mode 100644 index 000000000..a02bfa4b7 --- /dev/null +++ b/models-tosca/src/main/java/org/onap/policy/models/tosca/utils/ToscaUtils.java @@ -0,0 +1,85 @@ +/*- + * ============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.tosca.utils; + +import javax.ws.rs.core.Response; + +import org.onap.policy.models.base.PfModelRuntimeException; +import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Utility class for TOSCA concepts. + * + * @author Liam Fallon (liam.fallon@est.tech) + */ +public final class ToscaUtils { + private static final Logger LOGGER = LoggerFactory.getLogger(ToscaUtils.class); + + /** + * Private constructor to prevent subclassing. + */ + private ToscaUtils() { + } + + /** + * Check if policy types have been specified is initialized. + */ + public static void assertPolicyTypesExist(final ToscaServiceTemplate serviceTemplate) { + if (serviceTemplate.getPolicyTypes() == null) { + String errorMessage = "no policy types specified on service template"; + LOGGER.warn(errorMessage); + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage); + } + + if (serviceTemplate.getPolicyTypes().getConceptMap().isEmpty()) { + String errorMessage = "list of policy types specified on service template is empty"; + LOGGER.warn(errorMessage); + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage); + } + } + + /** + * Check if policy types have been specified is initialized. + */ + public static void assertPoliciesExist(final ToscaServiceTemplate serviceTemplate) { + if (serviceTemplate.getTopologyTemplate() == null) { + String errorMessage = "topology template not specified on service template"; + LOGGER.warn(errorMessage); + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage); + } + + if (serviceTemplate.getTopologyTemplate().getPolicies() == null) { + String errorMessage = "no policies specified on topology template of service template"; + LOGGER.warn(errorMessage); + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage); + } + + if (serviceTemplate.getTopologyTemplate().getPolicies().getConceptMap().isEmpty()) { + String errorMessage = "list of policies specified on topology template of service template is empty"; + LOGGER.warn(errorMessage); + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage); + } + } + + +} diff --git a/models-base/src/test/java/org/onap/policy/models/base/keys/TestModels.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/TestPojos.java index a1bf3be68..7c813a625 100644 --- a/models-base/src/test/java/org/onap/policy/models/base/keys/TestModels.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/concepts/TestPojos.java @@ -1,7 +1,8 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ONAP Policy Model + * ================================================================================ + * 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. @@ -19,28 +20,33 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.models.base.keys; +package org.onap.policy.models.tosca.authorative.concepts; import com.openpojo.reflection.filters.FilterPackageInfo; import com.openpojo.validation.Validator; import com.openpojo.validation.ValidatorBuilder; +import com.openpojo.validation.rule.impl.GetterMustExistRule; +import com.openpojo.validation.rule.impl.SetterMustExistRule; 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. + * Class to perform unit tests of all pojos. + * + * @author Chenfei Gao (cgao@research.att.com) * - * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ -public class TestModels { +public class TestPojos { + + private static final String POJO_PACKAGE = "org.onap.policy.models.tosca.authorative.concepts"; @Test - public void testModels() { - final Validator validator = ValidatorBuilder.create().with(new ToStringTester()).with(new SetterTester()) + public void testPojos() { + final Validator validator = ValidatorBuilder.create().with(new ToStringTester()) + .with(new SetterMustExistRule()).with(new GetterMustExistRule()).with(new SetterTester()) .with(new GetterTester()).build(); - validator.validate(TestModels.class.getPackage().getName(), new FilterPackageInfo()); + validator.validate(POJO_PACKAGE, new FilterPackageInfo()); } } diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/mapping/PlainToscaServiceTemplateMapperTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/mapping/PlainToscaServiceTemplateMapperTest.java new file mode 100644 index 000000000..e9223b350 --- /dev/null +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/authorative/mapping/PlainToscaServiceTemplateMapperTest.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP Policy Model + * ================================================================================ + * 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.tosca.authorative.mapping; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import com.google.gson.Gson; +import com.google.gson.JsonSyntaxException; +import java.io.IOException; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.models.base.PfValidationResult; +import org.onap.policy.models.tosca.authorative.concepts.PlainToscaServiceTemplate; +import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate; +import org.yaml.snakeyaml.Yaml; + +/** + * This class performs unit test of {@link PlainToscaServiceTemplateMapper}}. + * + * @author Chenfei Gao (cgao@research.att.com) + */ +public class PlainToscaServiceTemplateMapperTest { + + private Gson defaultGson; + private PlainToscaServiceTemplateMapper mapper; + + @Before + public void setUp() { + defaultGson = new Gson(); + mapper = new PlainToscaServiceTemplateMapper(); + } + + @Test + public void testPlainToscaPolicies() throws JsonSyntaxException, IOException { + try { + String inputJson = ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json"); + + PlainToscaServiceTemplate plainPolicies = defaultGson.fromJson(inputJson, PlainToscaServiceTemplate.class); + ToscaServiceTemplate internalPolicies = mapper.toToscaServiceTemplate(plainPolicies); + assertTrue(internalPolicies.validate(new PfValidationResult()).isValid()); + PlainToscaServiceTemplate plainPolicies2 = mapper.fromToscaServiceTemplate(internalPolicies); + assertTrue(plainPolicies.equals(plainPolicies2)); + + } catch (Exception e) { + fail("no exception should be thrown"); + } + } + + @Test + public void testPlainToscaPolicyTypes() throws JsonSyntaxException, IOException { + try { + Yaml yaml = new Yaml(); + String inputYaml = ResourceUtils.getResourceAsString( + "policytypes/onap.policy.monitoring.cdap.tca.hi.lo.app.yaml"); + Object yamlObject = yaml.load(inputYaml); + String yamlAsJsonString = defaultGson.toJson(yamlObject); + + PlainToscaServiceTemplate plainPolicyTypes = defaultGson.fromJson(yamlAsJsonString, + PlainToscaServiceTemplate.class); + ToscaServiceTemplate internalPolicyTypes = mapper.toToscaServiceTemplate(plainPolicyTypes); + assertTrue(internalPolicyTypes.validate(new PfValidationResult()).isValid()); + PlainToscaServiceTemplate plainPolicyTypes2 = mapper.fromToscaServiceTemplate(internalPolicyTypes); + ToscaServiceTemplate internalPolicyTypes2 = mapper.toToscaServiceTemplate(plainPolicyTypes2); + assertTrue(internalPolicyTypes2.validate(new PfValidationResult()).isValid()); + assertTrue(internalPolicyTypes.compareTo(internalPolicyTypes2) == 0); + + } catch (Exception e) { + fail("no exception should be thrown"); + } + + } +} diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/concepts/LegacyGuardPolicyTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/concepts/LegacyGuardPolicyTest.java index d2b2216e7..764ce063f 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/concepts/LegacyGuardPolicyTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/concepts/LegacyGuardPolicyTest.java @@ -23,9 +23,7 @@ package org.onap.policy.models.tosca.legacy.concepts; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import java.util.ArrayList; import java.util.HashMap; -import java.util.List; import java.util.Map; import org.junit.Test; @@ -41,10 +39,8 @@ public class LegacyGuardPolicyTest { assertEquals("guard.frequency", guard.getPolicyId()); guard.setPolicyVersion("1"); assertEquals("1", guard.getPolicyVersion()); - Map<String, String> body = new HashMap<>(); - body.put("actor", "SO"); - List<Map<String, String>> content = new ArrayList<>(); - content.add(body); + Map<String, String> content = new HashMap<>(); + content.put("actor", "SO"); guard.setContent(content); assertEquals(1, guard.getContent().size()); } diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/provider/LegacyProviderTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/provider/LegacyProviderTest.java new file mode 100644 index 000000000..271e019d9 --- /dev/null +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/provider/LegacyProviderTest.java @@ -0,0 +1,317 @@ +/*- + * ============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.tosca.legacy.provider; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +import com.google.gson.Gson; + +import java.sql.Connection; +import java.sql.DriverManager; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.dao.DaoParameters; +import org.onap.policy.models.dao.PfDao; +import org.onap.policy.models.dao.PfDaoFactory; +import org.onap.policy.models.dao.impl.DefaultPfDao; +import org.onap.policy.models.tosca.legacy.concepts.LegacyOperationalPolicy; + +/** + * Test the {@link LegacyProvider} class. + * + * @author Liam Fallon (liam.fallon@est.tech) + */ +public class LegacyProviderTest { + private Connection connection; + private PfDao pfDao; + private Gson gson; + + + /** + * Set up the DAO towards the database. + * + * @throws Exception on database errors + */ + @Before + public void setupDao() throws Exception { + // Use the JDBC UI "jdbc:h2:mem:testdb" to test towards the h2 database + // Use the JDBC UI "jdbc:mariadb://localhost:3306/policy" to test towards a locally installed mariadb instance + connection = DriverManager.getConnection("jdbc:h2:mem:testdb", "policy", "P01icY"); + + final DaoParameters daoParameters = new DaoParameters(); + daoParameters.setPluginClass(DefaultPfDao.class.getCanonicalName()); + + // Use the persistence unit ToscaConceptTest to test towards the h2 database + // Use the persistence unit ToscaConceptMariaDBTest to test towards a locally installed mariadb instance + daoParameters.setPersistenceUnit("ToscaConceptTest"); + + pfDao = new PfDaoFactory().createPfDao(daoParameters); + pfDao.init(daoParameters); + } + + /** + * Set up GSON. + */ + @Before + public void setupGson() { + gson = new Gson(); + } + + @After + public void teardown() throws Exception { + pfDao.close(); + connection.close(); + } + + @Test + public void testPoliciesGet() throws PfModelException { + try { + new LegacyProvider().getOperationalPolicy(null, null); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("dao is marked @NonNull but is null", exc.getMessage()); + } + + try { + new LegacyProvider().getOperationalPolicy(null, ""); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("dao is marked @NonNull but is null", exc.getMessage()); + } + + try { + new LegacyProvider().getOperationalPolicy(pfDao, null); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("policyId is marked @NonNull but is null", exc.getMessage()); + } + + try { + new LegacyProvider().getOperationalPolicy(pfDao, "I Dont Exist"); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("no policy found for policy ID: I Dont Exist", exc.getMessage()); + } + + LegacyOperationalPolicy originalLop = + gson.fromJson(ResourceUtils.getResourceAsString("policies/vCPE.policy.operational.input.json"), + LegacyOperationalPolicy.class); + + assertNotNull(originalLop); + + LegacyOperationalPolicy createdLop = new LegacyProvider().createOperationalPolicy(pfDao, originalLop); + + assertEquals(originalLop, createdLop); + + LegacyOperationalPolicy gotLop = new LegacyProvider().getOperationalPolicy(pfDao, originalLop.getPolicyId()); + + assertEquals(gotLop, originalLop); + + String expectedJsonOutput = ResourceUtils.getResourceAsString("policies/vCPE.policy.operational.output.json"); + String actualJsonOutput = gson.toJson(gotLop); + + assertEquals(actualJsonOutput.replaceAll("\\s+", ""), expectedJsonOutput.replaceAll("\\s+", "")); + + LegacyOperationalPolicy createdLopV2 = new LegacyProvider().createOperationalPolicy(pfDao, originalLop); + LegacyOperationalPolicy gotLopV2 = new LegacyProvider().getOperationalPolicy(pfDao, originalLop.getPolicyId()); + assertEquals(gotLopV2, createdLopV2); + } + + @Test + public void testPolicyCreate() throws PfModelException { + try { + new LegacyProvider().createOperationalPolicy(null, null); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("dao is marked @NonNull but is null", exc.getMessage()); + } + + try { + new LegacyProvider().createOperationalPolicy(null, new LegacyOperationalPolicy()); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("dao is marked @NonNull but is null", exc.getMessage()); + } + + try { + new LegacyProvider().createOperationalPolicy(pfDao, null); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("legacyOperationalPolicy is marked @NonNull but is null", exc.getMessage()); + } + + LegacyOperationalPolicy originalLop = + gson.fromJson(ResourceUtils.getResourceAsString("policies/vCPE.policy.operational.input.json"), + LegacyOperationalPolicy.class); + + assertNotNull(originalLop); + + LegacyOperationalPolicy createdLop = new LegacyProvider().createOperationalPolicy(pfDao, originalLop); + + assertEquals(originalLop, createdLop); + + LegacyOperationalPolicy gotLop = new LegacyProvider().getOperationalPolicy(pfDao, originalLop.getPolicyId()); + + assertEquals(gotLop, originalLop); + + String expectedJsonOutput = ResourceUtils.getResourceAsString("policies/vCPE.policy.operational.output.json"); + String actualJsonOutput = gson.toJson(gotLop); + + assertEquals(actualJsonOutput.replaceAll("\\s+", ""), expectedJsonOutput.replaceAll("\\s+", "")); + } + + + @Test + public void testPolicyUpdate() throws PfModelException { + try { + new LegacyProvider().updateOperationalPolicy(null, null); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("dao is marked @NonNull but is null", exc.getMessage()); + } + + try { + new LegacyProvider().updateOperationalPolicy(null, new LegacyOperationalPolicy()); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("dao is marked @NonNull but is null", exc.getMessage()); + } + + try { + new LegacyProvider().updateOperationalPolicy(pfDao, null); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("legacyOperationalPolicy is marked @NonNull but is null", exc.getMessage()); + } + + try { + new LegacyProvider().updateOperationalPolicy(pfDao, new LegacyOperationalPolicy()); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("no policy found for policy ID: null", exc.getMessage()); + } + + LegacyOperationalPolicy originalLop = + gson.fromJson(ResourceUtils.getResourceAsString("policies/vCPE.policy.operational.input.json"), + LegacyOperationalPolicy.class); + + assertNotNull(originalLop); + + LegacyOperationalPolicy createdLop = new LegacyProvider().createOperationalPolicy(pfDao, originalLop); + assertEquals(originalLop, createdLop); + + LegacyOperationalPolicy gotLop = new LegacyProvider().getOperationalPolicy(pfDao, originalLop.getPolicyId()); + assertEquals(gotLop, originalLop); + + originalLop.setContent("Some New Content"); + LegacyOperationalPolicy updatedLop = new LegacyProvider().updateOperationalPolicy(pfDao, originalLop); + assertEquals(originalLop, updatedLop); + + LegacyOperationalPolicy gotUpdatedLop = + new LegacyProvider().getOperationalPolicy(pfDao, originalLop.getPolicyId()); + assertEquals(gotUpdatedLop, originalLop); + assertEquals("Some New Content", gotUpdatedLop.getContent()); + } + + + @Test + public void testPoliciesDelete() throws PfModelException { + try { + new LegacyProvider().deleteOperationalPolicy(null, null); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("dao is marked @NonNull but is null", exc.getMessage()); + } + + try { + new LegacyProvider().deleteOperationalPolicy(null, ""); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("dao is marked @NonNull but is null", exc.getMessage()); + } + + try { + new LegacyProvider().deleteOperationalPolicy(pfDao, null); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("policyId is marked @NonNull but is null", exc.getMessage()); + } + + + try { + new LegacyProvider().deleteOperationalPolicy(pfDao, "I Dont Exist"); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("no policy found for policy ID: I Dont Exist", exc.getMessage()); + } + + LegacyOperationalPolicy originalLop = + gson.fromJson(ResourceUtils.getResourceAsString("policies/vCPE.policy.operational.input.json"), + LegacyOperationalPolicy.class); + + assertNotNull(originalLop); + + LegacyOperationalPolicy createdLop = new LegacyProvider().createOperationalPolicy(pfDao, originalLop); + assertEquals(originalLop, createdLop); + + LegacyOperationalPolicy gotLop = new LegacyProvider().getOperationalPolicy(pfDao, originalLop.getPolicyId()); + + assertEquals(gotLop, originalLop); + + String expectedJsonOutput = ResourceUtils.getResourceAsString("policies/vCPE.policy.operational.output.json"); + String actualJsonOutput = gson.toJson(gotLop); + + assertEquals(actualJsonOutput.replaceAll("\\s+", ""), expectedJsonOutput.replaceAll("\\s+", "")); + + LegacyOperationalPolicy deletedLop = + new LegacyProvider().deleteOperationalPolicy(pfDao, originalLop.getPolicyId()); + assertEquals(deletedLop, originalLop); + + try { + new LegacyProvider().getOperationalPolicy(pfDao, originalLop.getPolicyId()); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("no policy found for policy ID: operational.restart", exc.getMessage()); + } + + LegacyOperationalPolicy otherLop = new LegacyOperationalPolicy(); + otherLop.setPolicyId("another-policy"); + otherLop.setPolicyVersion("1"); + otherLop.setContent("content"); + + LegacyOperationalPolicy createdOtherLop = new LegacyProvider().createOperationalPolicy(pfDao, otherLop); + assertEquals(otherLop, createdOtherLop); + + try { + new LegacyProvider().getOperationalPolicy(pfDao, originalLop.getPolicyId()); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("no policy found for policy ID: operational.restart", exc.getMessage()); + } + + } +} diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/serialization/LegacyOperationalPolicySerializationTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/serialization/LegacyOperationalPolicySerializationTest.java index 3c9deb7df..5d1fa42ad 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/serialization/LegacyOperationalPolicySerializationTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/legacy/serialization/LegacyOperationalPolicySerializationTest.java @@ -68,7 +68,7 @@ public class LegacyOperationalPolicySerializationTest { LOGGER.info(serviceTemplate.validate(new PfValidationResult()).toString()); assertTrue(serviceTemplate.validate(new PfValidationResult()).isValid()); - assertEquals("operational.restart:1.0.1", + assertEquals("operational.restart:1.0.0", serviceTemplate.getTopologyTemplate().getPolicies().get("operational.restart").getId()); } } diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/ToscaPolicyTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/ToscaPolicyTest.java index 807f33ed2..01c1377b9 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/ToscaPolicyTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/ToscaPolicyTest.java @@ -37,7 +37,7 @@ import org.onap.policy.models.base.PfValidationResult; import org.onap.policy.models.tosca.simple.concepts.ToscaPolicy; /** - * DAO test for ToscaDatatype. + * DAO test for ToscaPolicy. * * @author Liam Fallon (liam.fallon@est.tech) */ @@ -171,4 +171,4 @@ public class ToscaPolicyTest { assertEquals("resultIn is marked @NonNull but is null", exc.getMessage()); } } -} +}
\ No newline at end of file diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/ToscaPropertyTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/ToscaPropertyTest.java index a33da605e..0fcf96a89 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/ToscaPropertyTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/ToscaPropertyTest.java @@ -99,8 +99,7 @@ public class ToscaPropertyTest { tp.setRequired(false); assertFalse(tp.isRequired()); - PfConceptKey tdefaultKey = new PfConceptKey("defaultKey", "0.0.1"); - tp.setDefaultValue(tdefaultKey); + tp.setDefaultValue("defaultKey"); tp.setStatus(ToscaProperty.Status.SUPPORTED); @@ -141,7 +140,7 @@ public class ToscaPropertyTest { assertFalse(tp.compareTo(otherDt) == 0); otherDt.setRequired(false); assertFalse(tp.compareTo(otherDt) == 0); - otherDt.setDefaultValue(tdefaultKey); + otherDt.setDefaultValue("defaultKey"); assertFalse(tp.compareTo(otherDt) == 0); otherDt.setStatus(ToscaProperty.Status.SUPPORTED); assertFalse(tp.compareTo(otherDt) == 0); @@ -168,7 +167,7 @@ public class ToscaPropertyTest { assertEquals("target is marked @NonNull but is null", exc.getMessage()); } - assertEquals(6, tp.getKeys().size()); + assertEquals(5, tp.getKeys().size()); assertEquals(2, new ToscaProperty().getKeys().size()); new ToscaProperty().clean(); @@ -197,12 +196,7 @@ public class ToscaPropertyTest { tp.setDefaultValue(null); assertTrue(tp.validate(new PfValidationResult()).isValid()); - tp.setDefaultValue(tdefaultKey); - assertTrue(tp.validate(new PfValidationResult()).isValid()); - - tp.setDefaultValue(PfConceptKey.getNullKey()); - assertFalse(tp.validate(new PfValidationResult()).isValid()); - tp.setDefaultValue(tdefaultKey); + tp.setDefaultValue("defaultKey"); assertTrue(tp.validate(new PfValidationResult()).isValid()); tp.getConstraints().add(null); diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/ToscaTopologyTemplateTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/ToscaTopologyTemplateTest.java index 3ea225d19..d35c3d661 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/ToscaTopologyTemplateTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/concepts/ToscaTopologyTemplateTest.java @@ -118,7 +118,7 @@ public class ToscaTopologyTemplateTest { ttt.clean(); assertEquals(tttClone0, ttt); - assertFalse(new ToscaTopologyTemplate().validate(new PfValidationResult()).isValid()); + assertTrue(new ToscaTopologyTemplate().validate(new PfValidationResult()).isValid()); assertTrue(ttt.validate(new PfValidationResult()).isValid()); ttt.setDescription(null); diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProviderTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProviderTest.java new file mode 100644 index 000000000..ed25a7a25 --- /dev/null +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/provider/SimpleToscaProviderTest.java @@ -0,0 +1,283 @@ +/*- + * ============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.tosca.simple.provider; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +import com.google.gson.Gson; + +import java.sql.Connection; +import java.sql.DriverManager; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.dao.DaoParameters; +import org.onap.policy.models.dao.PfDao; +import org.onap.policy.models.dao.PfDaoFactory; +import org.onap.policy.models.dao.impl.DefaultPfDao; +import org.onap.policy.models.tosca.simple.concepts.ToscaPolicies; +import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate; +import org.onap.policy.models.tosca.simple.concepts.ToscaTopologyTemplate; +import org.onap.policy.models.tosca.simple.serialization.ToscaServiceTemplateMessageBodyHandler; + +/** + * Test the {@link SimpleToscaProvider} class. + * + * @author Liam Fallon (liam.fallon@est.tech) + */ +public class SimpleToscaProviderTest { + private Connection connection; + private PfDao pfDao; + private Gson gson; + + + /** + * Set up the DAO towards the database. + * + * @throws Exception on database errors + */ + @Before + public void setupDao() throws Exception { + // Use the JDBC UI "jdbc:h2:mem:testdb" to test towards the h2 database + // Use the JDBC UI "jdbc:mariadb://localhost:3306/policy" to test towards a locally installed mariadb instance + connection = DriverManager.getConnection("jdbc:h2:mem:testdb", "policy", "P01icY"); + + final DaoParameters daoParameters = new DaoParameters(); + daoParameters.setPluginClass(DefaultPfDao.class.getCanonicalName()); + + // Use the persistence unit ToscaConceptTest to test towards the h2 database + // Use the persistence unit ToscaConceptMariaDBTest to test towards a locally installed mariadb instance + daoParameters.setPersistenceUnit("ToscaConceptTest"); + + pfDao = new PfDaoFactory().createPfDao(daoParameters); + pfDao.init(daoParameters); + } + + /** + * Set up GSON. + */ + @Before + public void setupGson() { + gson = new ToscaServiceTemplateMessageBodyHandler().getGson(); + } + + @After + public void teardown() throws Exception { + pfDao.close(); + connection.close(); + } + + @Test + public void testPoliciesGet() throws PfModelException { + try { + new SimpleToscaProvider().getPolicies(null, null); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("dao is marked @NonNull but is null", exc.getMessage()); + } + + try { + new SimpleToscaProvider().getPolicies(null, new PfConceptKey()); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("dao is marked @NonNull but is null", exc.getMessage()); + } + + try { + new SimpleToscaProvider().getPolicies(pfDao, null); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("policyKey is marked @NonNull but is null", exc.getMessage()); + } + + ToscaServiceTemplate originalServiceTemplate = + gson.fromJson(ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json"), + ToscaServiceTemplate.class); + + assertNotNull(originalServiceTemplate); + ToscaServiceTemplate createdServiceTemplate = + new SimpleToscaProvider().createPolicies(pfDao, originalServiceTemplate); + + assertEquals(originalServiceTemplate, createdServiceTemplate); + + PfConceptKey policyKey = new PfConceptKey("onap.restart.tca:1.0.0"); + + ToscaServiceTemplate gotServiceTemplate = + new SimpleToscaProvider().getPolicies(pfDao, new PfConceptKey(policyKey)); + + assertEquals(originalServiceTemplate.getTopologyTemplate().getPolicies().get(policyKey), + gotServiceTemplate.getTopologyTemplate().getPolicies().get(policyKey)); + + } + + @Test + public void testPolicyCreate() throws PfModelException { + try { + new SimpleToscaProvider().createPolicies(null, null); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("dao is marked @NonNull but is null", exc.getMessage()); + } + + try { + new SimpleToscaProvider().createPolicies(null, new ToscaServiceTemplate()); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("dao is marked @NonNull but is null", exc.getMessage()); + } + + try { + new SimpleToscaProvider().createPolicies(pfDao, null); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("serviceTemplate is marked @NonNull but is null", exc.getMessage()); + } + + ToscaServiceTemplate originalServiceTemplate = + gson.fromJson(ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json"), + ToscaServiceTemplate.class); + + assertNotNull(originalServiceTemplate); + ToscaServiceTemplate createdServiceTemplate = + new SimpleToscaProvider().createPolicies(pfDao, originalServiceTemplate); + + assertEquals(originalServiceTemplate, createdServiceTemplate); + } + + @Test + public void testPolicyUpdate() throws PfModelException { + try { + new SimpleToscaProvider().updatePolicies(null, null); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("dao is marked @NonNull but is null", exc.getMessage()); + } + + try { + new SimpleToscaProvider().updatePolicies(null, new ToscaServiceTemplate()); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("dao is marked @NonNull but is null", exc.getMessage()); + } + + try { + new SimpleToscaProvider().updatePolicies(pfDao, null); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("serviceTemplate is marked @NonNull but is null", exc.getMessage()); + } + + ToscaServiceTemplate originalServiceTemplate = + gson.fromJson(ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json"), + ToscaServiceTemplate.class); + + assertNotNull(originalServiceTemplate); + ToscaServiceTemplate updatedServiceTemplate = + new SimpleToscaProvider().updatePolicies(pfDao, originalServiceTemplate); + + assertEquals(originalServiceTemplate, updatedServiceTemplate); + } + + @Test + public void testPoliciesDelete() throws PfModelException { + try { + new SimpleToscaProvider().deletePolicies(null, null); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("dao is marked @NonNull but is null", exc.getMessage()); + } + + try { + new SimpleToscaProvider().deletePolicies(null, new PfConceptKey()); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("dao is marked @NonNull but is null", exc.getMessage()); + } + + try { + new SimpleToscaProvider().deletePolicies(pfDao, null); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("policyKey is marked @NonNull but is null", exc.getMessage()); + } + + ToscaServiceTemplate originalServiceTemplate = + gson.fromJson(ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json"), + ToscaServiceTemplate.class); + + assertNotNull(originalServiceTemplate); + ToscaServiceTemplate createdServiceTemplate = + new SimpleToscaProvider().createPolicies(pfDao, originalServiceTemplate); + + assertEquals(originalServiceTemplate, createdServiceTemplate); + + PfConceptKey policyKey = new PfConceptKey("onap.restart.tca:1.0.0"); + + ToscaServiceTemplate deletedServiceTemplate = + new SimpleToscaProvider().deletePolicies(pfDao, new PfConceptKey(policyKey)); + + assertEquals(originalServiceTemplate.getTopologyTemplate().getPolicies().get(policyKey), + deletedServiceTemplate.getTopologyTemplate().getPolicies().get(policyKey)); + + try { + new SimpleToscaProvider().getPolicies(pfDao, new PfConceptKey(policyKey)); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("policy not found: onap.restart.tca:1.0.0", exc.getMessage()); + } + } + + @Test + public void testAssertPoliciesExist() throws PfModelException { + ToscaServiceTemplate testServiceTemplate = new ToscaServiceTemplate(); + + try { + new SimpleToscaProvider().createPolicies(pfDao, testServiceTemplate); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("topology template not specified on service template", exc.getMessage()); + } + + testServiceTemplate.setTopologyTemplate(new ToscaTopologyTemplate()); + try { + new SimpleToscaProvider().createPolicies(pfDao, testServiceTemplate); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("no policies specified on topology template of service template", exc.getMessage()); + } + + testServiceTemplate.getTopologyTemplate().setPolicies(new ToscaPolicies()); + try { + new SimpleToscaProvider().createPolicies(pfDao, testServiceTemplate); + fail("test should throw an exception here"); + } catch (Exception exc) { + assertEquals("list of policies specified on topology template of service template is empty", + exc.getMessage()); + } + + } +} diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/MonitoringPolicySerializationTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/MonitoringPolicySerializationTest.java index 95f0ac971..505e90e28 100644 --- a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/MonitoringPolicySerializationTest.java +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/MonitoringPolicySerializationTest.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. + * 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. @@ -23,17 +24,22 @@ package org.onap.policy.models.tosca.simple.serialization; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; import java.io.IOException; - +import java.util.Map; import org.junit.Before; import org.junit.Test; import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.models.base.PfConceptKey; import org.onap.policy.models.base.PfValidationResult; +import org.onap.policy.models.tosca.simple.concepts.ToscaPolicy; import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate; import org.onap.policy.models.tosca.simple.serialization.ToscaServiceTemplateMessageBodyHandler; import org.slf4j.Logger; @@ -44,11 +50,19 @@ import org.yaml.snakeyaml.Yaml; * Test serialization of monitoring policies. * * @author Liam Fallon (liam.fallon@est.tech) + * @author Chenfei Gao (cgao@research.att.com) */ public class MonitoringPolicySerializationTest { - // Logger for this class + private static final Logger LOGGER = LoggerFactory.getLogger(MonitoringPolicySerializationTest.class); + private static final String VCPE_MONITORING_INPUT_JSON = "policies/vCPE.policy.monitoring.input.tosca.json"; + private static final String VCPE_MONITORING_INPUT_YAML = "policies/vCPE.policy.monitoring.input.tosca.yaml"; + private static final String VDNS_MONITORING_INPUT_JSON = "policies/vDNS.policy.monitoring.input.tosca.json"; + private static final String VDNS_MONITORING_INPUT_YAML = "policies/vDNS.policy.monitoring.input.tosca.yaml"; + private static final String VFW_MONITORING_INPUT_JSON = "policies/vFirewall.policy.monitoring.input.tosca.json"; + private static final String VFW_MONITORING_INPUT_YAML = "policies/vFirewall.policy.monitoring.input.tosca.yaml"; + private Gson gson; @Before @@ -57,48 +71,232 @@ public class MonitoringPolicySerializationTest { } @Test - public void testJsonDeserialization() throws JsonSyntaxException, IOException { - String vcpePolicyJson = ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.json"); + public void testDeserialization() { + try { + // vCPE + ToscaServiceTemplate serviceTemplateFromJson = deserializeMonitoringInputJson(VCPE_MONITORING_INPUT_JSON); + verifyVcpeMonitoringInputDeserialization(serviceTemplateFromJson); + ToscaServiceTemplate serviceTemplateFromYaml = deserializeMonitoringInputYaml(VCPE_MONITORING_INPUT_YAML); + assertTrue(serviceTemplateFromJson.compareTo(serviceTemplateFromYaml) == 0); + + // vDNS + serviceTemplateFromJson = deserializeMonitoringInputJson(VDNS_MONITORING_INPUT_JSON); + verifyVdnsMonitoringInputDeserialization(serviceTemplateFromJson); + serviceTemplateFromYaml = deserializeMonitoringInputYaml(VDNS_MONITORING_INPUT_YAML); + assertTrue(serviceTemplateFromJson.compareTo(serviceTemplateFromYaml) == 0); + + // vFirewall + serviceTemplateFromJson = deserializeMonitoringInputJson(VFW_MONITORING_INPUT_JSON); + verifyVfwMonitoringInputDeserialization(serviceTemplateFromJson); + serviceTemplateFromYaml = deserializeMonitoringInputYaml(VFW_MONITORING_INPUT_YAML); + assertTrue(serviceTemplateFromJson.compareTo(serviceTemplateFromYaml) == 0); + + } catch (Exception e) { + fail("No exception should be thrown"); + } + } + + @Test + public void testSerialization() { + try { + // vCPE + ToscaServiceTemplate serviceTemplate = deserializeMonitoringInputJson(VCPE_MONITORING_INPUT_JSON); + String serializedServiceTemplate = serializeMonitoringServiceTemplate(serviceTemplate); + verifyVcpeMonitoringOutputserialization(serializedServiceTemplate); + + // vDNS + serviceTemplate = deserializeMonitoringInputJson(VDNS_MONITORING_INPUT_JSON); + serializedServiceTemplate = serializeMonitoringServiceTemplate(serviceTemplate); + verifyVdnsMonitoringOutputserialization(serializedServiceTemplate); + + // vFirewall + serviceTemplate = deserializeMonitoringInputJson(VFW_MONITORING_INPUT_JSON); + serializedServiceTemplate = serializeMonitoringServiceTemplate(serviceTemplate); + verifyVfwMonitoringOutputserialization(serializedServiceTemplate); + + } catch (Exception e) { + LOGGER.warn("No exception should be thrown", e); + fail("No exception should be thrown"); + } + } + + private ToscaServiceTemplate deserializeMonitoringInputJson(String resourcePath) + throws JsonSyntaxException, IOException { - ToscaServiceTemplate serviceTemplate = gson.fromJson(vcpePolicyJson, ToscaServiceTemplate.class); + String policyJson = ResourceUtils.getResourceAsString(resourcePath); + ToscaServiceTemplate serviceTemplate = gson.fromJson(policyJson, ToscaServiceTemplate.class); + return serviceTemplate; + } + + private ToscaServiceTemplate deserializeMonitoringInputYaml(String resourcePath) + throws JsonSyntaxException, IOException { + + Yaml yaml = new Yaml(); + String policyYaml = ResourceUtils.getResourceAsString(resourcePath); + Object yamlObject = yaml.load(policyYaml); + String yamlAsJsonString = new Gson().toJson(yamlObject); + ToscaServiceTemplate serviceTemplate = gson.fromJson(yamlAsJsonString, ToscaServiceTemplate.class); + return serviceTemplate; + } + + private String serializeMonitoringServiceTemplate(ToscaServiceTemplate serviceTemplate) { + return gson.toJson(serviceTemplate); + } + + private void verifyVcpeMonitoringInputDeserialization(ToscaServiceTemplate serviceTemplate) { + + // Sanity check the entire structure assertNotNull(serviceTemplate); LOGGER.info(serviceTemplate.validate(new PfValidationResult()).toString()); assertTrue(serviceTemplate.validate(new PfValidationResult()).isValid()); + // Check tosca_definitions_version + assertEquals("tosca_simple_yaml_1_0_0", + serviceTemplate.getToscaDefinitionsVersion()); + + Map<PfConceptKey, ToscaPolicy> policiesConceptMap = serviceTemplate.getTopologyTemplate() + .getPolicies().getConceptMap(); + + // Check policies + assertTrue(policiesConceptMap.size() == 1); + assertEquals("onap.restart.tca", policiesConceptMap.keySet().iterator().next().getName()); assertEquals("onap.restart.tca:1.0.0", serviceTemplate.getTopologyTemplate().getPolicies().get("onap.restart.tca").getId()); - String reserializedString = gson.toJson(serviceTemplate, ToscaServiceTemplate.class); - assertEquals(vcpePolicyJson.replaceAll("\\s+", ""), reserializedString.replaceAll("\\s+", "")); + ToscaPolicy policyVal = policiesConceptMap.values().iterator().next(); + + // Check metadata + assertTrue(policyVal.getMetadata().size() == 1); + assertEquals("policy-id", policyVal.getMetadata().entrySet().iterator().next().getKey()); + assertEquals("onap.restart.tca", policyVal.getMetadata().entrySet().iterator().next().getValue()); - ToscaServiceTemplate serviceTemplate2 = gson.fromJson(reserializedString, ToscaServiceTemplate.class); - assertNotNull(serviceTemplate2); - assertEquals(serviceTemplate, serviceTemplate2); + // Check properties + assertTrue(policiesConceptMap.values().iterator().next().getProperties().size() == 1); + assertEquals("tca_policy", policyVal.getProperties().keySet().iterator().next()); + assertNotNull(policyVal.getProperties().values().iterator().next()); } - @Test - public void testYamlDeserialization() throws JsonSyntaxException, IOException { - Yaml yaml = new Yaml(); + private void verifyVdnsMonitoringInputDeserialization(ToscaServiceTemplate serviceTemplate) { - String vcpePolicyYaml = ResourceUtils.getResourceAsString("policies/vCPE.policy.monitoring.input.tosca.yaml"); - Object yamlObject = yaml.load(vcpePolicyYaml); + // Sanity check the entire structure + assertNotNull(serviceTemplate); + LOGGER.info(serviceTemplate.validate(new PfValidationResult()).toString()); + assertTrue(serviceTemplate.validate(new PfValidationResult()).isValid()); - String yamlAsJsonString = new GsonBuilder().setPrettyPrinting().create().toJson(yamlObject); + // Check tosca_definitions_version + assertEquals("tosca_simple_yaml_1_0_0", + serviceTemplate.getToscaDefinitionsVersion()); - ToscaServiceTemplate serviceTemplate = gson.fromJson(yamlAsJsonString, ToscaServiceTemplate.class); + Map<PfConceptKey, ToscaPolicy> policiesConceptMap = serviceTemplate.getTopologyTemplate() + .getPolicies().getConceptMap(); + + // Check policies + assertTrue(policiesConceptMap.size() == 1); + assertEquals("onap.scaleout.tca", policiesConceptMap.keySet().iterator().next().getName()); + assertEquals("onap.scaleout.tca:1.0.0", + serviceTemplate.getTopologyTemplate().getPolicies().get("onap.scaleout.tca").getId()); + ToscaPolicy policyVal = policiesConceptMap.values().iterator().next(); + + // Check metadata + assertTrue(policyVal.getMetadata().size() == 1); + assertEquals("policy-id", policyVal.getMetadata().entrySet().iterator().next().getKey()); + assertEquals("onap.scaleout.tca", policyVal.getMetadata().entrySet().iterator().next().getValue()); + + // Check properties + assertTrue(policiesConceptMap.values().iterator().next().getProperties().size() == 1); + assertEquals("tca_policy", policyVal.getProperties().keySet().iterator().next()); + assertNotNull(policyVal.getProperties().values().iterator().next()); + } + + private void verifyVfwMonitoringInputDeserialization(ToscaServiceTemplate serviceTemplate) { + + // Sanity check the entire structure assertNotNull(serviceTemplate); LOGGER.info(serviceTemplate.validate(new PfValidationResult()).toString()); assertTrue(serviceTemplate.validate(new PfValidationResult()).isValid()); - assertEquals("onap.restart.tca:1.0.0", - serviceTemplate.getTopologyTemplate().getPolicies().get("onap.restart.tca").getId()); + // Check tosca_definitions_version + assertEquals("tosca_simple_yaml_1_0_0", + serviceTemplate.getToscaDefinitionsVersion()); + + Map<PfConceptKey, ToscaPolicy> policiesConceptMap = serviceTemplate.getTopologyTemplate() + .getPolicies().getConceptMap(); + + // Check policies + assertTrue(policiesConceptMap.size() == 1); + assertEquals("onap.vfirewall.tca", policiesConceptMap.keySet().iterator().next().getName()); + assertEquals("onap.vfirewall.tca:1.0.0", + serviceTemplate.getTopologyTemplate().getPolicies().get("onap.vfirewall.tca").getId()); + + ToscaPolicy policyVal = policiesConceptMap.values().iterator().next(); + + // Check metadata + assertTrue(policyVal.getMetadata().size() == 1); + assertEquals("policy-id", policyVal.getMetadata().entrySet().iterator().next().getKey()); + assertEquals("onap.vfirewall.tca", policyVal.getMetadata().entrySet().iterator().next().getValue()); + + // Check properties + assertTrue(policiesConceptMap.values().iterator().next().getProperties().size() == 1); + assertEquals("tca_policy", policyVal.getProperties().keySet().iterator().next()); + assertNotNull(policyVal.getProperties().values().iterator().next()); + } + + private void verifyVcpeMonitoringOutputserialization(String serializedServiceTemplate) { + + JsonObject serviceTemplateJsonObject = new JsonParser().parse(serializedServiceTemplate).getAsJsonObject(); + assertEquals("tosca_simple_yaml_1_0_0", serviceTemplateJsonObject.get("tosca_definitions_version") + .getAsString()); + JsonObject topologyTemplateJsonObject = serviceTemplateJsonObject.get("topology_template") + .getAsJsonObject(); + JsonArray policiesJsonArray = topologyTemplateJsonObject.get("policies").getAsJsonArray(); + assertTrue(policiesJsonArray.size() == 1); + JsonObject policy = policiesJsonArray.iterator().next().getAsJsonObject(); + assertNotNull(policy.get("onap.restart.tca")); + JsonObject policyVal = policy.get("onap.restart.tca").getAsJsonObject(); + assertEquals("onap.policies.monitoring.cdap.tca.hi.lo.app", policyVal.get("type").getAsString()); + assertEquals("1.0.0", policyVal.get("version").getAsString()); + assertEquals("onap.restart.tca", policyVal.get("metadata").getAsJsonObject().get("policy-id") + .getAsString()); + JsonObject properties = policyVal.get("properties").getAsJsonObject(); + assertNotNull(properties.get("tca_policy")); + } + + private void verifyVdnsMonitoringOutputserialization(String serializedServiceTemplate) { + + JsonObject serviceTemplateJsonObject = new JsonParser().parse(serializedServiceTemplate).getAsJsonObject(); + assertEquals("tosca_simple_yaml_1_0_0", serviceTemplateJsonObject.get("tosca_definitions_version") + .getAsString()); + JsonObject topologyTemplateJsonObject = serviceTemplateJsonObject.get("topology_template").getAsJsonObject(); + JsonArray policiesJsonArray = topologyTemplateJsonObject.get("policies").getAsJsonArray(); + assertTrue(policiesJsonArray.size() == 1); + JsonObject policy = policiesJsonArray.iterator().next().getAsJsonObject(); + assertNotNull(policy.get("onap.scaleout.tca")); + JsonObject policyVal = policy.get("onap.scaleout.tca").getAsJsonObject(); + assertEquals("onap.policies.monitoring.cdap.tca.hi.lo.app", policyVal.get("type").getAsString()); + assertEquals("1.0.0", policyVal.get("version").getAsString()); + assertEquals("onap.scaleout.tca", policyVal.get("metadata").getAsJsonObject().get("policy-id") + .getAsString()); + JsonObject properties = policyVal.get("properties").getAsJsonObject(); + assertNotNull(properties.get("tca_policy")); + } - String reserializedString = gson.toJson(serviceTemplate, ToscaServiceTemplate.class); - assertEquals(yamlAsJsonString.replaceAll("\\s+", ""), reserializedString.replaceAll("\\s+", "")); + private void verifyVfwMonitoringOutputserialization(String serializedServiceTemplate) { - ToscaServiceTemplate serviceTemplate2 = gson.fromJson(reserializedString, ToscaServiceTemplate.class); - assertNotNull(serviceTemplate2); - assertEquals(serviceTemplate, serviceTemplate2); + JsonObject serviceTemplateJsonObject = new JsonParser().parse(serializedServiceTemplate).getAsJsonObject(); + assertEquals("tosca_simple_yaml_1_0_0", serviceTemplateJsonObject.get("tosca_definitions_version") + .getAsString()); + JsonObject topologyTemplateJsonObject = serviceTemplateJsonObject.get("topology_template").getAsJsonObject(); + JsonArray policiesJsonArray = topologyTemplateJsonObject.get("policies").getAsJsonArray(); + assertTrue(policiesJsonArray.size() == 1); + JsonObject policy = policiesJsonArray.iterator().next().getAsJsonObject(); + assertNotNull(policy.get("onap.vfirewall.tca")); + JsonObject policyVal = policy.get("onap.vfirewall.tca").getAsJsonObject(); + assertEquals("onap.policy.monitoring.cdap.tca.hi.lo.app", policyVal.get("type").getAsString()); + assertEquals("1.0.0", policyVal.get("version").getAsString()); + assertEquals("onap.vfirewall.tca", policyVal.get("metadata").getAsJsonObject().get("policy-id") + .getAsString()); + JsonObject properties = policyVal.get("properties").getAsJsonObject(); + assertNotNull(properties.get("tca_policy")); } } diff --git a/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/MonitoringPolicyTypeSerializationTest.java b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/MonitoringPolicyTypeSerializationTest.java new file mode 100644 index 000000000..c40b32e3c --- /dev/null +++ b/models-tosca/src/test/java/org/onap/policy/models/tosca/simple/serialization/MonitoringPolicyTypeSerializationTest.java @@ -0,0 +1,424 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation. + * 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.tosca.simple.serialization; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import com.google.gson.Gson; +import com.google.gson.JsonSyntaxException; + +import java.io.IOException; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.models.base.PfConceptKey; +import org.onap.policy.models.base.PfValidationResult; +import org.onap.policy.models.tosca.simple.concepts.ToscaConstraintLogicalString; +import org.onap.policy.models.tosca.simple.concepts.ToscaConstraintValidValues; +import org.onap.policy.models.tosca.simple.concepts.ToscaDataType; +import org.onap.policy.models.tosca.simple.concepts.ToscaEntrySchema; +import org.onap.policy.models.tosca.simple.concepts.ToscaPolicyType; +import org.onap.policy.models.tosca.simple.concepts.ToscaProperty; +import org.onap.policy.models.tosca.simple.concepts.ToscaServiceTemplate; +import org.onap.policy.models.tosca.simple.serialization.ToscaServiceTemplateMessageBodyHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.yaml.snakeyaml.Yaml; + +/** + * Test serialization of monitoring policy types. + * + * @author Chenfei Gao (cgao@research.att.com) + */ +public class MonitoringPolicyTypeSerializationTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(MonitoringPolicyTypeSerializationTest.class); + + private static final String MONITORING_TCA_YAML = "policytypes/onap.policy.monitoring.cdap.tca.hi.lo.app.yaml"; + private static final String MONITORING_COLLECTORS_YAML = + "policytypes/onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server.yaml"; + + private Gson gson; + + @Before + public void setUp() { + gson = new ToscaServiceTemplateMessageBodyHandler().getGson(); + } + + @Test + public void testDeserialization() { + try { + // TCA + ToscaServiceTemplate serviceTemplateFromYaml = deserializeMonitoringInputYaml(MONITORING_TCA_YAML); + verifyTcaInputDeserialization(serviceTemplateFromYaml); + + // Collector + serviceTemplateFromYaml = deserializeMonitoringInputYaml(MONITORING_COLLECTORS_YAML); + verifyCollectorInputDeserialization(serviceTemplateFromYaml); + + } catch (Exception e) { + fail("No exception should be thrown"); + } + } + + @Test + public void testSerialization() { + try { + // TCA + ToscaServiceTemplate serviceTemplateFromYaml = deserializeMonitoringInputYaml(MONITORING_TCA_YAML); + String serializedServiceTemplate1 = serializeMonitoringServiceTemplate(serviceTemplateFromYaml); + ToscaServiceTemplate serviceTemplateFromJson = gson.fromJson(serializedServiceTemplate1, + ToscaServiceTemplate.class); + String serializedServiceTemplate2 = serializeMonitoringServiceTemplate(serviceTemplateFromJson); + assertEquals(serializedServiceTemplate1, serializedServiceTemplate2); + + // Collector + serviceTemplateFromYaml = deserializeMonitoringInputYaml(MONITORING_COLLECTORS_YAML); + serializedServiceTemplate1 = serializeMonitoringServiceTemplate(serviceTemplateFromYaml); + serviceTemplateFromJson = gson.fromJson(serializedServiceTemplate1, ToscaServiceTemplate.class); + serializedServiceTemplate2 = serializeMonitoringServiceTemplate(serviceTemplateFromJson); + assertEquals(serializedServiceTemplate1, serializedServiceTemplate2); + + } catch (Exception e) { + fail("No exception should be thrown"); + } + } + + private ToscaServiceTemplate deserializeMonitoringInputYaml(String resourcePath) + throws JsonSyntaxException, IOException { + + Yaml yaml = new Yaml(); + String policyTypeYaml = ResourceUtils.getResourceAsString(resourcePath); + Object yamlObject = yaml.load(policyTypeYaml); + String yamlAsJsonString = new Gson().toJson(yamlObject); + ToscaServiceTemplate serviceTemplate = gson.fromJson(yamlAsJsonString, ToscaServiceTemplate.class); + return serviceTemplate; + } + + private void verifyTcaInputDeserialization(ToscaServiceTemplate serviceTemplate) { + + // Sanity check the entire structure + assertNotNull(serviceTemplate); + LOGGER.info(serviceTemplate.validate(new PfValidationResult()).toString()); + assertTrue(serviceTemplate.validate(new PfValidationResult()).isValid()); + + // Check tosca_definitions_version + assertEquals("tosca_simple_yaml_1_0_0", serviceTemplate.getToscaDefinitionsVersion()); + + // Check policy_types + Map<PfConceptKey, ToscaPolicyType> policyTypesConceptMap = serviceTemplate.getPolicyTypes().getConceptMap(); + assertTrue(policyTypesConceptMap.size() == 2); + Iterator<Entry<PfConceptKey, ToscaPolicyType>> policyTypesIter = policyTypesConceptMap.entrySet().iterator(); + + Entry<PfConceptKey, ToscaPolicyType> firstPolicyType = policyTypesIter.next(); + assertEquals("onap.policies.Monitoring", firstPolicyType.getKey().getName()); + assertEquals("1.0.0", firstPolicyType.getKey().getVersion()); + assertEquals("tosca.policies.Root", firstPolicyType.getValue().getDerivedFrom().getName()); + assertEquals("a base policy type for all policies that governs monitoring provisioning", + firstPolicyType.getValue().getDescription()); + + Entry<PfConceptKey, ToscaPolicyType> secondPolicyType = policyTypesIter.next(); + assertEquals("onap.policy.monitoring.cdap.tca.hi.lo.app", secondPolicyType.getKey().getName()); + assertEquals("1.0.0", secondPolicyType.getKey().getVersion()); + assertEquals("onap.policies.Monitoring", secondPolicyType.getValue().getDerivedFrom().getName()); + assertTrue(secondPolicyType.getValue().getProperties().size() == 1); + + ToscaProperty property = secondPolicyType.getValue().getProperties().iterator().next(); + assertEquals("onap.policy.monitoring.cdap.tca.hi.lo.app", property.getKey().getParentKeyName()); + assertEquals("1.0.0", property.getKey().getParentKeyVersion()); + assertEquals("tca_policy", property.getKey().getLocalName()); + assertEquals("map", property.getType().getName()); + assertEquals("TCA Policy JSON", property.getDescription()); + + ToscaEntrySchema entrySchema = property.getEntrySchema(); + assertEquals("map", entrySchema.getKey().getParentKeyName()); + assertEquals("1.0.0", entrySchema.getKey().getParentKeyVersion()); + assertEquals("entry_schema", entrySchema.getKey().getLocalName()); + assertEquals("onap.datatypes.monitoring.tca_policy", entrySchema.getType().getName()); + + // Check data_types + Map<PfConceptKey, ToscaDataType> dataTypesConceptMap = serviceTemplate.getDataTypes().getConceptMap(); + assertTrue(dataTypesConceptMap.size() == 3); + Iterator<Entry<PfConceptKey, ToscaDataType>> dataTypesIter = dataTypesConceptMap.entrySet().iterator(); + + Entry<PfConceptKey, ToscaDataType> firstDataType = dataTypesIter.next(); + assertEquals("onap.datatypes.monitoring.metricsPerEventName", firstDataType.getKey().getName()); + ToscaDataType firstDataTypeVal = firstDataType.getValue(); + assertEquals("tosca.datatypes.Root", firstDataTypeVal.getDerivedFrom().getName()); + assertEquals("1.0.0", firstDataTypeVal.getDerivedFrom().getVersion()); + assertTrue(firstDataTypeVal.getProperties().size() == 6); + Iterator<ToscaProperty> firstDataTypePropertiesIter = firstDataTypeVal.getProperties().iterator(); + + ToscaProperty firstDataTypeFirstProperty = firstDataTypePropertiesIter.next(); + assertEquals("onap.datatypes.monitoring.metricsPerEventName", firstDataTypeFirstProperty.getKey() + .getParentKeyName()); + assertEquals("controlLoopSchemaType", firstDataTypeFirstProperty.getKey().getLocalName()); + assertEquals("string", firstDataTypeFirstProperty.getType().getName()); + assertTrue(firstDataTypeFirstProperty.isRequired()); + assertEquals("Specifies Control Loop Schema Type for the event Name e.g. VNF, VM", + firstDataTypeFirstProperty.getDescription()); + assertTrue(firstDataTypeFirstProperty.getConstraints().size() == 1); + assertEquals("valid_values", firstDataTypeFirstProperty.getConstraints().iterator().next().getKey() + .getLocalName()); + assertEquals("string", firstDataTypeFirstProperty.getConstraints().iterator().next().getKey() + .getParentKeyName()); + assertTrue(firstDataTypeFirstProperty.getConstraints().iterator().next() + instanceof ToscaConstraintValidValues); + assertTrue(((ToscaConstraintValidValues)(firstDataTypeFirstProperty.getConstraints().iterator().next())) + .getValidValues().size() == 2); + + ToscaProperty firstDataTypeSecondProperty = firstDataTypePropertiesIter.next(); + assertEquals("onap.datatypes.monitoring.metricsPerEventName", firstDataTypeSecondProperty.getKey() + .getParentKeyName()); + assertEquals("eventName", firstDataTypeSecondProperty.getKey().getLocalName()); + assertEquals("string", firstDataTypeSecondProperty.getType().getName()); + assertTrue(firstDataTypeSecondProperty.isRequired()); + assertEquals("Event name to which thresholds need to be applied", firstDataTypeSecondProperty + .getDescription()); + + ToscaProperty firstDataTypeThirdProperty = firstDataTypePropertiesIter.next(); + assertEquals("onap.datatypes.monitoring.metricsPerEventName", firstDataTypeThirdProperty.getKey() + .getParentKeyName()); + assertEquals("policyName", firstDataTypeThirdProperty.getKey().getLocalName()); + assertEquals("string", firstDataTypeThirdProperty.getType().getName()); + assertTrue(firstDataTypeThirdProperty.isRequired()); + assertEquals("TCA Policy Scope Name", firstDataTypeThirdProperty.getDescription()); + + ToscaProperty firstDataTypeFourthProperty = firstDataTypePropertiesIter.next(); + assertEquals("onap.datatypes.monitoring.metricsPerEventName", firstDataTypeFourthProperty.getKey() + .getParentKeyName()); + assertEquals("policyScope", firstDataTypeFourthProperty.getKey().getLocalName()); + assertEquals("string", firstDataTypeFourthProperty.getType().getName()); + assertTrue(firstDataTypeFourthProperty.isRequired()); + assertEquals("TCA Policy Scope", firstDataTypeFourthProperty.getDescription()); + + ToscaProperty firstDataTypeFifthProperty = firstDataTypePropertiesIter.next(); + assertEquals("onap.datatypes.monitoring.metricsPerEventName", firstDataTypeFifthProperty.getKey() + .getParentKeyName()); + assertEquals("policyVersion", firstDataTypeFifthProperty.getKey().getLocalName()); + assertEquals("string", firstDataTypeFifthProperty.getType().getName()); + assertTrue(firstDataTypeFifthProperty.isRequired()); + assertEquals("TCA Policy Scope Version", firstDataTypeFifthProperty.getDescription()); + + ToscaProperty firstDataTypeSixthProperty = firstDataTypePropertiesIter.next(); + assertEquals("onap.datatypes.monitoring.metricsPerEventName", firstDataTypeSixthProperty.getKey() + .getParentKeyName()); + assertEquals("thresholds", firstDataTypeSixthProperty.getKey().getLocalName()); + assertEquals("list", firstDataTypeSixthProperty.getType().getName()); + assertTrue(firstDataTypeSixthProperty.isRequired()); + assertEquals("Thresholds associated with eventName", firstDataTypeSixthProperty.getDescription()); + assertNotNull(firstDataTypeSixthProperty.getEntrySchema()); + assertEquals("entry_schema", firstDataTypeSixthProperty.getEntrySchema().getKey().getLocalName()); + assertEquals("list", firstDataTypeSixthProperty.getEntrySchema().getKey().getParentKeyName()); + assertEquals("onap.datatypes.monitoring.thresholds", firstDataTypeSixthProperty.getEntrySchema().getType() + .getName()); + + Entry<PfConceptKey, ToscaDataType> secondDataType = dataTypesIter.next(); + assertEquals("onap.datatypes.monitoring.tca_policy", secondDataType.getKey().getName()); + ToscaDataType secondDataTypeVal = secondDataType.getValue(); + assertEquals("tosca.datatypes.Root", secondDataTypeVal.getDerivedFrom().getName()); + assertEquals("1.0.0", secondDataTypeVal.getDerivedFrom().getVersion()); + assertTrue(secondDataTypeVal.getProperties().size() == 2); + Iterator<ToscaProperty> secondDataTypePropertiesIter = secondDataTypeVal.getProperties().iterator(); + + ToscaProperty secondDataTypeFirstProperty = secondDataTypePropertiesIter.next(); + assertEquals("onap.datatypes.monitoring.tca_policy", secondDataTypeFirstProperty.getKey().getParentKeyName()); + assertEquals("domain", secondDataTypeFirstProperty.getKey().getLocalName()); + assertEquals("string", secondDataTypeFirstProperty.getType().getName()); + assertTrue(secondDataTypeFirstProperty.isRequired()); + assertEquals("Domain name to which TCA needs to be applied", secondDataTypeFirstProperty.getDescription()); + assertEquals("measurementsForVfScaling", secondDataTypeFirstProperty.getDefaultValue()); + assertTrue(secondDataTypeFirstProperty.getConstraints().size() == 1); + assertEquals("string", secondDataTypeFirstProperty.getConstraints().iterator().next().getKey() + .getParentKeyName()); + assertEquals("equal", secondDataTypeFirstProperty.getConstraints().iterator().next().getKey().getLocalName()); + assertTrue(secondDataTypeFirstProperty.getConstraints().iterator().next() + instanceof ToscaConstraintLogicalString); + assertEquals("measurementsForVfScaling", ((ToscaConstraintLogicalString)(secondDataTypeFirstProperty + .getConstraints().iterator().next())).getCompareToString()); + + ToscaProperty secondDataTypeSecondProperty = secondDataTypePropertiesIter.next(); + assertEquals("onap.datatypes.monitoring.tca_policy", secondDataTypeSecondProperty.getKey().getParentKeyName()); + assertEquals("metricsPerEventName", secondDataTypeSecondProperty.getKey().getLocalName()); + assertEquals("list", secondDataTypeSecondProperty.getType().getName()); + assertTrue(secondDataTypeSecondProperty.isRequired()); + assertEquals("Contains eventName and threshold details that need to be applied to given eventName", + secondDataTypeSecondProperty.getDescription()); + assertNotNull(secondDataTypeSecondProperty.getEntrySchema()); + assertEquals("list", secondDataTypeSecondProperty.getEntrySchema().getKey().getParentKeyName()); + assertEquals("onap.datatypes.monitoring.metricsPerEventName", + secondDataTypeSecondProperty.getEntrySchema().getType().getName()); + assertEquals("entry_schema", secondDataTypeSecondProperty.getEntrySchema().getKey().getLocalName()); + + Entry<PfConceptKey, ToscaDataType> thirdDataType = dataTypesIter.next(); + assertEquals("onap.datatypes.monitoring.thresholds", thirdDataType.getKey().getName()); + ToscaDataType thirdDataTypeVal = thirdDataType.getValue(); + assertEquals("tosca.datatypes.Root", thirdDataTypeVal.getDerivedFrom().getName()); + assertEquals("1.0.0", thirdDataTypeVal.getDerivedFrom().getVersion()); + assertTrue(thirdDataTypeVal.getProperties().size() == 7); + Iterator<ToscaProperty> thirdDataTypePropertiesIter = thirdDataTypeVal.getProperties().iterator(); + + ToscaProperty thirdDataTypeFirstProperty = thirdDataTypePropertiesIter.next(); + assertEquals("onap.datatypes.monitoring.thresholds", thirdDataTypeFirstProperty.getKey().getParentKeyName()); + assertEquals("closedLoopControlName", thirdDataTypeFirstProperty.getKey().getLocalName()); + assertEquals("string", thirdDataTypeFirstProperty.getType().getName()); + assertTrue(thirdDataTypeFirstProperty.isRequired()); + assertEquals("Closed Loop Control Name associated with the threshold", thirdDataTypeFirstProperty + .getDescription()); + + ToscaProperty thirdDataTypeSecondProperty = thirdDataTypePropertiesIter.next(); + assertEquals("onap.datatypes.monitoring.thresholds", thirdDataTypeSecondProperty.getKey().getParentKeyName()); + assertEquals("closedLoopEventStatus", thirdDataTypeSecondProperty.getKey().getLocalName()); + assertEquals("string", thirdDataTypeSecondProperty.getType().getName()); + assertTrue(thirdDataTypeSecondProperty.isRequired()); + assertEquals("Closed Loop Event Status of the threshold", thirdDataTypeSecondProperty.getDescription()); + assertNotNull(thirdDataTypeSecondProperty.getConstraints()); + assertTrue(thirdDataTypeSecondProperty.getConstraints().size() == 1); + assertEquals("string", thirdDataTypeSecondProperty.getConstraints().iterator().next().getKey() + .getParentKeyName()); + assertEquals("valid_values", thirdDataTypeSecondProperty.getConstraints().iterator().next().getKey() + .getLocalName()); + assertTrue(thirdDataTypeSecondProperty.getConstraints().iterator().next() + instanceof ToscaConstraintValidValues); + assertTrue(((ToscaConstraintValidValues)(thirdDataTypeSecondProperty.getConstraints().iterator().next())) + .getValidValues().size() == 2); + + ToscaProperty thirdDataTypeThirdProperty = thirdDataTypePropertiesIter.next(); + assertEquals("onap.datatypes.monitoring.thresholds", thirdDataTypeThirdProperty.getKey().getParentKeyName()); + assertEquals("direction", thirdDataTypeThirdProperty.getKey().getLocalName()); + assertEquals("string", thirdDataTypeThirdProperty.getType().getName()); + assertTrue(thirdDataTypeThirdProperty.isRequired()); + assertEquals("Direction of the threshold", thirdDataTypeThirdProperty.getDescription()); + assertNotNull(thirdDataTypeThirdProperty.getConstraints()); + assertTrue(thirdDataTypeThirdProperty.getConstraints().size() == 1); + assertEquals("string", thirdDataTypeThirdProperty.getConstraints().iterator().next().getKey() + .getParentKeyName()); + assertEquals("valid_values", thirdDataTypeThirdProperty.getConstraints().iterator().next().getKey() + .getLocalName()); + assertTrue(((ToscaConstraintValidValues)(thirdDataTypeThirdProperty.getConstraints().iterator().next())) + .getValidValues().size() == 5); + + ToscaProperty thirdDataTypeFourthProperty = thirdDataTypePropertiesIter.next(); + assertEquals("onap.datatypes.monitoring.thresholds", thirdDataTypeFourthProperty.getKey().getParentKeyName()); + assertEquals("fieldPath", thirdDataTypeFourthProperty.getKey().getLocalName()); + assertEquals("string", thirdDataTypeFourthProperty.getType().getName()); + assertTrue(thirdDataTypeFourthProperty.isRequired()); + assertEquals("Json field Path as per CEF message which needs to be analyzed for TCA", + thirdDataTypeFourthProperty.getDescription()); + assertNotNull(thirdDataTypeFourthProperty.getConstraints()); + assertTrue(thirdDataTypeFourthProperty.getConstraints().size() == 1); + assertEquals("string", thirdDataTypeFourthProperty.getConstraints().iterator().next().getKey() + .getParentKeyName()); + assertEquals("valid_values", thirdDataTypeFourthProperty.getConstraints().iterator().next().getKey() + .getLocalName()); + assertTrue(((ToscaConstraintValidValues)(thirdDataTypeFourthProperty.getConstraints().iterator().next())) + .getValidValues().size() == 43); + + ToscaProperty thirdDataTypeFifthProperty = thirdDataTypePropertiesIter.next(); + assertEquals("onap.datatypes.monitoring.thresholds", thirdDataTypeFifthProperty.getKey().getParentKeyName()); + assertEquals("severity", thirdDataTypeFifthProperty.getKey().getLocalName()); + assertEquals("string", thirdDataTypeFifthProperty.getType().getName()); + assertTrue(thirdDataTypeFifthProperty.isRequired()); + assertEquals("Threshold Event Severity", thirdDataTypeFifthProperty.getDescription()); + assertNotNull(thirdDataTypeFifthProperty.getConstraints()); + assertTrue(thirdDataTypeFifthProperty.getConstraints().size() == 1); + assertEquals("string", thirdDataTypeFifthProperty.getConstraints().iterator().next().getKey() + .getParentKeyName()); + assertEquals("valid_values", thirdDataTypeFifthProperty.getConstraints().iterator().next().getKey() + .getLocalName()); + assertTrue(((ToscaConstraintValidValues)(thirdDataTypeFifthProperty.getConstraints().iterator().next())) + .getValidValues().size() == 5);; + + ToscaProperty thirdDataTypeSixthProperty = thirdDataTypePropertiesIter.next(); + assertEquals("onap.datatypes.monitoring.thresholds", thirdDataTypeSixthProperty.getKey().getParentKeyName()); + assertEquals("thresholdValue", thirdDataTypeSixthProperty.getKey().getLocalName()); + assertEquals("integer", thirdDataTypeSixthProperty.getType().getName()); + assertTrue(thirdDataTypeSixthProperty.isRequired()); + assertEquals("Threshold value for the field Path inside CEF message", thirdDataTypeSixthProperty + .getDescription()); + + ToscaProperty thirdDataTypeSeventhProperty = thirdDataTypePropertiesIter.next(); + assertEquals("onap.datatypes.monitoring.thresholds", thirdDataTypeSeventhProperty.getKey().getParentKeyName()); + assertEquals("version", thirdDataTypeSeventhProperty.getKey().getLocalName()); + assertEquals("string", thirdDataTypeSeventhProperty.getType().getName()); + assertTrue(thirdDataTypeSeventhProperty.isRequired()); + assertEquals("Version number associated with the threshold", thirdDataTypeSeventhProperty.getDescription()); + } + + private void verifyCollectorInputDeserialization(ToscaServiceTemplate serviceTemplate) { + + // Sanity check the entire structure + assertNotNull(serviceTemplate); + LOGGER.info(serviceTemplate.validate(new PfValidationResult()).toString()); + assertTrue(serviceTemplate.validate(new PfValidationResult()).isValid()); + + // Check tosca_definitions_version + assertEquals("tosca_simple_yaml_1_0_0", serviceTemplate.getToscaDefinitionsVersion()); + + // Check policy_types + Map<PfConceptKey, ToscaPolicyType> policyTypesConceptMap = serviceTemplate.getPolicyTypes().getConceptMap(); + assertTrue(policyTypesConceptMap.size() == 2); + Iterator<Entry<PfConceptKey, ToscaPolicyType>> policyTypesIter = policyTypesConceptMap.entrySet().iterator(); + + Entry<PfConceptKey, ToscaPolicyType> firstPolicyType = policyTypesIter.next(); + assertEquals("onap.policies.Monitoring", firstPolicyType.getKey().getName()); + assertEquals("1.0.0", firstPolicyType.getKey().getVersion()); + assertEquals("tosca.policies.Root", firstPolicyType.getValue().getDerivedFrom().getName()); + assertEquals("a base policy type for all policies that govern monitoring provision", + firstPolicyType.getValue().getDescription()); + + Entry<PfConceptKey, ToscaPolicyType> secondPolicyType = policyTypesIter.next(); + assertEquals("onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server", + secondPolicyType.getKey().getName()); + assertEquals("1.0.0", secondPolicyType.getKey().getVersion()); + assertEquals("policy.nodes.Root", secondPolicyType.getValue().getDerivedFrom().getName()); + assertTrue(secondPolicyType.getValue().getProperties().size() == 2); + + Iterator<ToscaProperty> propertiesIter = secondPolicyType.getValue().getProperties().iterator(); + + ToscaProperty firstProperty = propertiesIter.next(); + assertEquals("onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server", + firstProperty.getKey().getParentKeyName()); + assertEquals("1.0.0", firstProperty.getKey().getParentKeyVersion()); + assertEquals("buscontroller_feed_publishing_endpoint", firstProperty.getKey().getLocalName()); + assertEquals("string", firstProperty.getType().getName()); + assertEquals("DMAAP Bus Controller feed endpoint", firstProperty.getDescription()); + + ToscaProperty secondProperty = propertiesIter.next(); + assertEquals("onap.policies.monitoring.dcaegen2.collectors.datafile.datafile-app-server", + secondProperty.getKey().getParentKeyName()); + assertEquals("1.0.0", secondProperty.getKey().getParentKeyVersion()); + assertEquals("datafile.policy", secondProperty.getKey().getLocalName()); + assertEquals("string", secondProperty.getType().getName()); + assertEquals("datafile Policy JSON as string", secondProperty.getDescription()); + } + + private String serializeMonitoringServiceTemplate(ToscaServiceTemplate serviceTemplate) { + return gson.toJson(serviceTemplate); + } +}
\ No newline at end of file diff --git a/models-tosca/src/test/resources/META-INF/persistence.xml b/models-tosca/src/test/resources/META-INF/persistence.xml new file mode 100644 index 000000000..68340901b --- /dev/null +++ b/models-tosca/src/test/resources/META-INF/persistence.xml @@ -0,0 +1,74 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ============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========================================================= +--> + +<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0"> + <persistence-unit name="ToscaConceptTest" transaction-type="RESOURCE_LOCAL"> + <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> + + <class>org.onap.policy.models.dao.converters.CDataConditioner</class> + <class>org.onap.policy.models.dao.converters.Uuid2String</class> + <class>org.onap.policy.models.base.PfConceptKey</class> + <class>org.onap.policy.models.tosca.simple.concepts.ToscaPolicyType</class> + <class>org.onap.policy.models.tosca.simple.concepts.ToscaPolicy</class> + + <properties> + <property name="javax.persistence.jdbc.driver" value="org.h2.Driver" /> + <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:testdb" /> + <property name="javax.persistence.jdbc.user" value="policy" /> + <property name="javax.persistence.jdbc.password" value="P01icY" /> + <property name="eclipselink.ddl-generation" value="drop-and-create-tables" /> + <property name="eclipselink.ddl-generation.output-mode" value="database" /> + <property name="eclipselink.logging.level" value="INFO" /> + </properties> + </persistence-unit> + + <persistence-unit name="ToscaConceptMariaDBTest" transaction-type="RESOURCE_LOCAL"> + <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> + + <class>org.onap.policy.models.dao.converters.CDataConditioner</class> + <class>org.onap.policy.models.dao.converters.Uuid2String</class> + <class>org.onap.policy.models.base.PfConceptKey</class> + <class>org.onap.policy.models.tosca.simple.concepts.ToscaPolicy</class> + + <properties> + <property name="javax.persistence.jdbc.driver" value="org.mariadb.jdbc.Driver" /> + <property name="javax.persistence.jdbc.url" value="jdbc:mariadb://localhost:3306/policy" /> + <property name="javax.persistence.jdbc.user" value="policy" /> + <property name="javax.persistence.jdbc.password" value="P01icY" /> + <property name="javax.persistence.schema-generation.database.action" value="create" /> + + <!-- property name="eclipselink.logging.level" value="ALL" /> + <property name="eclipselink.logging.level.jpa" value="ALL" /> + <property name="eclipselink.logging.level.ddl" value="ALL" /> + <property name="eclipselink.logging.level.connection" value="ALL" /> + <property name="eclipselink.logging.level.sql" value="ALL" /> + <property name="eclipselink.logging.level.transaction" value="ALL" /> + <property name="eclipselink.logging.level.sequencing" value="ALL" /> + <property name="eclipselink.logging.level.server" value="ALL" /> + <property name="eclipselink.logging.level.query" value="ALL" /> + <property name="eclipselink.logging.level.properties" value="ALL" /--> + + <property name="eclipselink.ddl-generation" value="drop-and-create-tables" /> + <property name="eclipselink.ddl-generation.output-mode" value="database" /> + <property name="eclipselink.logging.level" value="INFO" /> + </properties> + </persistence-unit> +</persistence> |