From 676194789a8b880e2416f9d3bf2484a9fc6be1bc Mon Sep 17 00:00:00 2001 From: "a.sreekumar" Date: Tue, 15 Feb 2022 12:16:30 +0000 Subject: [PATCH 1/1] Fix issue with GeneratedValue in PfGeneratedIdKey PfGeneratedIdKey class (which is used as a composite key in JpaPolicyAudit and JpaPdpStatistics) uses GeneratedValue in a wrong way and not according to the specification. This review fixes it. PfGeneratedIdKey class is removed, and the generatedId is directly specified in the JpaPolicyAudit and JpaPdpStatistics classes. Note: These classes are only used by PAP, so the related methods for db interaction is removed as PAP directly talks to DB using spring repository layer. Also the only end result this change brings is that the 'generatedId' alone will be used as the primary key instead of 'generatedId, name and version' together. Corresponding changes in DB Migrator: https://gerrit.onap.org/r/c/policy/docker/+/127139 PAP: https://gerrit.onap.org/r/c/policy/pap/+/127130 Change-Id: Ib4ea8b60ffe5c2480746569c0354bf474a6b7006 Issue-ID: POLICY-3897 Signed-off-by: a.sreekumar --- .../onap/policy/models/base/PfGeneratedIdKey.java | 166 ------------ .../policy/models/base/PfGeneratedIdKeyTest.java | 96 ------- .../java/org/onap/policy/models/dao/PfDao.java | 34 +-- .../onap/policy/models/dao/impl/DefaultPfDao.java | 60 +---- .../org/onap/policy/models/dao/impl/ProxyDao.java | 49 +--- .../policy/models/dao/DummyGeneratedIdEntity.java | 132 ---------- .../org/onap/policy/models/dao/EntityTest.java | 150 +---------- .../pap/persistence/concepts/JpaPolicyAudit.java | 83 ++++-- .../persistence/provider/PolicyAuditProvider.java | 146 ----------- .../provider/PolicyAuditProviderTest.java | 234 ----------------- .../pdp/persistence/concepts/JpaPdpStatistics.java | 89 ++++--- .../provider/PdpStatisticsProvider.java | 172 ------------- .../persistence/concepts/JpaPdpStatisticsTest.java | 4 +- .../provider/PdpStatisticsProviderTest.java | 280 --------------------- .../models/provider/PolicyModelsProvider.java | 61 +---- .../impl/AbstractPolicyModelsProvider.java | 47 +--- .../impl/DatabasePolicyModelsProviderImpl.java | 2 +- .../impl/DatabasePolicyModelsProviderTest.java | 120 +-------- .../models/provider/impl/DummyBadProviderImpl.java | 45 +--- .../impl/DummyPolicyModelsProviderImpl.java | 44 +--- .../impl/DummyPolicyModelsProviderTest.java | 18 +- .../impl/PolicyStatisticsPersistenceTest.java | 87 ------- 22 files changed, 135 insertions(+), 1984 deletions(-) delete mode 100644 models-base/src/main/java/org/onap/policy/models/base/PfGeneratedIdKey.java delete mode 100644 models-base/src/test/java/org/onap/policy/models/base/PfGeneratedIdKeyTest.java delete mode 100644 models-dao/src/test/java/org/onap/policy/models/dao/DummyGeneratedIdEntity.java delete mode 100644 models-pap/src/main/java/org/onap/policy/models/pap/persistence/provider/PolicyAuditProvider.java delete mode 100644 models-pap/src/test/java/org/onap/policy/models/pap/persistence/provider/PolicyAuditProviderTest.java delete mode 100644 models-pdp/src/main/java/org/onap/policy/models/pdp/persistence/provider/PdpStatisticsProvider.java delete mode 100644 models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/provider/PdpStatisticsProviderTest.java delete mode 100644 models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyStatisticsPersistenceTest.java diff --git a/models-base/src/main/java/org/onap/policy/models/base/PfGeneratedIdKey.java b/models-base/src/main/java/org/onap/policy/models/base/PfGeneratedIdKey.java deleted file mode 100644 index 8e6e325c1..000000000 --- a/models-base/src/main/java/org/onap/policy/models/base/PfGeneratedIdKey.java +++ /dev/null @@ -1,166 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.models.base; - - -import javax.persistence.Column; -import javax.persistence.Embeddable; -import javax.persistence.GeneratedValue; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NonNull; -import org.onap.policy.common.parameters.annotations.Pattern; -import org.onap.policy.common.utils.validation.Assertions; - -/** - * A concept key uniquely identifies every first order entity in the system. Every first order concept in the system - * must have a {@link PfGeneratedIdKey} to identify it. Concepts that are wholly contained in another concept are - * identified using a {@link PfReferenceKey} key. - * - *

Key validation checks that the name and version fields match the NAME_REGEXP and VERSION_REGEXP - * regular expressions respectively. - */ -@Embeddable -@Data -@EqualsAndHashCode(callSuper = false) -public class PfGeneratedIdKey extends PfKeyImpl { - - private static final long serialVersionUID = 1L; - - private static final String ID_TOKEN = "ID"; - - @Column(name = NAME_TOKEN, length = 120) - @Pattern(regexp = NAME_REGEXP) - private String name; - - @Column(name = VERSION_TOKEN, length = 20) - @Pattern(regexp = VERSION_REGEXP) - private String version; - - @Column(name = ID_TOKEN) - @GeneratedValue - private Long generatedId; - - /** - * The default constructor creates a null concept key. - */ - public PfGeneratedIdKey() { - this(NULL_KEY_NAME, NULL_KEY_VERSION); - } - - /** - * Constructor to create a key with the specified name and version. - * - * @param name the key name - * @param version the key version - */ - public PfGeneratedIdKey(final String name, final String version) { - super(name, version); - } - - /** - * Copy constructor. - * - * @param copyConcept the concept to copy from - */ - public PfGeneratedIdKey(final PfGeneratedIdKey copyConcept) { - super(copyConcept); - this.generatedId = copyConcept.getGeneratedId(); - } - - /** - * Constructor to create a key with the specified name and version. - * - * @param name the key name - * @param version the key version - * @param generatedId the conceptId of key - */ - public PfGeneratedIdKey(@NonNull final String name, @NonNull final String version, - final Long generatedId) { - super(name, version); - this.generatedId = generatedId; - } - - /** - * Constructor to create a key using the key and version from the specified key ID. - * - * @param id the key ID in a format that respects the KEY_ID_REGEXP - */ - public PfGeneratedIdKey(final String id) { - super(id.substring(0, id.lastIndexOf(':'))); - this.generatedId = Long.parseLong(id.substring(id.lastIndexOf(':') + 1)); - } - - @Override - public int compareTo(@NonNull final PfConcept otherObj) { - int result = super.compareTo(otherObj); - if (0 == result) { - final PfGeneratedIdKey other = (PfGeneratedIdKey) otherObj; - return generatedId.compareTo(other.generatedId); - } - return result; - } - - @Override - public String getId() { - return getName() + ':' + getVersion() + ':' + getGeneratedId(); - } - - @Override - public boolean isNewerThan(@NonNull PfKey otherKey) { - Assertions.instanceOf(otherKey, PfGeneratedIdKey.class); - - final PfGeneratedIdKey otherConceptKey = (PfGeneratedIdKey) otherKey; - - if (this.equals(otherConceptKey)) { - return false; - } - - if (!generatedId.equals(otherConceptKey.generatedId)) { - return generatedId.compareTo(otherConceptKey.generatedId) >= 1; - } - - return super.isNewerThan(otherKey); - } - - @Override - public boolean isNullKey() { - return super.isNullKey() && getGeneratedId() == null; - } - - public void setName(@NonNull final String name) { - this.name = Assertions.validateStringParameter(NAME_TOKEN, name, getNameRegEx()); - } - - public void setVersion(@NonNull final String version) { - this.version = Assertions.validateStringParameter(VERSION_TOKEN, version, getVersionRegEx()); - } - - /** - * Get a null concept key. - * - * @return a null concept key - */ - public static final PfGeneratedIdKey getNullKey() { - return new PfGeneratedIdKey(PfKey.NULL_KEY_NAME, PfKey.NULL_KEY_VERSION); - } - -} diff --git a/models-base/src/test/java/org/onap/policy/models/base/PfGeneratedIdKeyTest.java b/models-base/src/test/java/org/onap/policy/models/base/PfGeneratedIdKeyTest.java deleted file mode 100644 index 4f10710ba..000000000 --- a/models-base/src/test/java/org/onap/policy/models/base/PfGeneratedIdKeyTest.java +++ /dev/null @@ -1,96 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - - -package org.onap.policy.models.base; - -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -public class PfGeneratedIdKeyTest { - private static final String VERSION001 = "0.0.1"; - private static final String CONCEPT_IS_NULL = "^copyConcept is marked .*on.*ull but is null$"; - private static final String NAME_IS_NULL = "^name is marked .*on.*ull but is null$"; - private static final String VERSION_IS_NULL = "^version is marked .*on.*ull but is null$"; - private static final long generatedId = 10001L; - - @Test - public void testGeneratedIdKey() { - PfGeneratedIdKey someKey0 = new PfGeneratedIdKey(); - assertEquals(PfGeneratedIdKey.getNullKey(), someKey0); - assertTrue(someKey0.isNullKey()); - assertEquals("PfGeneratedIdKey(name=NULL, version=0.0.0, generatedId=null)", - someKey0.toString()); - - PfGeneratedIdKey someKey1 = new PfGeneratedIdKey("my-name", VERSION001, generatedId); - PfGeneratedIdKey someKey2 = new PfGeneratedIdKey(someKey1); - PfGeneratedIdKey someKey3 = new PfGeneratedIdKey(someKey1.getId()); - assertEquals(someKey1, someKey2); - assertEquals(someKey1, someKey3); - assertFalse(someKey1.isNullVersion()); - assertEquals("PfGeneratedIdKey(name=my-name, version=0.0.1, generatedId=" - + generatedId + ")", someKey1.toString()); - - assertEquals("my-name", someKey1.getName()); - assertEquals(VERSION001, someKey1.getVersion()); - - assertEquals(someKey2, someKey1.getKey()); - assertEquals(1, someKey1.getKeys().size()); - assertThatThrownBy(() -> someKey0.setName(null)).isInstanceOf(NullPointerException.class) - .hasMessageMatching(NAME_IS_NULL); - assertThatThrownBy(() -> someKey0.setVersion(null)).isInstanceOf(NullPointerException.class) - .hasMessageMatching(VERSION_IS_NULL); - assertThatCode(() -> someKey0.setGeneratedId(null)).doesNotThrowAnyException(); - - assertFalse(someKey1.isNewerThan(someKey2)); - assertThatThrownBy(() -> someKey1.isNewerThan((PfKey) null)).isInstanceOf(NullPointerException.class) - .hasMessageMatching("^otherKey is marked .*on.*ull but is null$"); - someKey2.setGeneratedId(generatedId + 1); - assertTrue(someKey2.isNewerThan(someKey1)); - someKey3.setName("my-name3"); - assertTrue(someKey3.isNewerThan(someKey1)); - - assertEquals(-1, someKey1.compareTo(someKey2)); - assertEquals(-1, someKey1.compareTo(someKey3)); - assertThatThrownBy(() -> someKey1.compareTo((PfConcept) null)).isInstanceOf(NullPointerException.class) - .hasMessageMatching("^otherObj is marked .*on.*ull but is null$"); - - PfGeneratedIdKey someKey4 = new PfGeneratedIdKey("NULL", "0.0.0", generatedId); - assertFalse(someKey4.isNullKey()); - assertFalse(someKey1.isNullKey()); - } - - @Test - public void testTimestampKeyErrors() { - assertThatThrownBy(() -> new PfGeneratedIdKey((PfGeneratedIdKey) null)).isInstanceOf(NullPointerException.class) - .hasMessageMatching(CONCEPT_IS_NULL); - assertThatThrownBy(() -> new PfGeneratedIdKey(null, null, null)).isInstanceOf(NullPointerException.class) - .hasMessageMatching(NAME_IS_NULL); - assertThatThrownBy(() -> new PfGeneratedIdKey("my-name", null, null)).isInstanceOf(NullPointerException.class) - .hasMessageMatching(VERSION_IS_NULL); - assertThatCode(() -> new PfGeneratedIdKey("my-name", VERSION001, null)) - .doesNotThrowAnyException(); - } -} diff --git a/models-dao/src/main/java/org/onap/policy/models/dao/PfDao.java b/models-dao/src/main/java/org/onap/policy/models/dao/PfDao.java index 7358ab11b..380a9831e 100644 --- a/models-dao/src/main/java/org/onap/policy/models/dao/PfDao.java +++ b/models-dao/src/main/java/org/onap/policy/models/dao/PfDao.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019-2021 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,12 +22,10 @@ package org.onap.policy.models.dao; -import java.time.Instant; import java.util.Collection; import java.util.List; import org.onap.policy.models.base.PfConcept; import org.onap.policy.models.base.PfConceptKey; -import org.onap.policy.models.base.PfGeneratedIdKey; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.base.PfReferenceKey; import org.onap.policy.models.base.PfReferenceTimestampKey; @@ -94,15 +93,6 @@ public interface PfDao { */ void delete(Class someClass, PfTimestampKey timeStampKey); - /** - * Delete an Policy Framework concept on the database. - * - * @param the type of the object to delete, a subclass of {@link PfConcept} - * @param someClass the class of the object to delete, a subclass of {@link PfConcept} - * @param idKey the PfConceptIdKey of the object to delete - */ - void delete(Class someClass, PfGeneratedIdKey idKey); - /** * Create a collection of objects in the database. * @@ -202,16 +192,6 @@ public interface PfDao { */ T get(Class someClass, PfTimestampKey timestampKey); - /** - * Get an object from the database, referred to by reference key. - * - * @param the type of the object to get, a subclass of {@link PfConcept} - * @param someClass the class of the object to get, a subclass of {@link PfConcept} - * @param idKey the PfConceptIdKey of the object to get - * @return the object that was retrieved from the database or null if the object was not retrieved - */ - T get(Class someClass, PfGeneratedIdKey idKey); - /** * Get an object from the database, referred to by reference timestamp key. * @@ -272,18 +252,6 @@ public interface PfDao { */ List getAllVersionsByParent(Class someClass, final String parentKeyName); - /** - * Get all the objects in the database of a given type. - * - * @param the type of the objects to get, a subclass of {@link PfConcept} - * @param someClass the class of the objects to get, a subclass of {@link PfConcept} - * @param key the key of the PfGeneratedIdKey to get - * @param timeStamp the timeStamp of the concepts to get - * @return the objects or null if no objects were retrieved - */ - List getByTimestamp(final Class someClass, - final PfGeneratedIdKey key, final Instant timeStamp); - /** * Get a concept from the database with the given concept key. * diff --git a/models-dao/src/main/java/org/onap/policy/models/dao/impl/DefaultPfDao.java b/models-dao/src/main/java/org/onap/policy/models/dao/impl/DefaultPfDao.java index 1b1b77da2..22c5c5397 100644 --- a/models-dao/src/main/java/org/onap/policy/models/dao/impl/DefaultPfDao.java +++ b/models-dao/src/main/java/org/onap/policy/models/dao/impl/DefaultPfDao.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019-2021 Nordix Foundation. * Modifications Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,8 +22,6 @@ package org.onap.policy.models.dao.impl; -import java.sql.Timestamp; -import java.time.Instant; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -34,7 +33,6 @@ import javax.ws.rs.core.Response; import org.apache.commons.lang3.StringUtils; import org.onap.policy.models.base.PfConcept; import org.onap.policy.models.base.PfConceptKey; -import org.onap.policy.models.base.PfGeneratedIdKey; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.base.PfReferenceKey; @@ -60,7 +58,6 @@ public class DefaultPfDao implements PfDao { private static final String NAME = "name"; private static final String VERSION = "version"; private static final String TIMESTAMP = "timeStamp"; - private static final String GENERATEDID = "Id"; private static final String PARENT_NAME = "parentname"; private static final String PARENT_VERSION = "parentversion"; private static final String LOCAL_NAME = "localname"; @@ -78,8 +75,6 @@ public class DefaultPfDao implements PfDao { private static final String NAME_FILTER = "c.key.name = :name"; private static final String VERSION_FILTER = "c.key.version = :version"; private static final String TIMESTAMP_FILTER = "c.key.timeStamp = :timeStamp"; - private static final String TIMESTAMP_FILTER_NOKEY = "c.timeStamp = :timeStamp"; - private static final String GENERATED_ID_FILTER = "c.key.generatedId = :Id"; private static final String PARENT_NAME_FILTER = "c.key.parentKeyName = :parentname"; private static final String PARENT_VERSION_FILTER = "c.key.parentKeyVersion = :parentversion"; private static final String LOCAL_NAME_FILTER = "c.key.localName = :localname"; @@ -92,9 +87,6 @@ public class DefaultPfDao implements PfDao { private static final String DELETE_BY_TIMESTAMP_KEY = DELETE_FROM_TABLE + WHERE + NAME_FILTER + AND + VERSION_FILTER + AND + TIMESTAMP_FILTER; - private static final String DELETE_BY_GENERATED_ID_KEY = - DELETE_FROM_TABLE + WHERE + NAME_FILTER + AND + VERSION_FILTER + AND + GENERATED_ID_FILTER; - private static final String DELETE_BY_REFERENCE_KEY = DELETE_FROM_TABLE + WHERE + PARENT_NAME_FILTER + AND + PARENT_VERSION_FILTER + AND + LOCAL_NAME_FILTER; @@ -109,9 +101,6 @@ public class DefaultPfDao implements PfDao { private static final String SELECT_BY_CONCEPT_KEY = SELECT_FROM_TABLE + WHERE + NAME_FILTER + AND + VERSION_FILTER; - private static final String SELECT_BY_TIMESTAMP_NOKEY = - SELECT_FROM_TABLE + WHERE + NAME_FILTER + AND + VERSION_FILTER + AND + TIMESTAMP_FILTER_NOKEY; - private static final String SELECT_BY_REFERENCE_KEY = SELECT_FROM_TABLE + WHERE + PARENT_NAME_FILTER + AND + PARENT_VERSION_FILTER + AND + LOCAL_NAME_FILTER; // @formatter:on @@ -254,27 +243,6 @@ public class DefaultPfDao implements PfDao { } } - @Override - public void delete(final Class someClass, final PfGeneratedIdKey key) { - if (key == null) { - return; - } - final var mg = getEntityManager(); - try { - // @formatter:off - mg.getTransaction().begin(); - mg.createQuery(setQueryTable(DELETE_BY_GENERATED_ID_KEY, someClass), someClass) - .setParameter(NAME, key.getName()) - .setParameter(VERSION, key.getVersion()) - .setParameter(GENERATEDID, key.getGeneratedId()) - .executeUpdate(); - mg.getTransaction().commit(); - // @formatter:on - } finally { - mg.close(); - } - } - @Override public void createCollection(final Collection objs) { if (objs == null || objs.isEmpty()) { @@ -417,11 +385,6 @@ public class DefaultPfDao implements PfDao { return genericGet(someClass, key); } - @Override - public T get(final Class someClass, final PfGeneratedIdKey key) { - return genericGet(someClass, key); - } - @Override public T get(final Class someClass, final PfTimestampKey key) { return genericGet(someClass, key); @@ -534,27 +497,6 @@ public class DefaultPfDao implements PfDao { } } - @Override - public List getByTimestamp(final Class someClass, final PfGeneratedIdKey key, - final Instant timeStamp) { - if (someClass == null || key == null || timeStamp == null) { - return Collections.emptyList(); - } - - final var mg = getEntityManager(); - try { - // @formatter:off - return mg.createQuery(setQueryTable(SELECT_BY_TIMESTAMP_NOKEY, someClass), someClass) - .setParameter(NAME, key.getName()) - .setParameter(VERSION, key.getVersion()) - .setParameter(TIMESTAMP, Timestamp.from(timeStamp)) - .getResultList(); - // @formatter:on - } finally { - mg.close(); - } - } - @Override public T getConcept(final Class someClass, final PfConceptKey key) { if (someClass == null || key == null) { diff --git a/models-dao/src/main/java/org/onap/policy/models/dao/impl/ProxyDao.java b/models-dao/src/main/java/org/onap/policy/models/dao/impl/ProxyDao.java index 72d56834d..d0681e1e4 100644 --- a/models-dao/src/main/java/org/onap/policy/models/dao/impl/ProxyDao.java +++ b/models-dao/src/main/java/org/onap/policy/models/dao/impl/ProxyDao.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,8 +21,6 @@ package org.onap.policy.models.dao.impl; -import java.sql.Timestamp; -import java.time.Instant; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -32,7 +31,6 @@ import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.StringUtils; import org.onap.policy.models.base.PfConcept; import org.onap.policy.models.base.PfConceptKey; -import org.onap.policy.models.base.PfGeneratedIdKey; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.base.PfReferenceKey; import org.onap.policy.models.base.PfReferenceTimestampKey; @@ -58,7 +56,6 @@ public class ProxyDao implements PfDao { private static final String NAME = "name"; private static final String VERSION = "version"; private static final String TIMESTAMP = "timeStamp"; - private static final String GENERATEDID = "Id"; private static final String PARENT_NAME = "parentname"; private static final String PARENT_VERSION = "parentversion"; private static final String LOCAL_NAME = "localname"; @@ -76,8 +73,6 @@ public class ProxyDao implements PfDao { private static final String NAME_FILTER = "c.key.name = :name"; private static final String VERSION_FILTER = "c.key.version = :version"; private static final String TIMESTAMP_FILTER = "c.key.timeStamp = :timeStamp"; - private static final String TIMESTAMP_FILTER_NOKEY = "c.timeStamp = :timeStamp"; - private static final String GENERATED_ID_FILTER = "c.key.generatedId = :Id"; private static final String PARENT_NAME_FILTER = "c.key.parentKeyName = :parentname"; private static final String PARENT_VERSION_FILTER = "c.key.parentKeyVersion = :parentversion"; private static final String LOCAL_NAME_FILTER = "c.key.localName = :localname"; @@ -90,9 +85,6 @@ public class ProxyDao implements PfDao { private static final String DELETE_BY_TIMESTAMP_KEY = DELETE_FROM_TABLE + WHERE + NAME_FILTER + AND + VERSION_FILTER + AND + TIMESTAMP_FILTER; - private static final String DELETE_BY_GENERATED_ID_KEY = - DELETE_FROM_TABLE + WHERE + NAME_FILTER + AND + VERSION_FILTER + AND + GENERATED_ID_FILTER; - private static final String DELETE_BY_REFERENCE_KEY = DELETE_FROM_TABLE + WHERE + PARENT_NAME_FILTER + AND + PARENT_VERSION_FILTER + AND + LOCAL_NAME_FILTER; @@ -107,9 +99,6 @@ public class ProxyDao implements PfDao { private static final String SELECT_BY_CONCEPT_KEY = SELECT_FROM_TABLE + WHERE + NAME_FILTER + AND + VERSION_FILTER; - private static final String SELECT_BY_TIMESTAMP_NOKEY = - SELECT_FROM_TABLE + WHERE + NAME_FILTER + AND + VERSION_FILTER + AND + TIMESTAMP_FILTER_NOKEY; - private static final String SELECT_BY_REFERENCE_KEY = SELECT_FROM_TABLE + WHERE + PARENT_NAME_FILTER + AND + PARENT_VERSION_FILTER + AND + LOCAL_NAME_FILTER; // @formatter:on @@ -186,21 +175,6 @@ public class ProxyDao implements PfDao { // @formatter:on } - @Override - public void delete(final Class someClass, final PfGeneratedIdKey key) { - if (key == null) { - return; - } - - // @formatter:off - mg.createQuery(setQueryTable(DELETE_BY_GENERATED_ID_KEY, someClass), someClass) - .setParameter(NAME, key.getName()) - .setParameter(VERSION, key.getVersion()) - .setParameter(GENERATEDID, key.getGeneratedId()) - .executeUpdate(); - // @formatter:on - } - @Override public void createCollection(final Collection objs) { if (objs == null || objs.isEmpty()) { @@ -307,11 +281,6 @@ public class ProxyDao implements PfDao { return genericGet(someClass, key); } - @Override - public T get(final Class someClass, final PfGeneratedIdKey key) { - return genericGet(someClass, key); - } - @Override public T get(final Class someClass, final PfTimestampKey key) { return genericGet(someClass, key); @@ -396,22 +365,6 @@ public class ProxyDao implements PfDao { // @formatter:on } - @Override - public List getByTimestamp(final Class someClass, final PfGeneratedIdKey key, - final Instant timeStamp) { - if (someClass == null || key == null || timeStamp == null) { - return Collections.emptyList(); - } - - // @formatter:off - return mg.createQuery(setQueryTable(SELECT_BY_TIMESTAMP_NOKEY, someClass), someClass) - .setParameter(NAME, key.getName()) - .setParameter(VERSION, key.getVersion()) - .setParameter(TIMESTAMP, Timestamp.from(timeStamp)) - .getResultList(); - // @formatter:on - } - @Override public T getConcept(final Class someClass, final PfConceptKey key) { if (someClass == null || key == null) { diff --git a/models-dao/src/test/java/org/onap/policy/models/dao/DummyGeneratedIdEntity.java b/models-dao/src/test/java/org/onap/policy/models/dao/DummyGeneratedIdEntity.java deleted file mode 100644 index 6ba045c54..000000000 --- a/models-dao/src/test/java/org/onap/policy/models/dao/DummyGeneratedIdEntity.java +++ /dev/null @@ -1,132 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2021 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.dao; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import javax.persistence.Column; -import javax.persistence.EmbeddedId; -import javax.persistence.Entity; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NonNull; -import org.onap.policy.common.parameters.BeanValidationResult; -import org.onap.policy.models.base.PfConcept; -import org.onap.policy.models.base.PfGeneratedIdKey; -import org.onap.policy.models.base.PfKey; - - -@Entity -@Table(name = "DummyGeneratedIdEntity") -@Data -@EqualsAndHashCode(callSuper = false) -public class DummyGeneratedIdEntity extends PfConcept { - private static final long serialVersionUID = -2962570563281067896L; - - @EmbeddedId() - @NonNull - private PfGeneratedIdKey key; - - @Column(precision = 3) - @Temporal(TemporalType.TIMESTAMP) - private Date timeStamp; - - @Column - private double doubleValue; - - /** - * Default constructor. - */ - public DummyGeneratedIdEntity() { - this.key = new PfGeneratedIdKey(); - this.timeStamp = new Date(); - } - - public DummyGeneratedIdEntity(DummyGeneratedIdEntity source) { - this.key = source.key; - this.timeStamp = source.timeStamp; - } - - /** - * Constructor. - * - * @param key the key - * @param timeStamp the date value - */ - public DummyGeneratedIdEntity(final PfGeneratedIdKey key, final Date timeStamp) { - this.key = key; - this.timeStamp = timeStamp; - } - - /** - * Constructor. - * - * @param key the key - * @param timeStamp the date value - * @param doubleValue the double value * - */ - public DummyGeneratedIdEntity(final PfGeneratedIdKey key, final Date timeStamp, final double doubleValue) { - this.key = key; - this.timeStamp = timeStamp; - this.doubleValue = doubleValue; - } - - @Override - public List getKeys() { - final List keyList = new ArrayList<>(); - keyList.add(getKey()); - return keyList; - } - - @Override - public BeanValidationResult validate(@NonNull String fieldName) { - BeanValidationResult result = new BeanValidationResult(fieldName, this); - result.addResult(key.validate("key")); - return result; - } - - @Override - public void clean() { - key.clean(); - } - - @Override - public int compareTo(@NonNull final PfConcept otherObj) { - if (this == otherObj) { - return 0; - } - - if (getClass() != otherObj.getClass()) { - return this.getClass().getName().compareTo(otherObj.getClass().getName()); - } - - final DummyGeneratedIdEntity other = (DummyGeneratedIdEntity) otherObj; - if (this.timeStamp != other.timeStamp) { - return timeStamp.compareTo(other.timeStamp); - } - return Double.compare(doubleValue, other.doubleValue); - } - -} diff --git a/models-dao/src/test/java/org/onap/policy/models/dao/EntityTest.java b/models-dao/src/test/java/org/onap/policy/models/dao/EntityTest.java index c0b0f2ad0..65d22863f 100644 --- a/models-dao/src/test/java/org/onap/policy/models/dao/EntityTest.java +++ b/models-dao/src/test/java/org/onap/policy/models/dao/EntityTest.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019-2021 Nordix Foundation. * Modifications Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +31,6 @@ import static org.junit.Assert.assertNull; import java.time.Instant; import java.util.ArrayList; -import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -42,7 +42,6 @@ import org.eclipse.persistence.config.PersistenceUnitProperties; import org.junit.After; import org.junit.Test; import org.onap.policy.models.base.PfConceptKey; -import org.onap.policy.models.base.PfGeneratedIdKey; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.base.PfReferenceKey; import org.onap.policy.models.base.PfReferenceTimestampKey; @@ -66,9 +65,6 @@ public class EntityTest { private static final Instant TIMESTAMP0 = Instant.ofEpochSecond(1613494293); private static final Instant TIMESTAMP1 = Instant.ofEpochSecond(1613494293).plusSeconds(55); private static final Instant TIMESTAMP2 = Instant.ofEpochSecond(1613494293).plusSeconds(90); - private static final Long GENERATEDID0 = 10000L; - private static final Long GENERATEDID1 = 10001L; - private static final Long GENERATEDID2 = 10002L; private PfDao pfDao; @@ -134,16 +130,12 @@ public class EntityTest { testAllOps(); - testGeneratedId(); - testReferenceTimestamp(); testVersionOps(); testgetFilteredOps(); - testgetFilteredOps2(); - testgetFilteredOps3(); } @@ -384,111 +376,6 @@ public class EntityTest { assertEquals(0, pfDao.size(DummyTimestampEntity.class)); } - private void testGeneratedId() { - final PfGeneratedIdKey agKey0 = new PfGeneratedIdKey("AT-KEY0", VERSION001, GENERATEDID0); - final PfGeneratedIdKey agKey1 = new PfGeneratedIdKey("AT-KEY1", VERSION001, GENERATEDID1); - final PfGeneratedIdKey agKey2 = new PfGeneratedIdKey("AT-KEY2", VERSION001, GENERATEDID2); - final DummyGeneratedIdEntity gkeyInfo0 = new DummyGeneratedIdEntity(agKey0, Date.from(TIMESTAMP0)); - final DummyGeneratedIdEntity gkeyInfo1 = new DummyGeneratedIdEntity(agKey1, Date.from(TIMESTAMP1)); - final DummyGeneratedIdEntity gkeyInfo2 = new DummyGeneratedIdEntity(agKey2, Date.from(TIMESTAMP2)); - - pfDao.create(gkeyInfo0); - - final DummyGeneratedIdEntity gkeyInfoBack0 = pfDao.get(DummyGeneratedIdEntity.class, agKey0); - assertEquals(gkeyInfo0, gkeyInfoBack0); - - assertEquals(1, pfDao.getByTimestamp(DummyGeneratedIdEntity.class, agKey0, TIMESTAMP0).size()); - - final DummyGeneratedIdEntity gkeyInfoBackNull = - pfDao.get(DummyGeneratedIdEntity.class, PfGeneratedIdKey.getNullKey()); - assertNull(gkeyInfoBackNull); - - final Set gkeyInfoSetIn = new TreeSet<>(); - gkeyInfoSetIn.add(gkeyInfo1); - gkeyInfoSetIn.add(gkeyInfo2); - - pfDao.createCollection(gkeyInfoSetIn); - - Set gkeyInfoSetOut = new TreeSet<>(pfDao.getAll(DummyGeneratedIdEntity.class)); - - gkeyInfoSetIn.add(gkeyInfo0); - assertEquals(gkeyInfoSetIn, gkeyInfoSetOut); - - pfDao.delete(gkeyInfo1); - gkeyInfoSetIn.remove(gkeyInfo1); - gkeyInfoSetOut = new TreeSet<>(pfDao.getAll(DummyGeneratedIdEntity.class)); - assertEquals(gkeyInfoSetIn, gkeyInfoSetOut); - - pfDao.deleteCollection(gkeyInfoSetIn); - gkeyInfoSetOut = new TreeSet<>(pfDao.getAll(DummyGeneratedIdEntity.class)); - assertEquals(0, gkeyInfoSetOut.size()); - - gkeyInfoSetIn.add(gkeyInfo2); - pfDao.createCollection(gkeyInfoSetIn); - gkeyInfoSetOut = new TreeSet<>(pfDao.getAll(DummyGeneratedIdEntity.class)); - assertEquals(gkeyInfoSetIn, gkeyInfoSetOut); - - pfDao.delete(DummyGeneratedIdEntity.class, agKey2); - gkeyInfoSetOut = new TreeSet<>(pfDao.getAll(DummyGeneratedIdEntity.class)); - assertEquals(gkeyInfoSetOut.size(), pfDao.size(DummyGeneratedIdEntity.class)); - - pfDao.deleteAll(DummyGeneratedIdEntity.class); - assertEquals(0, pfDao.size(DummyGeneratedIdEntity.class)); - - final PfGeneratedIdKey agKey3 = new PfGeneratedIdKey("AT-KEY0", VERSION001); - final PfGeneratedIdKey agKey4 = new PfGeneratedIdKey("AT-KEY1", VERSION001); - final PfGeneratedIdKey agKey5 = new PfGeneratedIdKey("AT-KEY2", VERSION001); - final DummyGeneratedIdEntity gkeyInfo3 = new DummyGeneratedIdEntity(agKey3, Date.from(TIMESTAMP0)); - final DummyGeneratedIdEntity gkeyInfo4 = new DummyGeneratedIdEntity(agKey4, Date.from(TIMESTAMP1)); - final DummyGeneratedIdEntity gkeyInfo5 = new DummyGeneratedIdEntity(agKey5, Date.from(TIMESTAMP2)); - - pfDao.create(gkeyInfo3); - - final DummyGeneratedIdEntity gkeyInfoBack3 = pfDao.get(DummyGeneratedIdEntity.class, agKey3); - assertEquals(gkeyInfo3, gkeyInfoBack3); - - assertEquals(1, pfDao.getByTimestamp(DummyGeneratedIdEntity.class, agKey3, TIMESTAMP0).size()); - - assertEquals(1, gkeyInfo3.getKeys().size()); - - assertEquals(1, gkeyInfo4.compareTo(gkeyInfo3)); - - assertNull(gkeyInfo4.validate(VERSION002).getResult()); - - - gkeyInfoSetIn.clear(); - gkeyInfoSetIn.add(gkeyInfo4); - gkeyInfoSetIn.add(gkeyInfo5); - - pfDao.createCollection(gkeyInfoSetIn); - - gkeyInfoSetOut = new TreeSet<>(pfDao.getAll(DummyGeneratedIdEntity.class)); - - gkeyInfoSetIn.add(gkeyInfo3); - assertEquals(gkeyInfoSetIn, gkeyInfoSetOut); - - pfDao.delete(gkeyInfo4); - gkeyInfoSetIn.remove(gkeyInfo4); - gkeyInfoSetOut = new TreeSet<>(pfDao.getAll(DummyGeneratedIdEntity.class)); - assertEquals(gkeyInfoSetIn, gkeyInfoSetOut); - - pfDao.deleteCollection(gkeyInfoSetIn); - gkeyInfoSetOut = new TreeSet<>(pfDao.getAll(DummyGeneratedIdEntity.class)); - assertEquals(0, gkeyInfoSetOut.size()); - - gkeyInfoSetIn.add(gkeyInfo5); - pfDao.createCollection(gkeyInfoSetIn); - gkeyInfoSetOut = new TreeSet<>(pfDao.getAll(DummyGeneratedIdEntity.class)); - assertEquals(gkeyInfoSetIn, gkeyInfoSetOut); - - pfDao.delete(DummyGeneratedIdEntity.class, agKey5); - gkeyInfoSetOut = new TreeSet<>(pfDao.getAll(DummyGeneratedIdEntity.class)); - assertEquals(gkeyInfoSetOut.size(), pfDao.size(DummyGeneratedIdEntity.class)); - - pfDao.deleteAll(DummyGeneratedIdEntity.class); - assertEquals(0, pfDao.size(DummyGeneratedIdEntity.class)); - } - private void testReferenceTimestamp() { final PfConceptKey owner0Key = new PfConceptKey("Owner0", VERSION001); final PfConceptKey owner1Key = new PfConceptKey("Owner1", VERSION001); @@ -638,41 +525,6 @@ public class EntityTest { PfFilterParameters.builder().filterMap(filterMap).build())).hasSize(1); } - private void testgetFilteredOps2() { - Map filterMap = new HashMap<>(); - filterMap.put("doubleValue", 200.1); - - final PfGeneratedIdKey agKey0 = new PfGeneratedIdKey("AT-KEY0", VERSION001); - final PfGeneratedIdKey agKey1 = new PfGeneratedIdKey("AT-KEY1", VERSION001); - final PfGeneratedIdKey agKey2 = new PfGeneratedIdKey("AT-KEY2", VERSION001); - final DummyGeneratedIdEntity gkeyInfo0 = new DummyGeneratedIdEntity(agKey0, Date.from(TIMESTAMP0), 200.0); - final DummyGeneratedIdEntity gkeyInfo1 = new DummyGeneratedIdEntity(agKey1, Date.from(TIMESTAMP1), 200.1); - final DummyGeneratedIdEntity gkeyInfo2 = new DummyGeneratedIdEntity(agKey2, Date.from(TIMESTAMP2), 200.2); - - pfDao.create(gkeyInfo0); - pfDao.create(gkeyInfo1); - pfDao.create(gkeyInfo2); - - - assertThat(pfDao.getFiltered(DummyGeneratedIdEntity.class, - PfFilterParameters.builder().name("AT-KEY0").version(VERSION001).build())).hasSize(1); - assertThat(pfDao.getFiltered(DummyGeneratedIdEntity.class, - PfFilterParameters.builder().name("AT-KEY0").build())).hasSize(1); - assertThat(pfDao.getFiltered(DummyGeneratedIdEntity.class, PfFilterParameters.builder().version(VERSION001) - .startTime(TIMESTAMP0).endTime(TIMESTAMP2).build())).hasSize(3); - assertThat(pfDao.getFiltered(DummyGeneratedIdEntity.class, PfFilterParameters.builder().name("AT-KEY0") - .version(VERSION001).startTime(TIMESTAMP0).endTime(TIMESTAMP2).build())).hasSize(1); - assertThat(pfDao.getFiltered(DummyGeneratedIdEntity.class, - PfFilterParameters.builder().version(VERSION001).endTime(TIMESTAMP2).build())).hasSize(3); - assertThat(pfDao.getFiltered(DummyGeneratedIdEntity.class, - PfFilterParameters.builder().version(VERSION001).startTime(TIMESTAMP0).build())).hasSize(3); - assertThat(pfDao.getFiltered(DummyGeneratedIdEntity.class, PfFilterParameters.builder().version(VERSION001) - .startTime(TIMESTAMP0).endTime(TIMESTAMP2).sortOrder("DESC").recordNum(2).build())).hasSize(2); - - assertThat(pfDao.getFiltered(DummyGeneratedIdEntity.class, - PfFilterParameters.builder().filterMap(filterMap).build())).hasSize(1); - } - private void testgetFilteredOps3() { Map filterMap = new HashMap<>(); filterMap.put("localName", "AT-KEY0"); diff --git a/models-pap/src/main/java/org/onap/policy/models/pap/persistence/concepts/JpaPolicyAudit.java b/models-pap/src/main/java/org/onap/policy/models/pap/persistence/concepts/JpaPolicyAudit.java index e151441da..35e385637 100644 --- a/models-pap/src/main/java/org/onap/policy/models/pap/persistence/concepts/JpaPolicyAudit.java +++ b/models-pap/src/main/java/org/onap/policy/models/pap/persistence/concepts/JpaPolicyAudit.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2021 Nordix Foundation. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,28 +22,36 @@ package org.onap.policy.models.pap.persistence.concepts; import java.time.Instant; +import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.Column; -import javax.persistence.EmbeddedId; import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; import javax.persistence.Index; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.Table; +import javax.persistence.TableGenerator; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import lombok.Data; import lombok.EqualsAndHashCode; +import lombok.NonNull; import org.apache.commons.lang3.builder.CompareToBuilder; +import org.onap.policy.common.parameters.BeanValidationResult; +import org.onap.policy.common.parameters.ValidationStatus; +import org.onap.policy.common.parameters.annotations.Pattern; import org.onap.policy.common.utils.validation.Assertions; import org.onap.policy.models.base.PfAuthorative; import org.onap.policy.models.base.PfConcept; -import org.onap.policy.models.base.PfGeneratedIdKey; +import org.onap.policy.models.base.PfConceptKey; import org.onap.policy.models.base.PfKey; import org.onap.policy.models.base.PfReferenceKey; -import org.onap.policy.models.base.validation.annotations.VerifyKey; +import org.onap.policy.models.base.Validated; import org.onap.policy.models.pap.concepts.PolicyAudit; import org.onap.policy.models.pap.concepts.PolicyAudit.AuditAction; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; @@ -62,11 +70,24 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; public class JpaPolicyAudit extends PfConcept implements PfAuthorative { private static final long serialVersionUID = -2935734300607322191L; - @EmbeddedId - @Column - @NotNull - @VerifyKey(versionNotNull = true) - private PfGeneratedIdKey key; + @Id + @Column(name = "ID") + @GeneratedValue(strategy = GenerationType.TABLE, generator = "auditIdGen") + @TableGenerator( + name = "auditIdGen", + table = "sequence", + pkColumnName = "SEQ_NAME", + valueColumnName = "SEQ_COUNT", + pkColumnValue = "SEQ_GEN") + private Long generatedId; + + @Column(name = "name", length = 120) + @Pattern(regexp = PfKey.NAME_REGEXP) + private String name; + + @Column(name = "version", length = 20) + @Pattern(regexp = PfKey.VERSION_REGEXP) + private String version; @Column private String pdpGroup; @@ -90,7 +111,8 @@ public class JpaPolicyAudit extends PfConcept implements PfAuthorative getKeys() { - return getKey().getKeys(); + final List keyList = new ArrayList<>(); + keyList.add(getKey()); + return keyList; } @Override - public void clean() { - key.clean(); + public PfKey getKey() { + return new PfConceptKey(name, version); + } + @Override + public void clean() { pdpGroup = Assertions.validateStringParameter("pdpGroup", pdpGroup, PfReferenceKey.LOCAL_NAME_REGEXP); pdpType = Assertions.validateStringParameter("pdpType", pdpType, PfReferenceKey.LOCAL_NAME_REGEXP); user = Assertions.validateStringParameter("user", user, PfReferenceKey.LOCAL_NAME_REGEXP); } + + @Override + public BeanValidationResult validate(@NonNull String fieldName) { + BeanValidationResult result = super.validate(fieldName); + if (PfKey.NULL_KEY_NAME.equals(name)) { + result.addResult("name", name, ValidationStatus.INVALID, Validated.IS_NULL); + } + return result; + } } diff --git a/models-pap/src/main/java/org/onap/policy/models/pap/persistence/provider/PolicyAuditProvider.java b/models-pap/src/main/java/org/onap/policy/models/pap/persistence/provider/PolicyAuditProvider.java deleted file mode 100644 index ec759d34d..000000000 --- a/models-pap/src/main/java/org/onap/policy/models/pap/persistence/provider/PolicyAuditProvider.java +++ /dev/null @@ -1,146 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nordix Foundation. - * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * 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.pap.persistence.provider; - -import java.time.Instant; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import javax.ws.rs.core.Response; -import lombok.Builder; -import lombok.Data; -import lombok.NonNull; -import org.apache.commons.lang3.StringUtils; -import org.onap.policy.common.parameters.BeanValidationResult; -import org.onap.policy.models.base.PfModelRuntimeException; -import org.onap.policy.models.dao.PfDao; -import org.onap.policy.models.dao.PfFilterParametersIntfc; -import org.onap.policy.models.pap.concepts.PolicyAudit; -import org.onap.policy.models.pap.concepts.PolicyAudit.AuditAction; -import org.onap.policy.models.pap.persistence.concepts.JpaPolicyAudit; - -/** - * Provider for Policy Audit. - * - * @author Adheli Tavares (adheli.tavares@est.tech) - * - */ -public class PolicyAuditProvider { - - private static final Integer DEFAULT_MAX_RECORDS = 100; - private static final Integer DEFAULT_MIN_RECORDS = 10; - - /** - * Create audit records. - * - * @param audits list of policy audit - */ - public void createAuditRecords(@NonNull PfDao dao, @NonNull final List audits) { - List jpaAudits = audits.stream().map(JpaPolicyAudit::new).collect(Collectors.toList()); - - var result = new BeanValidationResult("createAuditRecords", jpaAudits); - - var count = 0; - for (JpaPolicyAudit jpaAudit : jpaAudits) { - result.addResult(jpaAudit.validate(String.valueOf(count++))); - } - - if (!result.isValid()) { - throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, result.getResult()); - } - - dao.createCollection(jpaAudits); - } - - /** - * Collect audit records based on filters at {@link AuditFilter}. - * - * @param auditFilter {@link AuditFilter} object with filters for search - * @return list of {@link PolicyAudit} records - */ - public List getAuditRecords(@NonNull PfDao dao, @NonNull AuditFilter auditFilter) { - if (auditFilter.getRecordNum() < 1) { - auditFilter.setRecordNum(DEFAULT_MIN_RECORDS); - } else if (auditFilter.getRecordNum() > DEFAULT_MAX_RECORDS) { - auditFilter.setRecordNum(DEFAULT_MAX_RECORDS); - } - - return dao.getFiltered(JpaPolicyAudit.class, auditFilter).stream().map(JpaPolicyAudit::toAuthorative) - .collect(Collectors.toList()); - } - - /** - * Create a filter for looking for audit records. - * name - policy name - * version - policy version - * pdpGroup - PDP group that policy might be related - * action - type of action/operation realized on policy - * fromDate - start of period in case of time interval search - */ - @Data - @Builder - public static class AuditFilter implements PfFilterParametersIntfc { - private String name; - private String version; - private AuditAction action; - private String pdpGroup; - private Instant fromDate; - private Instant toDate; - private int recordNum; - @Builder.Default - private String sortOrder = "DESC"; - - // initialized lazily, if not set via the builder - private Map filterMap; - - @Override - public Instant getStartTime() { - return fromDate; - } - - @Override - public Instant getEndTime() { - return toDate; - } - - @Override - public Map getFilterMap() { - if (filterMap != null) { - return filterMap; - } - - filterMap = new HashMap<>(); - - if (StringUtils.isNotBlank(pdpGroup)) { - filterMap.put("pdpGroup", pdpGroup); - } - - if (action != null) { - filterMap.put("action", action); - } - - return filterMap; - } - } -} diff --git a/models-pap/src/test/java/org/onap/policy/models/pap/persistence/provider/PolicyAuditProviderTest.java b/models-pap/src/test/java/org/onap/policy/models/pap/persistence/provider/PolicyAuditProviderTest.java deleted file mode 100644 index 41c9b92a6..000000000 --- a/models-pap/src/test/java/org/onap/policy/models/pap/persistence/provider/PolicyAuditProviderTest.java +++ /dev/null @@ -1,234 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2021 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.pap.persistence.provider; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; - -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.TimeUnit; -import org.awaitility.Awaitility; -import org.eclipse.persistence.config.PersistenceUnitProperties; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.models.base.PfModelRuntimeException; -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.pap.concepts.PolicyAudit; -import org.onap.policy.models.pap.concepts.PolicyAudit.AuditAction; -import org.onap.policy.models.pap.persistence.provider.PolicyAuditProvider.AuditFilter; -import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; - -/** - * Class for unit testing {@link PolicyAuditProvider}. - * - * @author Adheli Tavares (adheli.tavares@est.tech) - * - */ -public class PolicyAuditProviderTest { - - private static final String FIELD_IS_NULL = "%s is marked .*ull but is null"; - private static final String GROUP_A = "groupA"; - private static final String GROUP_B = "groupB"; - private static final ToscaConceptIdentifier MY_POLICY = new ToscaConceptIdentifier("MyPolicy", "1.2.3"); - private static final ToscaConceptIdentifier MY_POLICY2 = new ToscaConceptIdentifier("MyPolicyB", "2.3.4"); - private static final Integer NUMBER_RECORDS = 10; - - private PfDao pfDao; - - /** - * Set up the DAO towards the database. - * - * @throws Exception on database errors - */ - @Before - public void setupDao() throws Exception { - final DaoParameters daoParameters = new DaoParameters(); - daoParameters.setPluginClass(DefaultPfDao.class.getName()); - - daoParameters.setPersistenceUnit("ToscaConceptTest"); - - Properties jdbcProperties = new Properties(); - jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_USER, "policy"); - jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_PASSWORD, "P01icY"); - - if (System.getProperty("USE-MARIADB") != null) { - jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_DRIVER, "org.mariadb.jdbc.Driver"); - jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_URL, "jdbc:mariadb://localhost:3306/policy"); - } else { - jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_DRIVER, "org.h2.Driver"); - jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_URL, "jdbc:h2:mem:PolicyAuditProviderTest"); - } - - daoParameters.setJdbcProperties(jdbcProperties); - - pfDao = new PfDaoFactory().createPfDao(daoParameters); - pfDao.init(daoParameters); - } - - @After - public void teardown() { - pfDao.close(); - } - - @Test - public void testCreatePolicyAudit() { - PolicyAuditProvider provider = new PolicyAuditProvider(); - - Instant date = Instant.now(); - provider.createAuditRecords(pfDao, generatePolicyAudits(date, GROUP_A, MY_POLICY)); - - List records = - provider.getAuditRecords(pfDao, AuditFilter.builder().recordNum(NUMBER_RECORDS).build()); - assertThat(records).hasSize(2); - - // as the start date is 10 min ahead of first record, shouldn't return any records - List emptyList = provider.getAuditRecords(pfDao, - AuditFilter.builder().fromDate(Instant.now().plusSeconds(600)).recordNum(600).build()); - assertThat(emptyList).isEmpty(); - } - - @Test - public void testCreatePolicyAuditInvalid() { - PolicyAuditProvider provider = new PolicyAuditProvider(); - - List audits = List.of(PolicyAudit.builder().pdpType("pdpType").action(AuditAction.DEPLOYMENT) - .timestamp(Instant.now()).build()); - - assertThrows(PfModelRuntimeException.class, () -> provider.createAuditRecords(pfDao, audits)); - - List records = - provider.getAuditRecords(pfDao, AuditFilter.builder().recordNum(NUMBER_RECORDS).build()); - assertThat(records).isEmpty(); - } - - @Test - public void testFilters() { - PolicyAuditProvider provider = new PolicyAuditProvider(); - - Instant date = Instant.now().truncatedTo(ChronoUnit.SECONDS); - provider.createAuditRecords(pfDao, generatePolicyAudits(date, GROUP_A, MY_POLICY)); - provider.createAuditRecords(pfDao, generatePolicyAudits(date, GROUP_B, MY_POLICY)); - provider.createAuditRecords(pfDao, generatePolicyAudits(date, GROUP_B, MY_POLICY2)); - Awaitility.await().pollDelay(3, TimeUnit.SECONDS).until(() -> { - return true; - }); - - List records = provider.getAuditRecords(pfDao, - AuditFilter.builder().fromDate(date).toDate(Instant.now()).recordNum(NUMBER_RECORDS).build()); - assertThat(records).hasSize(6); - - List recordsWithGroupB = provider.getAuditRecords(pfDao, - AuditFilter.builder().pdpGroup(GROUP_B).recordNum(NUMBER_RECORDS).build()); - assertThat(recordsWithGroupB).hasSize(4); - - List recordsWithActionDeploy = provider.getAuditRecords(pfDao, - AuditFilter.builder().action(AuditAction.DEPLOYMENT).recordNum(NUMBER_RECORDS).build()); - assertThat(recordsWithActionDeploy).hasSize(3); - - List recordsWithMyPolicy = provider.getAuditRecords(pfDao, AuditFilter.builder() - .name(MY_POLICY.getName()).version(MY_POLICY.getVersion()).recordNum(NUMBER_RECORDS).build()); - assertThat(recordsWithMyPolicy).hasSize(4); - } - - @Test - public void testLoadRecordsForLimit() { - PolicyAuditProvider provider = new PolicyAuditProvider(); - - List loadAudits = new ArrayList<>(); - - // going to create 102 records. - for (int i = 0; i <= 50; i++) { - loadAudits.addAll(generatePolicyAudits(Instant.now().plusSeconds(i), GROUP_A, MY_POLICY)); - } - - provider.createAuditRecords(pfDao, loadAudits); - - List records = - provider.getAuditRecords(pfDao, AuditFilter.builder().recordNum(NUMBER_RECORDS).build()); - assertThat(records).hasSize(10); - - // check that is being ordered - assertTrue(records.get(0).getTimestamp().isAfter(records.get(9).getTimestamp())); - assertEquals(loadAudits.get(loadAudits.size() - 1).getTimestamp(), records.get(0).getTimestamp()); - - // try to get 102 records should return 100 - records = provider.getAuditRecords(pfDao, AuditFilter.builder().recordNum(102).build()); - assertThat(records).hasSize(100); - - // try to get -1 records should return 10 - records = provider.getAuditRecords(pfDao, AuditFilter.builder().recordNum(-1).build()); - assertThat(records).hasSize(10); - } - - @Test - public void policyProviderExceptions() { - PolicyAuditProvider provider = new PolicyAuditProvider(); - - assertThatThrownBy(() -> { - provider.createAuditRecords(null, null); - }).hasMessageMatching(String.format(FIELD_IS_NULL, "dao")); - - assertThatThrownBy(() -> { - provider.createAuditRecords(pfDao, null); - }).hasMessageMatching(String.format(FIELD_IS_NULL, "audits")); - - assertThatThrownBy(() -> { - provider.getAuditRecords(null, AuditFilter.builder().build()); - }).hasMessageMatching(String.format(FIELD_IS_NULL, "dao")); - - assertThatThrownBy(() -> { - provider.getAuditRecords(pfDao, null); - }).hasMessageMatching(String.format(FIELD_IS_NULL, "auditFilter")); - } - - private List generatePolicyAudits(Instant date, String group, ToscaConceptIdentifier policy) { - // @formatter:off - PolicyAudit deploy = PolicyAudit.builder() - .pdpGroup(group) - .pdpType("pdpType") - .policy(policy) - .action(AuditAction.DEPLOYMENT) - .timestamp(date.truncatedTo(ChronoUnit.SECONDS)) - .build(); - - PolicyAudit undeploy = PolicyAudit.builder() - .pdpGroup(group) - .pdpType("pdpType") - .policy(policy) - .action(AuditAction.UNDEPLOYMENT) - .timestamp(date.plusSeconds(1).truncatedTo(ChronoUnit.SECONDS)) - .build(); - // @formatter:on - - return List.of(deploy, undeploy); - } -} diff --git a/models-pdp/src/main/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpStatistics.java b/models-pdp/src/main/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpStatistics.java index 0ff60b90f..45e63e404 100644 --- a/models-pdp/src/main/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpStatistics.java +++ b/models-pdp/src/main/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpStatistics.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2021 Nordix Foundation. * Modifications Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,15 +26,19 @@ package org.onap.policy.models.pdp.persistence.concepts; import java.io.Serializable; import java.time.Instant; +import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.Column; import javax.persistence.ElementCollection; -import javax.persistence.EmbeddedId; import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.Table; +import javax.persistence.TableGenerator; import javax.persistence.Temporal; import javax.persistence.TemporalType; import lombok.AllArgsConstructor; @@ -42,13 +47,15 @@ import lombok.EqualsAndHashCode; import lombok.NonNull; import org.apache.commons.lang3.builder.CompareToBuilder; import org.eclipse.persistence.annotations.Index; -import org.onap.policy.common.parameters.annotations.NotNull; +import org.onap.policy.common.parameters.BeanValidationResult; +import org.onap.policy.common.parameters.ValidationStatus; +import org.onap.policy.common.parameters.annotations.Pattern; import org.onap.policy.models.base.PfAuthorative; import org.onap.policy.models.base.PfConcept; -import org.onap.policy.models.base.PfGeneratedIdKey; +import org.onap.policy.models.base.PfConceptKey; import org.onap.policy.models.base.PfKey; import org.onap.policy.models.base.PfUtils; -import org.onap.policy.models.base.validation.annotations.VerifyKey; +import org.onap.policy.models.base.Validated; import org.onap.policy.models.pdp.concepts.PdpEngineWorkerStatistics; import org.onap.policy.models.pdp.concepts.PdpStatistics; @@ -67,10 +74,24 @@ import org.onap.policy.models.pdp.concepts.PdpStatistics; public class JpaPdpStatistics extends PfConcept implements PfAuthorative, Serializable { private static final long serialVersionUID = -7312974966820980659L; - @EmbeddedId - @VerifyKey - @NotNull - private PfGeneratedIdKey key; + @Id + @Column(name = "ID") + @GeneratedValue(strategy = GenerationType.TABLE, generator = "statisticsIdGen") + @TableGenerator( + name = "statisticsIdGen", + table = "sequence", + pkColumnName = "SEQ_NAME", + valueColumnName = "SEQ_COUNT", + pkColumnValue = "SEQ_GEN") + private Long generatedId; + + @Column(name = "name", length = 120) + @Pattern(regexp = PfKey.NAME_REGEXP) + private String name; + + @Column(name = "version", length = 20) + @Pattern(regexp = PfKey.VERSION_REGEXP) + private String version; @Column(precision = 3) @Temporal(TemporalType.TIMESTAMP) @@ -116,16 +137,8 @@ public class JpaPdpStatistics extends PfConcept implements PfAuthorative getKeys() { - return getKey().getKeys(); + final List keyList = new ArrayList<>(); + keyList.add(getKey()); + return keyList; + } + + @Override + public PfKey getKey() { + return new PfConceptKey(name, version); } @Override public void clean() { - key.clean(); pdpGroupName = pdpGroupName.trim(); pdpSubGroupName = pdpSubGroupName.trim(); if (engineStats != null) { @@ -255,4 +277,13 @@ public class JpaPdpStatistics extends PfConcept implements PfAuthorative getFilteredPdpStatistics(@NonNull final PfDao dao, - PdpFilterParameters filterParams) { - - if (filterParams.getRecordNum() <= 0) { - filterParams.setRecordNum(DEFAULT_RECORD_COUNT); - - } else if (filterParams.getRecordNum() > MAX_RECORD_COUNT) { - filterParams.setRecordNum(MAX_RECORD_COUNT); - } - - return asPdpStatisticsList(dao.getFiltered(JpaPdpStatistics.class, filterParams)); - } - - /** - * Creates PDP statistics. - * - * @param dao the DAO to use to access the database - * @param pdpStatisticsList a specification of the PDP statistics to create - * @return the PDP statistics created - * @throws PfModelException on errors creating PDP statistics - */ - public List createPdpStatistics(@NonNull final PfDao dao, - @NonNull final List pdpStatisticsList) throws PfModelException { - for (PdpStatistics pdpStatistics : pdpStatisticsList) { - var jpaPdpStatistics = new JpaPdpStatistics(); - jpaPdpStatistics.fromAuthorative(pdpStatistics); - BeanValidationResult validationResult = jpaPdpStatistics.validate("pdp statistics"); - if (!validationResult.isValid()) { - throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, validationResult.getResult()); - } - - dao.create(jpaPdpStatistics); - pdpStatistics.setGeneratedId(jpaPdpStatistics.getKey().getGeneratedId()); - } - - // Return the created PDP statistics - List pdpStatistics = new ArrayList<>(pdpStatisticsList.size()); - - for (PdpStatistics pdpStatisticsItem : pdpStatisticsList) { - var jpaPdpStatistics = - dao.get(JpaPdpStatistics.class, new PfGeneratedIdKey(pdpStatisticsItem.getPdpInstanceId(), - PfKey.NULL_KEY_VERSION, pdpStatisticsItem.getGeneratedId())); - pdpStatistics.add(jpaPdpStatistics.toAuthorative()); - } - return pdpStatistics; - } - - /** - * Updates PDP statistics. - * - * @param dao the DAO to use to access the database - * @param pdpStatisticsList a specification of the PDP statistics to update - * @return the PDP statistics updated - * @throws PfModelException on errors updating PDP statistics - */ - public List updatePdpStatistics(@NonNull final PfDao dao, - @NonNull final List pdpStatisticsList) throws PfModelException { - - for (PdpStatistics pdpStatistics : pdpStatisticsList) { - var jpaPdpStatistics = new JpaPdpStatistics(); - jpaPdpStatistics.fromAuthorative(pdpStatistics); - - BeanValidationResult validationResult = jpaPdpStatistics.validate("pdp statistics"); - if (!validationResult.isValid()) { - throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, validationResult.getResult()); - } - - dao.update(jpaPdpStatistics); - } - - // Return the created PDP statistics - List pdpStatistics = new ArrayList<>(pdpStatisticsList.size()); - - for (PdpStatistics pdpStatisticsItem : pdpStatisticsList) { - var jpaPdpStatistics = - dao.get(JpaPdpStatistics.class, new PfGeneratedIdKey(pdpStatisticsItem.getPdpInstanceId(), - PfKey.NULL_KEY_VERSION, pdpStatisticsItem.getGeneratedId())); - pdpStatistics.add(jpaPdpStatistics.toAuthorative()); - } - - return pdpStatistics; - } - - /** - * Delete a PDP statistics. - * - * @param dao the DAO to use to access the database - * @param name the name of the policy to get, null to get all PDP statistics - * @param timestamp the timeStamp of statistics to delete, null to delete all statistics record of given PDP - * @return the PDP statistics list deleted - * @throws PfModelException on errors deleting PDP statistics - */ - public List deletePdpStatistics(@NonNull final PfDao dao, @NonNull final String name, - final Instant timestamp) { - List pdpStatisticsListToDel = asPdpStatisticsList(dao.getFiltered(JpaPdpStatistics.class, - PfFilterParameters.builder().name(name).startTime(timestamp).endTime(timestamp).build())); - - pdpStatisticsListToDel.stream().forEach(s -> dao.delete(JpaPdpStatistics.class, - new PfGeneratedIdKey(s.getPdpInstanceId(), PfKey.NULL_KEY_VERSION, s.getGeneratedId()))); - - return pdpStatisticsListToDel; - } - - /** - * Convert JPA PDP statistics list to an PDP statistics list. - * - * @param jpaPdpStatisticsList the list to convert - * @return the PDP statistics list - */ - private List asPdpStatisticsList(List jpaPdpStatisticsList) { - return jpaPdpStatisticsList.stream().map(JpaPdpStatistics::toAuthorative).collect(Collectors.toList()); - } -} diff --git a/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpStatisticsTest.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpStatisticsTest.java index 7c0522ff9..505e3f685 100644 --- a/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpStatisticsTest.java +++ b/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/concepts/JpaPdpStatisticsTest.java @@ -2,6 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019-2021 Nordix Foundation. * Modifications Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,7 +32,6 @@ import static org.junit.Assert.assertTrue; import java.time.Instant; import java.util.ArrayList; import org.junit.Test; -import org.onap.policy.models.base.PfGeneratedIdKey; import org.onap.policy.models.pdp.concepts.PdpStatistics; /** @@ -41,14 +41,12 @@ public class JpaPdpStatisticsTest { @Test public void testConstructor() { - assertThatThrownBy(() -> new JpaPdpStatistics((PfGeneratedIdKey) null)).hasMessageContaining("key"); assertThatThrownBy(() -> new JpaPdpStatistics((JpaPdpStatistics) null)).hasMessageContaining("copyConcept"); assertThatThrownBy(() -> new JpaPdpStatistics((PdpStatistics) null)).hasMessageContaining("authorativeConcept"); assertNotNull(new JpaPdpStatistics()); - assertNotNull(new JpaPdpStatistics(new PfGeneratedIdKey())); PdpStatistics pdpStat = createPdpStatistics(); JpaPdpStatistics jpaPdpStat = new JpaPdpStatistics(createPdpStatistics()); diff --git a/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/provider/PdpStatisticsProviderTest.java b/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/provider/PdpStatisticsProviderTest.java deleted file mode 100644 index 90b85b5ae..000000000 --- a/models-pdp/src/test/java/org/onap/policy/models/pdp/persistence/provider/PdpStatisticsProviderTest.java +++ /dev/null @@ -1,280 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020-2021 Nordix Foundation. - * Modifications Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.models.pdp.persistence.provider; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Instant; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Properties; -import org.eclipse.persistence.config.PersistenceUnitProperties; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.models.base.Validated; -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.pdp.concepts.PdpEngineWorkerStatistics; -import org.onap.policy.models.pdp.concepts.PdpStatistics; - -public class PdpStatisticsProviderTest { - private static final String DAO_IS_NULL = "dao is marked .*ull but is null"; - private static final String LIST_IS_NULL = "pdpStatisticsList is marked .*ull but is null"; - private static final String GROUP0 = "group0"; - private static final String NAME = "name"; - private static final String GROUP = "group"; - private static final String SUBGROUP = "subgroup"; - private static final Instant TIMESTAMP1 = Instant.ofEpochSecond(1078884319); - private static final Instant TIMESTAMP2 = Instant.ofEpochSecond(1078884350); - - private PfDao pfDao; - - private List engineStats = new ArrayList<>(); - private PdpStatistics pdpStatistics11; - private PdpStatistics pdpStatistics12; - private PdpStatistics pdpStatistics22; - private PdpStatistics pdpStatistics31; - - // checkstyle complained about this as a local variable; had to make it a field - private long genId; - - /** - * Set up test Dao. - */ - @Before - public void setupDao() throws Exception { - final DaoParameters daoParameters = new DaoParameters(); - daoParameters.setPluginClass(DefaultPfDao.class.getName()); - - daoParameters.setPersistenceUnit("ToscaConceptTest"); - - Properties jdbcProperties = new Properties(); - jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_USER, "policy"); - jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_PASSWORD, "P01icY"); - - if (System.getProperty("USE-MARIADB") != null) { - jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_DRIVER, "org.mariadb.jdbc.Driver"); - jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_URL, "jdbc:mariadb://localhost:3306/policy"); - } else { - jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_DRIVER, "org.h2.Driver"); - jdbcProperties.setProperty(PersistenceUnitProperties.JDBC_URL, "jdbc:h2:mem:PdpStatisticsProviderTest"); - } - - daoParameters.setJdbcProperties(jdbcProperties); - - pfDao = new PfDaoFactory().createPfDao(daoParameters); - pfDao.init(daoParameters); - - genId = 1; - - pdpStatistics11 = new PdpStatistics(); - pdpStatistics11.setPdpInstanceId(NAME); - pdpStatistics11.setTimeStamp(TIMESTAMP1); - pdpStatistics11.setGeneratedId(genId++); - pdpStatistics11.setPdpGroupName(GROUP); - pdpStatistics11.setPdpSubGroupName(SUBGROUP); - pdpStatistics11.setPolicyDeployCount(2); - pdpStatistics11.setPolicyDeployFailCount(1); - pdpStatistics11.setPolicyDeploySuccessCount(1); - pdpStatistics11.setPolicyExecutedCount(2); - pdpStatistics11.setPolicyExecutedFailCount(1); - pdpStatistics11.setPolicyExecutedSuccessCount(1); - pdpStatistics11.setEngineStats(engineStats); - - pdpStatistics12 = new PdpStatistics(); - pdpStatistics12.setPdpInstanceId(NAME); - pdpStatistics12.setTimeStamp(TIMESTAMP2); - pdpStatistics12.setGeneratedId(genId++); - pdpStatistics12.setPdpGroupName(GROUP); - pdpStatistics12.setPdpSubGroupName(SUBGROUP); - pdpStatistics12.setPolicyDeployCount(2); - pdpStatistics12.setPolicyDeployFailCount(1); - pdpStatistics12.setPolicyDeploySuccessCount(1); - pdpStatistics12.setPolicyExecutedCount(2); - pdpStatistics12.setPolicyExecutedFailCount(1); - pdpStatistics12.setPolicyExecutedSuccessCount(1); - pdpStatistics12.setEngineStats(engineStats); - - pdpStatistics22 = new PdpStatistics(); - pdpStatistics22.setPdpInstanceId("name2"); - pdpStatistics22.setTimeStamp(TIMESTAMP2); - pdpStatistics22.setGeneratedId(genId++); - pdpStatistics22.setPdpGroupName(GROUP); - pdpStatistics22.setPdpSubGroupName(SUBGROUP); - pdpStatistics22.setPolicyDeployCount(2); - pdpStatistics22.setPolicyDeployFailCount(1); - pdpStatistics22.setPolicyDeploySuccessCount(1); - pdpStatistics22.setPolicyExecutedCount(2); - pdpStatistics22.setPolicyExecutedFailCount(1); - pdpStatistics22.setPolicyExecutedSuccessCount(1); - pdpStatistics22.setEngineStats(engineStats); - - pdpStatistics31 = new PdpStatistics(); - pdpStatistics31.setPdpInstanceId("name3"); - pdpStatistics31.setTimeStamp(TIMESTAMP1); - pdpStatistics31.setGeneratedId(genId++); - pdpStatistics31.setPdpGroupName(GROUP); - pdpStatistics31.setPdpSubGroupName(SUBGROUP); - pdpStatistics31.setPolicyDeployCount(2); - pdpStatistics31.setPolicyDeployFailCount(1); - pdpStatistics31.setPolicyDeploySuccessCount(1); - pdpStatistics31.setPolicyExecutedCount(2); - pdpStatistics31.setPolicyExecutedFailCount(1); - pdpStatistics31.setPolicyExecutedSuccessCount(1); - pdpStatistics31.setEngineStats(engineStats); - - List create = List.of(pdpStatistics11, pdpStatistics22, pdpStatistics31, pdpStatistics12); - List createdPdpStatisticsList = new PdpStatisticsProvider().createPdpStatistics(pfDao, create); - - // these should match AND be in the same order - assertThat(createdPdpStatisticsList).isEqualTo(create); - } - - @After - public void teardown() { - pfDao.close(); - } - - @Test - public void testNotOkPdpStatistics() { - PdpStatistics pdpStatisticsErr = new PdpStatistics(); - pdpStatisticsErr.setPdpInstanceId("NULL"); - pdpStatisticsErr.setPdpGroupName(GROUP); - ArrayList pdpStatisticsNullList = new ArrayList<>(); - pdpStatisticsNullList.add(pdpStatisticsErr); - - assertThatThrownBy(() -> { - new PdpStatisticsProvider().createPdpStatistics(pfDao, null); - }).hasMessageMatching(LIST_IS_NULL); - - assertThatThrownBy(() -> { - new PdpStatisticsProvider().updatePdpStatistics(pfDao, null); - }).hasMessageMatching(LIST_IS_NULL); - - assertThatThrownBy(() -> { - new PdpStatisticsProvider().createPdpStatistics(pfDao, pdpStatisticsNullList); - }).hasMessageContaining("pdp statistics").hasMessageContaining("key") - .hasMessageContaining(Validated.IS_A_NULL_KEY); - - assertThatThrownBy(() -> { - new PdpStatisticsProvider().updatePdpStatistics(pfDao, pdpStatisticsNullList); - }).hasMessageContaining("pdp statistics").hasMessageContaining("key") - .hasMessageContaining(Validated.IS_A_NULL_KEY); - } - - @Test - public void testGetFilteredPdpStatistics() throws Exception { - - assertThatThrownBy(() -> { - new PdpStatisticsProvider().getFilteredPdpStatistics(null, PdpFilterParameters.builder().build()); - }).hasMessageMatching(DAO_IS_NULL); - - List getPdpStatisticsList; - - // empty filter - should return everything - getPdpStatisticsList = new PdpStatisticsProvider().getFilteredPdpStatistics(pfDao, PdpFilterParameters - .builder().build()); - verifyEquals(getPdpStatisticsList, List.of(pdpStatistics11, pdpStatistics12, pdpStatistics22, pdpStatistics31)); - - // match on name - returns multiple records - getPdpStatisticsList = new PdpStatisticsProvider().getFilteredPdpStatistics(pfDao, PdpFilterParameters - .builder().name(NAME).group(GROUP).startTime(TIMESTAMP1).endTime(TIMESTAMP2).build()); - verifyEquals(getPdpStatisticsList, List.of(pdpStatistics11, pdpStatistics12)); - - // this name only has one record - getPdpStatisticsList = new PdpStatisticsProvider().getFilteredPdpStatistics(pfDao, PdpFilterParameters - .builder().name("name2").group(GROUP).startTime(TIMESTAMP1).endTime(TIMESTAMP2).build()); - verifyEquals(getPdpStatisticsList, List.of(pdpStatistics22)); - - // match on subgroup - getPdpStatisticsList = new PdpStatisticsProvider().getFilteredPdpStatistics(pfDao, - PdpFilterParameters.builder().name("name2").group(GROUP).subGroup(SUBGROUP) - .startTime(TIMESTAMP1).endTime(TIMESTAMP2).build()); - verifyEquals(getPdpStatisticsList, List.of(pdpStatistics22)); - - // only request one record - getPdpStatisticsList = new PdpStatisticsProvider().getFilteredPdpStatistics(pfDao, PdpFilterParameters - .builder().name(NAME).recordNum(1).build()); - verifyEquals(getPdpStatisticsList, List.of(pdpStatistics12)); - - // request too many records - getPdpStatisticsList = new PdpStatisticsProvider().getFilteredPdpStatistics(pfDao, PdpFilterParameters - .builder().name(NAME).recordNum(10000).build()); - verifyEquals(getPdpStatisticsList, List.of(pdpStatistics11, pdpStatistics12)); - - // group mismatch - getPdpStatisticsList = new PdpStatisticsProvider().getFilteredPdpStatistics(pfDao, PdpFilterParameters - .builder().name(NAME).group(GROUP0).startTime(TIMESTAMP1).endTime(TIMESTAMP2).build()); - assertThat(getPdpStatisticsList).isEmpty(); - - // subgroup mismatch - getPdpStatisticsList = new PdpStatisticsProvider().getFilteredPdpStatistics(pfDao, - PdpFilterParameters.builder().name("name2").group(GROUP).subGroup("subgroup2") - .startTime(TIMESTAMP1).endTime(TIMESTAMP2).build()); - assertThat(getPdpStatisticsList).isEmpty(); - } - - @Test - public void testUpdatePdpStatistics() throws Exception { - assertThatThrownBy(() -> { - new PdpStatisticsProvider().updatePdpStatistics(null, null); - }).hasMessageMatching(DAO_IS_NULL); - - pdpStatistics11.setPdpGroupName(GROUP0); - List update = List.of(pdpStatistics11); - List updatePdpStatisticsList = new PdpStatisticsProvider().updatePdpStatistics(pfDao, update); - - // these should match AND be in the same order - assertThat(updatePdpStatisticsList).isEqualTo(update); - } - - @Test - public void testDeletePdpStatistics() throws Exception { - assertThatThrownBy(() -> { - new PdpStatisticsProvider().deletePdpStatistics(null, null, null); - }).hasMessageMatching(DAO_IS_NULL); - - assertThatThrownBy(() -> { - new PdpStatisticsProvider().deletePdpStatistics(pfDao, null, null); - }).hasMessageMatching("name is marked .*ull but is null"); - - List deletedPdpStatisticsList = - new PdpStatisticsProvider().deletePdpStatistics(pfDao, NAME, null); - verifyEquals(deletedPdpStatisticsList, List.of(pdpStatistics12, pdpStatistics11)); - } - - private void verifyEquals(List list1, List list2) { - assertThat(sort(list1)).isEqualTo(sort(list2)); - } - - private List sort(List list1) { - List list2 = new ArrayList<>(list1); - Collections.sort(list2, (stat1, stat2) -> stat1.getGeneratedId().compareTo(stat2.getGeneratedId())); - - return list2; - } -} diff --git a/models-provider/src/main/java/org/onap/policy/models/provider/PolicyModelsProvider.java b/models-provider/src/main/java/org/onap/policy/models/provider/PolicyModelsProvider.java index 5cc5fc96b..f0a5382de 100644 --- a/models-provider/src/main/java/org/onap/policy/models/provider/PolicyModelsProvider.java +++ b/models-provider/src/main/java/org/onap/policy/models/provider/PolicyModelsProvider.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019-2022 Nordix Foundation. - * Modifications Copyright (C) 2020 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2020, 2022 Bell Canada. All rights reserved. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -22,7 +22,6 @@ package org.onap.policy.models.provider; -import java.time.Instant; import java.util.Collection; import java.util.List; import java.util.Map; @@ -30,15 +29,11 @@ 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.pap.concepts.PolicyAudit; -import org.onap.policy.models.pap.persistence.provider.PolicyAuditProvider.AuditFilter; import org.onap.policy.models.pdp.concepts.Pdp; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpGroupFilter; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus; -import org.onap.policy.models.pdp.concepts.PdpStatistics; import org.onap.policy.models.pdp.concepts.PdpSubGroup; -import org.onap.policy.models.pdp.persistence.provider.PdpFilterParameters; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierOptVersion; import org.onap.policy.models.tosca.authorative.concepts.ToscaEntityFilter; import org.onap.policy.models.tosca.authorative.concepts.ToscaEntityKey; @@ -378,46 +373,6 @@ public interface PolicyModelsProvider extends AutoCloseable { */ public PdpGroup deletePdpGroup(@NonNull final String name) throws PfModelException; - - /** - * Get filtered PdpStatistics. - * - * @param filterParams filter parameters - * @return the PDP statistics found - * @throws PfModelException on errors getting policies - */ - public List getFilteredPdpStatistics(PdpFilterParameters filterParams) throws PfModelException; - - /** - * Creates PDP statistics. - * - * @param pdpStatisticsList a specification of the PDP statistics to create - * @return the PDP statistics created - * @throws PfModelException on errors creating PDP statistics - */ - public List createPdpStatistics(@NonNull List pdpStatisticsList) - throws PfModelException; - - /** - * Updates PDP statistics. - * - * @param pdpStatisticsList a specification of the PDP statistics to update - * @return the PDP statistics updated - * @throws PfModelException on errors updating PDP statistics - */ - public List updatePdpStatistics(@NonNull List pdpStatisticsList) - throws PfModelException; - - /** - * Delete a PDP statistics. - * - * @param name the name of the policy to get, null to get all PDP statistics - * @param timestamp the timestamp of statistics to delete, null to delete all statistics record of given pdp - * @return the PDP statistics deleted - * @throws PfModelException on errors deleting PDP statistics - */ - public List deletePdpStatistics(@NonNull String name, Instant timestamp) throws PfModelException; - /** * Gets all policy deployments. * @@ -453,18 +408,4 @@ public interface PolicyModelsProvider extends AutoCloseable { */ public void cudPolicyStatus(Collection createObjs, Collection updateObjs, Collection deleteObjs); - - /** - * Creates records for audit actions on policies. - * - * @param auditRecords the objects to create - */ - public void createAuditRecords(@NonNull List auditRecords); - - /** - * Collect the audit records. - * @param auditFilter filter for search - * @return list of {@link PolicyAudit} or empty if none or not match with filter - */ - public List getAuditRecords(AuditFilter auditFilter); } diff --git a/models-provider/src/main/java/org/onap/policy/models/provider/impl/AbstractPolicyModelsProvider.java b/models-provider/src/main/java/org/onap/policy/models/provider/impl/AbstractPolicyModelsProvider.java index ffb470628..6747d9c49 100644 --- a/models-provider/src/main/java/org/onap/policy/models/provider/impl/AbstractPolicyModelsProvider.java +++ b/models-provider/src/main/java/org/onap/policy/models/provider/impl/AbstractPolicyModelsProvider.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2021-2022 Nordix Foundation. + * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +21,6 @@ package org.onap.policy.models.provider.impl; -import java.time.Instant; import java.util.Collection; import java.util.List; import java.util.Map; @@ -30,18 +30,12 @@ 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.pap.concepts.PolicyAudit; -import org.onap.policy.models.pap.persistence.provider.PolicyAuditProvider; -import org.onap.policy.models.pap.persistence.provider.PolicyAuditProvider.AuditFilter; import org.onap.policy.models.pdp.concepts.Pdp; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpGroupFilter; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus; -import org.onap.policy.models.pdp.concepts.PdpStatistics; import org.onap.policy.models.pdp.concepts.PdpSubGroup; -import org.onap.policy.models.pdp.persistence.provider.PdpFilterParameters; import org.onap.policy.models.pdp.persistence.provider.PdpProvider; -import org.onap.policy.models.pdp.persistence.provider.PdpStatisticsProvider; import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierOptVersion; @@ -279,33 +273,6 @@ public abstract class AbstractPolicyModelsProvider implements PolicyModelsProvid return new PdpProvider().deletePdpGroup(getPfDao(), name); } - @Override - public List getFilteredPdpStatistics(PdpFilterParameters filterParams) throws PfModelException { - assertInitialized(); - return new PdpStatisticsProvider().getFilteredPdpStatistics(getPfDao(), filterParams); - } - - @Override - public List createPdpStatistics(@NonNull final List pdpStatisticsList) - throws PfModelException { - assertInitialized(); - return new PdpStatisticsProvider().createPdpStatistics(getPfDao(), pdpStatisticsList); - } - - @Override - public List updatePdpStatistics(@NonNull final List pdpStatisticsList) - throws PfModelException { - assertInitialized(); - return new PdpStatisticsProvider().updatePdpStatistics(getPfDao(), pdpStatisticsList); - } - - @Override - public List deletePdpStatistics(@NonNull final String name, final Instant timestamp) - throws PfModelException { - assertInitialized(); - return new PdpStatisticsProvider().deletePdpStatistics(getPfDao(), name, timestamp); - } - @Override public List getAllPolicyStatus() throws PfModelException { assertInitialized(); @@ -332,18 +299,6 @@ public abstract class AbstractPolicyModelsProvider implements PolicyModelsProvid new PdpProvider().cudPolicyStatus(getPfDao(), createObjs, updateObjs, deleteObjs); } - @Override - public void createAuditRecords(List auditRecords) { - assertInitialized(); - new PolicyAuditProvider().createAuditRecords(getPfDao(), auditRecords); - } - - @Override - public List getAuditRecords(AuditFilter auditFilter) { - assertInitialized(); - return new PolicyAuditProvider().getAuditRecords(getPfDao(), auditFilter); - } - /** * Check if the model provider is initialized. */ 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 af03fdbcf..ed47ae0a0 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019-2021 Nordix Foundation. * Modifications Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2020 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2020, 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. 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 561ef5daa..ff3dae81a 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019-2022 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2020 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2020, 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,14 +22,11 @@ package org.onap.policy.models.provider.impl; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -37,22 +34,16 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.pap.concepts.PolicyAudit; -import org.onap.policy.models.pap.concepts.PolicyAudit.AuditAction; -import org.onap.policy.models.pap.persistence.provider.PolicyAuditProvider.AuditFilter; import org.onap.policy.models.pdp.concepts.Pdp; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpGroupFilter; -import org.onap.policy.models.pdp.concepts.PdpStatistics; import org.onap.policy.models.pdp.concepts.PdpSubGroup; import org.onap.policy.models.pdp.enums.PdpHealthStatus; import org.onap.policy.models.pdp.enums.PdpState; -import org.onap.policy.models.pdp.persistence.provider.PdpFilterParameters; 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.authorative.concepts.ToscaConceptIdentifier; -import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierOptVersion; import org.onap.policy.models.tosca.authorative.concepts.ToscaEntityFilter; import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate; import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeType; @@ -84,10 +75,6 @@ public class DatabasePolicyModelsProviderTest { private static final String VERSION_100 = "1.0.0"; - private static final Instant TIMESTAMP = Instant.EPOCH; - - private static final String ORDER = "DESC"; - private PolicyModelsProviderParameters parameters; private PolicyModelsProvider databaseProvider; @@ -282,18 +269,6 @@ public class DatabasePolicyModelsProviderTest { databaseProvider.deletePdpGroup(null); }).hasMessageMatching(NAME_IS_NULL); - assertThatThrownBy(() -> { - databaseProvider.createPdpStatistics(null); - }).hasMessageMatching("^pdpStatisticsList is marked .*on.*ull but is null$"); - - assertThatThrownBy(() -> { - databaseProvider.updatePdpStatistics(null); - }).hasMessageMatching("^pdpStatisticsList is marked .*on.*ull but is null$"); - - assertThatThrownBy(() -> { - databaseProvider.deletePdpStatistics(null, TIMESTAMP); - }).hasMessageMatching(NAME_IS_NULL); - databaseProvider.close(); } @@ -413,68 +388,6 @@ public class DatabasePolicyModelsProviderTest { }).hasMessage("delete of PDP group \"name:0.0.0\" failed, PDP group does not exist"); assertEquals(pdpGroup.getName(), databaseProvider.deletePdpGroup(GROUP).getName()); - - List statisticsArrayList = makePdpStatisticsList(); - - assertThat(databaseProvider.getFilteredPdpStatistics(PdpFilterParameters.builder().build())).isEmpty(); - assertThat(databaseProvider.createPdpStatistics(statisticsArrayList)).hasSize(1); - assertThat(databaseProvider.updatePdpStatistics(statisticsArrayList)).hasSize(1); - } - - @Test - public void testProviderMethodsStatistics() throws PfModelException { - databaseProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(parameters); - databaseProvider.createPdpStatistics(makePdpStatisticsList()); - - assertEquals(NAME, databaseProvider.getFilteredPdpStatistics(PdpFilterParameters.builder().build()).get(0) - .getPdpInstanceId()); - assertEquals(NAME, databaseProvider.getFilteredPdpStatistics( - PdpFilterParameters.builder().group(GROUP).build()).get(0).getPdpInstanceId()); - assertEquals(0, databaseProvider.getFilteredPdpStatistics( - PdpFilterParameters.builder().group(GROUP).startTime(Instant.now()).build()).size()); - assertEquals(NAME, databaseProvider - .getFilteredPdpStatistics(PdpFilterParameters.builder().group(GROUP).endTime(TIMESTAMP).build()) - .get(0).getPdpInstanceId()); - assertEquals(0, databaseProvider.getFilteredPdpStatistics(PdpFilterParameters.builder().group(GROUP) - .startTime(Instant.now()).endTime(Instant.now()).build()).size()); - - assertEquals(NAME, databaseProvider - .getFilteredPdpStatistics(PdpFilterParameters.builder().name(NAME).group(GROUP).build()).get(0) - .getPdpInstanceId()); - assertEquals(0, databaseProvider.getFilteredPdpStatistics(PdpFilterParameters.builder().name(NAME).group(GROUP) - .startTime(Instant.now()).endTime(Instant.now()).build()).size()); - - assertEquals(NAME, - databaseProvider.getFilteredPdpStatistics( - PdpFilterParameters.builder().name(NAME).group(GROUP).subGroup("type").build()) - .get(0).getPdpInstanceId()); - - assertEquals(0, databaseProvider.getFilteredPdpStatistics( - PdpFilterParameters.builder().name(NAME).group(GROUP).subGroup("type") - .startTime(Instant.now()).endTime(Instant.now()).build()).size()); - - assertEquals(NAME, databaseProvider.getFilteredPdpStatistics( - PdpFilterParameters.builder().name(NAME).group(GROUP).subGroup("type") - .sortOrder(ORDER).recordNum(1).build()).get(0).getPdpInstanceId()); - assertEquals(NAME, databaseProvider.getFilteredPdpStatistics( - PdpFilterParameters.builder().name(NAME).group(GROUP).subGroup("type") - .sortOrder(ORDER).recordNum(5).build()).get(0).getPdpInstanceId()); - assertEquals(0, databaseProvider.getFilteredPdpStatistics( - PdpFilterParameters.builder().name(NAME).group(GROUP).subGroup("type") - .startTime(Instant.now()).endTime(Instant.now()) - .sortOrder(ORDER).recordNum(5).build()).size()); - - assertEquals(NAME, databaseProvider.deletePdpStatistics(NAME, null).get(0).getPdpInstanceId()); - assertThat(databaseProvider.getFilteredPdpStatistics(PdpFilterParameters.builder().build())).isEmpty(); - - assertThat(databaseProvider.getAllPolicyStatus()).isEmpty(); - assertThat(databaseProvider.getAllPolicyStatus(new ToscaConceptIdentifierOptVersion("MyPolicy", null))) - .isEmpty(); - assertThat(databaseProvider.getGroupPolicyStatus(GROUP)).isEmpty(); - assertThatCode(() -> databaseProvider.cudPolicyStatus(null, null, null)) - .doesNotThrowAnyException(); - - databaseProvider.close(); } @Test @@ -550,27 +463,6 @@ public class DatabasePolicyModelsProviderTest { databaseProvider.close(); } - @Test - public void testCreateAuditRecords() throws PfModelException { - PolicyAudit audit = PolicyAudit.builder().action(AuditAction.DEPLOYMENT).pdpGroup(GROUP).pdpType(GROUP) - .policy(new ToscaConceptIdentifier(NAME, VERSION_100)).user("user").build(); - - databaseProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(parameters); - - databaseProvider.createAuditRecords(List.of(audit)); - List createdAudits = databaseProvider.getAuditRecords(AuditFilter.builder().recordNum(10).build()); - assertThat(createdAudits).hasSize(1); - - List emptyList = databaseProvider - .getAuditRecords(AuditFilter.builder().action(AuditAction.UNDEPLOYMENT).recordNum(10).build()); - assertThat(emptyList).isEmpty(); - - assertThatThrownBy(() -> databaseProvider.createAuditRecords(null)) - .hasMessageContaining("audits is marked non-null but is null"); - - databaseProvider.close(); - } - @Test public void testToscaNodeTemplateHandling() throws PfModelException { databaseProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(parameters); @@ -596,16 +488,6 @@ public class DatabasePolicyModelsProviderTest { databaseProvider.close(); } - private List makePdpStatisticsList() { - PdpStatistics pdpStatistics = new PdpStatistics(); - pdpStatistics.setPdpInstanceId(NAME); - pdpStatistics.setTimeStamp(TIMESTAMP); - pdpStatistics.setPdpGroupName(GROUP); - pdpStatistics.setPdpSubGroupName("type"); - List statisticsArrayList = List.of(pdpStatistics); - return statisticsArrayList; - } - private ToscaServiceTemplate makeNodeTemplate() { ToscaServiceTemplate serviceTemplate = new ToscaServiceTemplate(); serviceTemplate.setToscaDefinitionsVersion("sample:1.1.0"); diff --git a/models-provider/src/test/java/org/onap/policy/models/provider/impl/DummyBadProviderImpl.java b/models-provider/src/test/java/org/onap/policy/models/provider/impl/DummyBadProviderImpl.java index 410ecf26a..84331e905 100644 --- a/models-provider/src/test/java/org/onap/policy/models/provider/impl/DummyBadProviderImpl.java +++ b/models-provider/src/test/java/org/onap/policy/models/provider/impl/DummyBadProviderImpl.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019-2022 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2020 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2020, 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,8 +22,6 @@ package org.onap.policy.models.provider.impl; -import java.time.Instant; -import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -33,15 +31,11 @@ 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.pap.concepts.PolicyAudit; -import org.onap.policy.models.pap.persistence.provider.PolicyAuditProvider.AuditFilter; import org.onap.policy.models.pdp.concepts.Pdp; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpGroupFilter; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus; -import org.onap.policy.models.pdp.concepts.PdpStatistics; import org.onap.policy.models.pdp.concepts.PdpSubGroup; -import org.onap.policy.models.pdp.persistence.provider.PdpFilterParameters; import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierOptVersion; import org.onap.policy.models.tosca.authorative.concepts.ToscaEntityFilter; @@ -241,32 +235,6 @@ public class DummyBadProviderImpl implements PolicyModelsProvider { // do nothing } - @Override - public List getFilteredPdpStatistics(PdpFilterParameters filterParams) throws PfModelException { - // Not implemented - return null; - } - - @Override - public List createPdpStatistics(final List pdpStatisticsList) - throws PfModelException { - // Not implemented - return new ArrayList<>(); - } - - @Override - public List updatePdpStatistics(final List pdpStatisticsList) - throws PfModelException { - // Not implemented - return new ArrayList<>(); - } - - @Override - public List deletePdpStatistics(final String name, final Instant timestamp) { - // Not implemented - return null; - } - @Override public List getAllPolicyStatus() throws PfModelException { // Not implemented @@ -297,15 +265,4 @@ public class DummyBadProviderImpl implements PolicyModelsProvider { // Not implemented return null; } - - @Override - public void createAuditRecords(List auditRecords) { - // Not implemented - } - - @Override - public List getAuditRecords(AuditFilter auditFilter) { - // Not implemented - return null; - } } diff --git a/models-provider/src/test/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderImpl.java b/models-provider/src/test/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderImpl.java index dcc436a05..4b8f1b866 100644 --- a/models-provider/src/test/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderImpl.java +++ b/models-provider/src/test/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderImpl.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019-2022 Nordix Foundation. * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2020 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2020, 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ package org.onap.policy.models.provider.impl; -import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -34,15 +33,11 @@ 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; -import org.onap.policy.models.pap.concepts.PolicyAudit; -import org.onap.policy.models.pap.persistence.provider.PolicyAuditProvider.AuditFilter; import org.onap.policy.models.pdp.concepts.Pdp; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpGroupFilter; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus; -import org.onap.policy.models.pdp.concepts.PdpStatistics; import org.onap.policy.models.pdp.concepts.PdpSubGroup; -import org.onap.policy.models.pdp.persistence.provider.PdpFilterParameters; import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.provider.PolicyModelsProviderParameters; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierOptVersion; @@ -249,32 +244,6 @@ public class DummyPolicyModelsProviderImpl implements PolicyModelsProvider { return null; } - @Override - public List getFilteredPdpStatistics(PdpFilterParameters filterParams) throws PfModelException { - // Not implemented - return new ArrayList<>(); - } - - @Override - public List createPdpStatistics(final List pdpStatisticsList) - throws PfModelException { - // Not implemented - return new ArrayList<>(); - } - - @Override - public List updatePdpStatistics(final List pdpStatisticsList) - throws PfModelException { - // Not implemented - return new ArrayList<>(); - } - - @Override - public List deletePdpStatistics(final String name, final Instant timestamp) { - // Not implemented - return new ArrayList<>(); - } - @Override public List getAllPolicyStatus() throws PfModelException { // Not implemented @@ -300,17 +269,6 @@ public class DummyPolicyModelsProviderImpl implements PolicyModelsProvider { // Not implemented } - @Override - public void createAuditRecords(List auditRecords) { - // Not implemented - } - - @Override - public List getAuditRecords(AuditFilter auditFilter) { - // Not implemented - return new ArrayList<>(); - } - /** * Return a ToscaServicetemplate dummy response. * diff --git a/models-provider/src/test/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderTest.java b/models-provider/src/test/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderTest.java index ca4c2e573..628aef96e 100644 --- a/models-provider/src/test/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderTest.java +++ b/models-provider/src/test/java/org/onap/policy/models/provider/impl/DummyPolicyModelsProviderTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019-2021 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2020 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2020, 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,15 +30,12 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import java.time.Instant; import java.util.ArrayList; import org.junit.Test; import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.pap.persistence.provider.PolicyAuditProvider.AuditFilter; import org.onap.policy.models.pdp.concepts.Pdp; import org.onap.policy.models.pdp.concepts.PdpGroupFilter; import org.onap.policy.models.pdp.concepts.PdpSubGroup; -import org.onap.policy.models.pdp.persistence.provider.PdpFilterParameters; import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.provider.PolicyModelsProviderFactory; import org.onap.policy.models.provider.PolicyModelsProviderParameters; @@ -112,17 +109,6 @@ public class DummyPolicyModelsProviderTest { dummyProvider.updatePdpSubGroup("name", new PdpSubGroup()); dummyProvider.updatePdp("name", "type", new Pdp()); - dummyProvider.updatePdpStatistics(new ArrayList<>()); - assertThat(dummyProvider.getFilteredPdpStatistics(PdpFilterParameters.builder().name("name").build())) - .isEmpty(); - - assertTrue( - dummyProvider.getFilteredPdpStatistics( - PdpFilterParameters.builder().name("name") - .startTime(Instant.now()).endTime(Instant.now()).build()).isEmpty()); - assertTrue(dummyProvider.createPdpStatistics(null).isEmpty()); - assertTrue(dummyProvider.updatePdpStatistics(null).isEmpty()); - assertTrue(dummyProvider.deletePdpStatistics(null, Instant.now()).isEmpty()); assertThat(dummyProvider.getAllPolicyStatus()).isEmpty(); assertThat(dummyProvider.getAllPolicyStatus(new ToscaConceptIdentifierOptVersion("MyPolicy", @@ -130,8 +116,6 @@ public class DummyPolicyModelsProviderTest { assertThat(dummyProvider.getGroupPolicyStatus("name")).isEmpty(); assertThatCode(() -> dummyProvider.cudPolicyStatus(null, null, null)).doesNotThrowAnyException(); - assertThatCode(() -> dummyProvider.createAuditRecords(null)).doesNotThrowAnyException(); - assertThat(dummyProvider.getAuditRecords(AuditFilter.builder().recordNum(10).build())).isEmpty(); } @Test diff --git a/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyStatisticsPersistenceTest.java b/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyStatisticsPersistenceTest.java deleted file mode 100644 index abc08846a..000000000 --- a/models-provider/src/test/java/org/onap/policy/models/provider/impl/PolicyStatisticsPersistenceTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2021 Nordix Foundation. - * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.models.provider.impl; - -import static org.assertj.core.api.Assertions.assertThatCode; - -import java.time.Instant; -import java.util.Arrays; -import org.junit.Test; -import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.pdp.concepts.PdpStatistics; -import org.onap.policy.models.provider.PolicyModelsProvider; -import org.onap.policy.models.provider.PolicyModelsProviderFactory; -import org.onap.policy.models.provider.PolicyModelsProviderParameters; - -/** - * Test persistence of PDP statistics to and from the database. - */ -public class PolicyStatisticsPersistenceTest { - - @Test - public void testPdpStatiscticsPersistence() throws PfModelException { - // Try the test on three providers - for (int i = 0; i < 3; i++) { - try (PolicyModelsProvider databaseProvider = setupProvider()) { - testPdpStatiscticsPersistenceOneProvider(databaseProvider); - } - } - } - - public void testPdpStatiscticsPersistenceOneProvider(PolicyModelsProvider databaseProvider) { - PdpStatistics pdpStatistics = new PdpStatistics(); - pdpStatistics.setPdpInstanceId("TheInstance"); - pdpStatistics.setTimeStamp(Instant.now()); - - // Try creating three identical statistics instances - for (int i = 0; i < 3; i++) { - assertThatCode(() -> databaseProvider.createPdpStatistics(Arrays.asList(pdpStatistics))) - .doesNotThrowAnyException(); - } - - // Try creating three statistics instances with timestams incremented - for (int i = 0; i < 3; i++) { - pdpStatistics.setTimeStamp(pdpStatistics.getTimeStamp().plusSeconds(1)); - - assertThatCode(() -> databaseProvider.createPdpStatistics(Arrays.asList(pdpStatistics))) - .doesNotThrowAnyException(); - } - } - - private PolicyModelsProvider setupProvider() throws PfModelException { - PolicyModelsProviderParameters parameters = new PolicyModelsProviderParameters(); - - if (System.getProperty("USE-MARIADB") != null) { - parameters.setDatabaseDriver("org.mariadb.jdbc.Driver"); - parameters.setDatabaseUrl("jdbc:mariadb://localhost:3306/policy"); - } else { - parameters.setDatabaseDriver("org.h2.Driver"); - parameters.setDatabaseUrl("jdbc:h2:mem:PolicyStatisticsPersistenceTest"); - } - - parameters.setDatabaseUser("policy"); - parameters.setDatabasePassword("P01icY"); - parameters.setPersistenceUnit("ToscaConceptTest"); - - return new PolicyModelsProviderFactory().createPolicyModelsProvider(parameters); - } -} -- 2.16.6