Add support transaction in Statistics Providers 71/125671/2
authorFrancescoFioraEst <francesco.fiora@est.tech>
Tue, 2 Nov 2021 16:08:46 +0000 (16:08 +0000)
committerFrancescoFioraEst <francesco.fiora@est.tech>
Wed, 10 Nov 2021 12:58:26 +0000 (12:58 +0000)
Add support transaction
in ClElementStatisticsProvider and ParticipantStatisticsProvider

Issue-ID: POLICY-3801
Change-Id: Iaf9d55a268627f9d548afdf108476441b19e1413
Signed-off-by: FrancescoFioraEst <francesco.fiora@est.tech>
13 files changed:
models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ClElementStatisticsProvider.java
models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ParticipantStatisticsProvider.java
models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/ClElementStatisticsRepository.java [new file with mode: 0644]
models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/FilterRepository.java [new file with mode: 0644]
models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/FilterRepositoryImpl.java [new file with mode: 0644]
models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/ParticipantStatisticsRepository.java [new file with mode: 0644]
models/src/test/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ClElementStatisticsProviderTest.java
models/src/test/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ParticipantStatisticsProviderTest.java
runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/Application.java
runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/instantiation/ControlLoopInstantiationProviderTest.java
runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/monitoring/TestMonitoringProvider.java
runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/monitoring/rest/MonitoringQueryControllerTest.java
runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/SupervisionMessagesTest.java

index e5b062b..bdb0d4d 100644 (file)
 package org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider;
 
 import java.time.Instant;
-import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
 import java.util.stream.Collectors;
+import javax.ws.rs.core.Response.Status;
+import lombok.AllArgsConstructor;
 import lombok.NonNull;
 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ClElementStatistics;
 import org.onap.policy.clamp.controlloop.models.controlloop.persistence.concepts.JpaClElementStatistics;
+import org.onap.policy.clamp.controlloop.models.controlloop.persistence.repository.ClElementStatisticsRepository;
 import org.onap.policy.models.base.PfModelException;
 import org.onap.policy.models.base.PfReferenceTimestampKey;
 import org.onap.policy.models.dao.PfFilterParameters;
-import org.onap.policy.models.provider.PolicyModelsProviderParameters;
-import org.onap.policy.models.provider.impl.AbstractModelsProvider;
 import org.springframework.stereotype.Component;
+import org.springframework.transaction.annotation.Transactional;
 
 /**
  * This class provides the provision of information on control loop element statistics in the database to callers.
@@ -41,46 +42,34 @@ import org.springframework.stereotype.Component;
  * @author Ramesh Murugan Iyer (ramesh.murugan.iyer@est.tech)
  */
 @Component
-public class ClElementStatisticsProvider extends AbstractModelsProvider {
+@Transactional
+@AllArgsConstructor
+public class ClElementStatisticsProvider {
 
-    /**
-     * Create a provider for control loop element statistics.
-     *
-     * @param parameters the parameters for database access
-     * @throws PfModelException on initiation errors
-     */
-    public ClElementStatisticsProvider(@NonNull PolicyModelsProviderParameters parameters) throws PfModelException {
-        super(parameters);
-        this.init();
-    }
+    private ClElementStatisticsRepository clElementStatisticsRepository;
 
     /**
      * Creates control loop element statistics.
      *
      * @param clElementStatisticsList a specification of the CL element statistics to create
      * @return the clElement statistics created
-     * @throws PfModelException on errors creating clElement statistics
+     * @throws PfModelException on initiation errors
      */
     public List<ClElementStatistics> createClElementStatistics(
             @NonNull final List<ClElementStatistics> clElementStatisticsList) throws PfModelException {
 
-        List<JpaClElementStatistics> jpaClElementStatisticsList = ProviderUtils.getJpaAndValidate(
-                clElementStatisticsList, JpaClElementStatistics::new, "control loop element statistics");
+        try {
+            var jpaClElementStatisticsList = ProviderUtils.getJpaAndValidate(clElementStatisticsList,
+                    JpaClElementStatistics::new, "control loop element statistics");
 
-        jpaClElementStatisticsList.forEach(jpaClElementStatistics -> getPfDao().create(jpaClElementStatistics));
+            var jpaClElementStatisticsSaved = clElementStatisticsRepository.saveAll(jpaClElementStatisticsList);
 
-        // Return the created control loop element statistics
-        List<ClElementStatistics> elementStatistics = new ArrayList<>(clElementStatisticsList.size());
-
-        for (ClElementStatistics clElementStat : clElementStatisticsList) {
-            var jpaClElementStatistics = getPfDao().get(JpaClElementStatistics.class,
-                    new PfReferenceTimestampKey(clElementStat.getParticipantId().getName(),
-                            clElementStat.getParticipantId().getVersion(), clElementStat.getId().toString(),
-                            clElementStat.getTimeStamp()));
-            elementStatistics.add(jpaClElementStatistics.toAuthorative());
+            // Return the saved control loop element statistics
+            return asClElementStatisticsList(jpaClElementStatisticsSaved);
+        } catch (IllegalArgumentException e) {
+            throw new PfModelException(Status.INTERNAL_SERVER_ERROR, "Error in save control loop element statistics",
+                    e);
         }
-
-        return elementStatistics;
     }
 
     /**
@@ -101,22 +90,17 @@ public class ClElementStatisticsProvider extends AbstractModelsProvider {
      * @param id of the control loop element
      * @param timestamp timestamp of the statistics
      * @return the clElement statistics found
-     * @throws PfModelException on errors getting clElement statistics
      */
+    @Transactional(readOnly = true)
     public List<ClElementStatistics> getClElementStatistics(final String name, final String version, final String id,
-            final Instant timestamp) throws PfModelException {
-        List<ClElementStatistics> clElementStatistics = new ArrayList<>(1);
+            final Instant timestamp) {
         if (name != null && version != null && timestamp != null && id != null) {
-            clElementStatistics.add(getPfDao()
-                    .get(JpaClElementStatistics.class, new PfReferenceTimestampKey(name, version, id, timestamp))
-                    .toAuthorative());
-            return clElementStatistics;
+            return asClElementStatisticsList(clElementStatisticsRepository
+                    .findAllById(List.of(new PfReferenceTimestampKey(name, version, id, timestamp))));
         } else if (name != null) {
-            clElementStatistics.addAll(getFilteredClElementStatistics(name, version, null, null, null, "DESC", 0));
-        } else {
-            clElementStatistics.addAll(asClElementStatisticsList(getPfDao().getAll(JpaClElementStatistics.class)));
+            return getFilteredClElementStatistics(name, version, null, null, null, "DESC", 0);
         }
-        return clElementStatistics;
+        return asClElementStatisticsList(clElementStatisticsRepository.findAll());
     }
 
     /**
@@ -130,8 +114,8 @@ public class ClElementStatisticsProvider extends AbstractModelsProvider {
      * @param getRecordNum Total query count from database
      * @param filterMap the filters to apply to the get operation
      * @return the clElement statistics found
-     * @throws PfModelException on errors getting policies
      */
+    @Transactional(readOnly = true)
     public List<ClElementStatistics> getFilteredClElementStatistics(final String name, final String version,
             final Instant startTimeStamp, final Instant endTimeStamp, Map<String, Object> filterMap,
             final String sortOrder, final int getRecordNum) {
@@ -148,6 +132,7 @@ public class ClElementStatisticsProvider extends AbstractModelsProvider {
                 .recordNum(getRecordNum)
                 .build();
         // @formatter:on
-        return asClElementStatisticsList(getPfDao().getFiltered(JpaClElementStatistics.class, filterParams));
+        return asClElementStatisticsList(
+                clElementStatisticsRepository.getFiltered(JpaClElementStatistics.class, filterParams));
     }
 }
index fa27a41..06c7a11 100644 (file)
 package org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider;
 
 import java.time.Instant;
-import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
 import java.util.stream.Collectors;
+import javax.ws.rs.core.Response.Status;
+import lombok.AllArgsConstructor;
 import lombok.NonNull;
 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ParticipantStatistics;
 import org.onap.policy.clamp.controlloop.models.controlloop.persistence.concepts.JpaParticipantStatistics;
+import org.onap.policy.clamp.controlloop.models.controlloop.persistence.repository.ParticipantStatisticsRepository;
 import org.onap.policy.models.base.PfModelException;
 import org.onap.policy.models.base.PfTimestampKey;
 import org.onap.policy.models.dao.PfFilterParameters;
-import org.onap.policy.models.provider.PolicyModelsProviderParameters;
-import org.onap.policy.models.provider.impl.AbstractModelsProvider;
 import org.springframework.stereotype.Component;
+import org.springframework.transaction.annotation.Transactional;
 
 /**
  * This class provides the provision of information on participant statistics in the database to callers.
  */
 @Component
-public class ParticipantStatisticsProvider extends AbstractModelsProvider {
+@Transactional
+@AllArgsConstructor
+public class ParticipantStatisticsProvider {
 
-    /**
-     * Create a provider for control loops statistics.
-     *
-     * @param parameters the parameters for database access
-     * @throws PfModelException on initiation errors
-     */
-    public ParticipantStatisticsProvider(@NonNull PolicyModelsProviderParameters parameters) throws PfModelException {
-        super(parameters);
-        this.init();
-    }
+    private ParticipantStatisticsRepository participantStatisticsRepository;
 
     /**
      * Get Participant statistics.
@@ -59,20 +53,18 @@ public class ParticipantStatisticsProvider extends AbstractModelsProvider {
      * @param version the version of the participant statistics to get, null to get all stats for a name
      * @param timestamp the time stamp for the stats to get
      * @return the participant statistics found
-     * @throws PfModelException on errors getting participant statistics
      */
+    @Transactional(readOnly = true)
     public List<ParticipantStatistics> getParticipantStatistics(final String name, final String version,
-            final Instant timestamp) throws PfModelException {
+            final Instant timestamp) {
 
         if (name != null && version != null && timestamp != null) {
-            List<ParticipantStatistics> participantStatistics = new ArrayList<>(1);
-            participantStatistics.add(getPfDao()
-                    .get(JpaParticipantStatistics.class, new PfTimestampKey(name, version, timestamp)).toAuthorative());
-            return participantStatistics;
+            return asParticipantStatisticsList(
+                    participantStatisticsRepository.findAllById(List.of(new PfTimestampKey(name, version, timestamp))));
         } else if (name != null) {
             return getFilteredParticipantStatistics(name, version, timestamp, null, null, "DESC", 0);
         } else {
-            return asParticipantStatisticsList(getPfDao().getAll(JpaParticipantStatistics.class));
+            return asParticipantStatisticsList(participantStatisticsRepository.findAll());
         }
     }
 
@@ -87,8 +79,8 @@ public class ParticipantStatisticsProvider extends AbstractModelsProvider {
      * @param getRecordNum Total query count from database
      * @param filterMap the filters to apply to the get operation
      * @return the participant statistics found
-     * @throws PfModelException on errors getting policies
      */
+    @Transactional(readOnly = true)
     public List<ParticipantStatistics> getFilteredParticipantStatistics(final String name, final String version,
             final Instant startTimeStamp, final Instant endTimeStamp, Map<String, Object> filterMap,
             final String sortOrder, final int getRecordNum) {
@@ -106,7 +98,8 @@ public class ParticipantStatisticsProvider extends AbstractModelsProvider {
                 .build();
         // @formatter:on
 
-        return asParticipantStatisticsList(getPfDao().getFiltered(JpaParticipantStatistics.class, filterParams));
+        return asParticipantStatisticsList(
+                participantStatisticsRepository.getFiltered(JpaParticipantStatistics.class, filterParams));
     }
 
     /**
@@ -119,23 +112,17 @@ public class ParticipantStatisticsProvider extends AbstractModelsProvider {
     public List<ParticipantStatistics> createParticipantStatistics(
             @NonNull final List<ParticipantStatistics> participantStatisticsList) throws PfModelException {
 
-        List<JpaParticipantStatistics> jpaParticipantStatisticsList = ProviderUtils
-                .getJpaAndValidate(participantStatisticsList, JpaParticipantStatistics::new, "Participant Statistics");
-
-        jpaParticipantStatisticsList.forEach(jpaParticipantStatistics -> getPfDao().update(jpaParticipantStatistics));
+        try {
+            var jpaParticipantStatisticsList = ProviderUtils.getJpaAndValidate(participantStatisticsList,
+                    JpaParticipantStatistics::new, "Participant Statistics");
 
-        // Return the created participant statistics
-        List<ParticipantStatistics> participantStatistics = new ArrayList<>(participantStatisticsList.size());
+            var jpaParticipantStatisticsSaved = participantStatisticsRepository.saveAll(jpaParticipantStatisticsList);
 
-        for (ParticipantStatistics participantStatisticsItem : participantStatisticsList) {
-            var jpaParticipantStatistics = getPfDao().get(JpaParticipantStatistics.class,
-                    new PfTimestampKey(participantStatisticsItem.getParticipantId().getName(),
-                            participantStatisticsItem.getParticipantId().getVersion(),
-                            participantStatisticsItem.getTimeStamp()));
-            participantStatistics.add(jpaParticipantStatistics.toAuthorative());
+            // Return the saved participant statistics
+            return asParticipantStatisticsList(jpaParticipantStatisticsSaved);
+        } catch (IllegalArgumentException e) {
+            throw new PfModelException(Status.INTERNAL_SERVER_ERROR, "Error in save participant statistics", e);
         }
-
-        return participantStatistics;
     }
 
     /**
diff --git a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/ClElementStatisticsRepository.java b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/ClElementStatisticsRepository.java
new file mode 100644 (file)
index 0000000..1e07a4f
--- /dev/null
@@ -0,0 +1,32 @@
+/*-
+ * ============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.clamp.controlloop.models.controlloop.persistence.repository;
+
+import org.onap.policy.clamp.controlloop.models.controlloop.persistence.concepts.JpaClElementStatistics;
+import org.onap.policy.models.base.PfReferenceTimestampKey;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.stereotype.Repository;
+
+@Repository
+public interface ClElementStatisticsRepository
+        extends JpaRepository<JpaClElementStatistics, PfReferenceTimestampKey>, FilterRepository {
+
+}
diff --git a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/FilterRepository.java b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/FilterRepository.java
new file mode 100644 (file)
index 0000000..ce1f3d8
--- /dev/null
@@ -0,0 +1,53 @@
+/*-
+ * ============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.clamp.controlloop.models.controlloop.persistence.repository;
+
+import java.util.List;
+import org.onap.policy.models.base.PfConcept;
+import org.onap.policy.models.dao.PfFilterParametersIntfc;
+
+public interface FilterRepository {
+
+    /**
+     * Get an object from the database, referred to by concept key.
+     *
+     * @param <T> 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}, if name is null, all concepts
+     *        of type T are returned, if name is not null and version is null, all versions of that concept matching the
+     *        name are returned.
+     * @param filterParams filter parameters
+     * @return the objects that was retrieved from the database
+     */
+    <T extends PfConcept> List<T> getFiltered(Class<T> someClass, PfFilterParametersIntfc filterParams);
+
+    /**
+     * Get an object from the database, referred to by concept key.
+     *
+     * @param <T> 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}, if name is null, all concepts
+     *        of type T are returned, if name is not null and version is null, all versions of that concept matching the
+     *        name are returned.
+     * @param name the name of the object to get, null returns all objects
+     * @param version the version the object to get, null returns all objects for a specified name
+     * @return the objects that was retrieved from the database
+     */
+    <T extends PfConcept> List<T> getFiltered(Class<T> someClass, String name, String version);
+}
diff --git a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/FilterRepositoryImpl.java b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/FilterRepositoryImpl.java
new file mode 100644 (file)
index 0000000..0dc8fc3
--- /dev/null
@@ -0,0 +1,51 @@
+/*-
+ * ============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.clamp.controlloop.models.controlloop.persistence.repository;
+
+import java.util.List;
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+import org.onap.policy.models.base.PfConcept;
+import org.onap.policy.models.dao.PfDao;
+import org.onap.policy.models.dao.PfFilterParametersIntfc;
+import org.onap.policy.models.dao.impl.ProxyDao;
+import org.springframework.stereotype.Repository;
+
+@Repository
+public class FilterRepositoryImpl implements FilterRepository {
+
+    @PersistenceContext
+    private EntityManager entityManager;
+
+    protected PfDao getPfDao() {
+        return new ProxyDao(entityManager);
+    }
+
+    @Override
+    public <T extends PfConcept> List<T> getFiltered(Class<T> someClass, PfFilterParametersIntfc filterParams) {
+        return getPfDao().getFiltered(someClass, filterParams);
+    }
+
+    @Override
+    public <T extends PfConcept> List<T> getFiltered(Class<T> someClass, String name, String version) {
+        return getPfDao().getFiltered(someClass, name, version);
+    }
+}
diff --git a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/ParticipantStatisticsRepository.java b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/ParticipantStatisticsRepository.java
new file mode 100644 (file)
index 0000000..6fecd61
--- /dev/null
@@ -0,0 +1,32 @@
+/*-
+ * ============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.clamp.controlloop.models.controlloop.persistence.repository;
+
+import org.onap.policy.clamp.controlloop.models.controlloop.persistence.concepts.JpaParticipantStatistics;
+import org.onap.policy.models.base.PfTimestampKey;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.stereotype.Repository;
+
+@Repository
+public interface ParticipantStatisticsRepository
+        extends JpaRepository<JpaParticipantStatistics, PfTimestampKey>, FilterRepository {
+
+}
index a9ef914..cf4136d 100644 (file)
@@ -23,19 +23,23 @@ package org.onap.policy.clamp.controlloop.models.controlloop.persistence.provide
 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.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
 
 import java.time.Instant;
 import java.util.List;
-import java.util.concurrent.atomic.AtomicInteger;
-import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ClElementStatistics;
 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ClElementStatisticsList;
+import org.onap.policy.clamp.controlloop.models.controlloop.persistence.concepts.JpaClElementStatistics;
+import org.onap.policy.clamp.controlloop.models.controlloop.persistence.repository.ClElementStatisticsRepository;
 import org.onap.policy.common.utils.coder.Coder;
 import org.onap.policy.common.utils.coder.StandardCoder;
 import org.onap.policy.common.utils.resources.ResourceUtils;
-import org.onap.policy.models.provider.PolicyModelsProviderParameters;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
 
 class ClElementStatisticsProviderTest {
@@ -43,9 +47,6 @@ class ClElementStatisticsProviderTest {
     private static final Coder CODER = new StandardCoder();
     private static final String CL_ELEMENT_STATS_JSON = "src/test/resources/providers/TestClElementStatistics.json";
 
-    private static AtomicInteger dbNameCounter = new AtomicInteger();
-
-    private PolicyModelsProviderParameters parameters;
     private ClElementStatisticsProvider clElementStatisticsProvider;
     private ClElementStatisticsList inputClElementStats;
     private String originalJson = ResourceUtils.getResourceAsString(CL_ELEMENT_STATS_JSON);
@@ -58,22 +59,23 @@ class ClElementStatisticsProviderTest {
     @BeforeEach
     void beforeSetupDao() throws Exception {
 
-        parameters = new PolicyModelsProviderParameters();
-        parameters.setDatabaseDriver("org.h2.Driver");
-        parameters.setName("PolicyProviderParameterGroup");
-        parameters.setImplementation("org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl");
-        parameters.setDatabaseUrl("jdbc:h2:mem:clElementTestDb" + dbNameCounter.getAndIncrement());
-        parameters.setDatabaseUser("policy");
-        parameters.setDatabasePassword("P01icY");
-        parameters.setPersistenceUnit("ToscaConceptTest");
-
-        clElementStatisticsProvider = new ClElementStatisticsProvider(parameters);
         inputClElementStats = CODER.decode(originalJson, ClElementStatisticsList.class);
-    }
+        var clElementStatisticsRepository = mock(ClElementStatisticsRepository.class);
+
+        var jpaClElementStatisticsList = ProviderUtils.getJpaAndValidate(inputClElementStats.getClElementStatistics(),
+                JpaClElementStatistics::new, "control loop element statistics");
+
+        for (var clElementStat : jpaClElementStatisticsList) {
+            when(clElementStatisticsRepository.findAllById(List.of(clElementStat.getKey())))
+                    .thenReturn(List.of(clElementStat));
+        }
+
+        when(clElementStatisticsRepository.saveAll(anyList())).thenReturn(jpaClElementStatisticsList);
+
+        when(clElementStatisticsRepository.getFiltered(eq(JpaClElementStatistics.class), any()))
+                .thenReturn(List.of(jpaClElementStatisticsList.get(0)));
 
-    @AfterEach
-    void teardown() {
-        clElementStatisticsProvider.close();
+        clElementStatisticsProvider = new ClElementStatisticsProvider(clElementStatisticsRepository);
     }
 
     @Test
@@ -84,10 +86,10 @@ class ClElementStatisticsProviderTest {
 
         ClElementStatisticsList createdClElementStats = new ClElementStatisticsList();
         createdClElementStats.setClElementStatistics(
-            clElementStatisticsProvider.createClElementStatistics(inputClElementStats.getClElementStatistics()));
+                clElementStatisticsProvider.createClElementStatistics(inputClElementStats.getClElementStatistics()));
 
         assertEquals(inputClElementStats.toString().replaceAll("\\s+", ""),
-            createdClElementStats.toString().replaceAll("\\s+", ""));
+                createdClElementStats.toString().replaceAll("\\s+", ""));
     }
 
     @Test
@@ -104,9 +106,9 @@ class ClElementStatisticsProviderTest {
         Instant instant = inputClElementStats.getClElementStatistics().get(0).getTimeStamp();
         String id = inputClElementStats.getClElementStatistics().get(0).getId().toString();
         assertEquals(1, clElementStatisticsProvider
-            .getClElementStatistics(identifier.getName(), identifier.getVersion(), id, instant).size());
+                .getClElementStatistics(identifier.getName(), identifier.getVersion(), id, instant).size());
 
         assertEquals(1, clElementStatisticsProvider
-            .getFilteredClElementStatistics("name2", "1.0.1", null, null, null, "DESC", 1).size());
+                .getFilteredClElementStatistics("name2", "1.0.1", null, null, null, "DESC", 1).size());
     }
 }
index 8191dd6..c6e1f81 100644 (file)
@@ -23,19 +23,23 @@ package org.onap.policy.clamp.controlloop.models.controlloop.persistence.provide
 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.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
 
 import java.time.Instant;
 import java.util.List;
-import java.util.concurrent.atomic.AtomicInteger;
-import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ParticipantStatistics;
 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ParticipantStatisticsList;
+import org.onap.policy.clamp.controlloop.models.controlloop.persistence.concepts.JpaParticipantStatistics;
+import org.onap.policy.clamp.controlloop.models.controlloop.persistence.repository.ParticipantStatisticsRepository;
 import org.onap.policy.common.utils.coder.Coder;
 import org.onap.policy.common.utils.coder.StandardCoder;
 import org.onap.policy.common.utils.resources.ResourceUtils;
-import org.onap.policy.models.provider.PolicyModelsProviderParameters;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
 
 class ParticipantStatisticsProviderTest {
@@ -44,32 +48,29 @@ class ParticipantStatisticsProviderTest {
     private static final Coder CODER = new StandardCoder();
     private static final String PARTICIPANT_STATS_JSON = "src/test/resources/providers/TestParticipantStatistics.json";
 
-    private static AtomicInteger dbNameCounter = new AtomicInteger();
-
-    private PolicyModelsProviderParameters parameters;
     private ParticipantStatisticsProvider participantStatisticsProvider;
     private ParticipantStatisticsList inputParticipantStatistics;
     private String originalJson = ResourceUtils.getResourceAsString(PARTICIPANT_STATS_JSON);
 
     @BeforeEach
     void beforeSetupDao() throws Exception {
+        var participantStatisticsRepository = mock(ParticipantStatisticsRepository.class);
+        participantStatisticsProvider = new ParticipantStatisticsProvider(participantStatisticsRepository);
+        inputParticipantStatistics = CODER.decode(originalJson, ParticipantStatisticsList.class);
 
-        parameters = new PolicyModelsProviderParameters();
-        parameters.setDatabaseDriver("org.h2.Driver");
-        parameters.setName("PolicyProviderParameterGroup");
-        parameters.setImplementation("org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl");
-        parameters.setDatabaseUrl("jdbc:h2:mem:participantStatisticsProviderTestDb" + dbNameCounter.getAndIncrement());
-        parameters.setDatabaseUser("policy");
-        parameters.setDatabasePassword("P01icY");
-        parameters.setPersistenceUnit("ToscaConceptTest");
+        var jpaParticipantStatisticsList =
+                ProviderUtils.getJpaAndValidate(inputParticipantStatistics.getStatisticsList(),
+                        JpaParticipantStatistics::new, "Participant Statistics");
 
-        participantStatisticsProvider = new ParticipantStatisticsProvider(parameters);
-        inputParticipantStatistics = CODER.decode(originalJson, ParticipantStatisticsList.class);
-    }
+        for (var participantStat : jpaParticipantStatisticsList) {
+            when(participantStatisticsRepository.findAllById(List.of(participantStat.getKey())))
+                    .thenReturn(List.of(participantStat));
+        }
+
+        when(participantStatisticsRepository.getFiltered(eq(JpaParticipantStatistics.class), any()))
+                .thenReturn(List.of(jpaParticipantStatisticsList.get(0)));
 
-    @AfterEach
-    void teardown() {
-        participantStatisticsProvider.close();
+        when(participantStatisticsRepository.saveAll(anyList())).thenReturn(jpaParticipantStatisticsList);
     }
 
     @Test
index 3f51f1f..64d1393 100644 (file)
@@ -30,7 +30,7 @@ import org.springframework.scheduling.annotation.EnableScheduling;
 
 @EnableScheduling
 @SpringBootApplication
-@EnableJpaRepositories
+@EnableJpaRepositories({"org.onap.policy.clamp.controlloop.models.controlloop.persistence.repository"})
 @ComponentScan({"org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider",
     "org.onap.policy.clamp.controlloop.runtime",
     "org.onap.policy.clamp.controlloop.common.rest"})
index 8fbd471..564109e 100644 (file)
@@ -26,6 +26,7 @@ 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.assertNull;
+import static org.mockito.Mockito.mock;
 
 import java.io.IOException;
 import java.util.ArrayList;
@@ -124,10 +125,8 @@ class ControlLoopInstantiationProviderTest {
         clProvider = new ControlLoopProvider(controlLoopParameters.getDatabaseProviderParameters());
         participantProvider = new ParticipantProvider(controlLoopParameters.getDatabaseProviderParameters());
 
-        var participantStatisticsProvider =
-                new ParticipantStatisticsProvider(controlLoopParameters.getDatabaseProviderParameters());
-        var clElementStatisticsProvider =
-                new ClElementStatisticsProvider(controlLoopParameters.getDatabaseProviderParameters());
+        var participantStatisticsProvider = Mockito.mock(ParticipantStatisticsProvider.class);
+        var clElementStatisticsProvider = mock(ClElementStatisticsProvider.class);
         commissioningProvider = new CommissioningProvider(new ServiceTemplateProvider(modelsProvider), clProvider, null,
                 participantProvider);
         var monitoringProvider =
index 2fcbf12..2233e86 100644 (file)
@@ -24,13 +24,19 @@ package org.onap.policy.clamp.controlloop.runtime.monitoring;
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
 import java.io.File;
 import java.time.Instant;
 import java.util.LinkedHashMap;
+import java.util.List;
 import java.util.Map;
 import java.util.UUID;
+import javax.ws.rs.core.Response;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeAll;
 import org.junit.jupiter.api.Test;
@@ -47,6 +53,7 @@ import org.onap.policy.clamp.controlloop.runtime.util.CommonTestData;
 import org.onap.policy.common.utils.coder.Coder;
 import org.onap.policy.common.utils.coder.CoderException;
 import org.onap.policy.common.utils.coder.StandardCoder;
+import org.onap.policy.models.base.PfModelRuntimeException;
 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
 
 class TestMonitoringProvider {
@@ -61,14 +68,23 @@ class TestMonitoringProvider {
             "src/test/resources/rest/monitoring/TestClElementStatistics_Invalid.json";
     private static final Coder CODER = new StandardCoder();
 
-    private static final String LIST_IS_NULL = ".*StatisticsList is marked .*ull but is null";
+    private static final String STAT_LIST_IS_NULL = ".*StatisticsList is marked .*ull but is null";
+    private static final String PARTICIPANT_STAT_LIST_IS_NULL =
+            "participantStatisticsList is marked .*null but is null";
+    private static final String NAME_IS_NULL = "name is marked .*null but is null";
+    private static final String CL_LIST_IS_NULL = "clElementStatisticsList is marked .*null but is null";
+    private static final String ID_VERSION1 = "1.001";
+    private static final String ID_VERSION2 = "1.002";
+    private static final String ID_NAME1 = "name1";
+    private static final String ID_NAME2 = "name2";
+    private static final String SORT_DESC = "DESC";
+    private static final String ID_NAME3 = "testCLName";
+    private static final String ID_INVALID_NAME = "invalidCLName";
     private static ParticipantStatisticsList inputParticipantStatistics;
     private static ParticipantStatisticsList invalidParticipantInput;
     private static ClElementStatisticsList inputClElementStatistics;
     private static ClElementStatisticsList invalidClElementInput;
 
-    private ParticipantStatisticsProvider participantStatisticsProvider = null;
-    private ClElementStatisticsProvider clElementStatisticsProvider = null;
     private ControlLoopProvider clProvider = null;
 
     @BeforeAll
@@ -84,12 +100,6 @@ class TestMonitoringProvider {
 
     @AfterEach
     void close() throws Exception {
-        if (participantStatisticsProvider != null) {
-            participantStatisticsProvider.close();
-        }
-        if (clElementStatisticsProvider != null) {
-            clElementStatisticsProvider.close();
-        }
         if (clProvider != null) {
             clProvider.close();
         }
@@ -97,20 +107,28 @@ class TestMonitoringProvider {
 
     @Test
     void testCreateParticipantStatistics() throws Exception {
+        var participantStatisticsProvider = mock(ParticipantStatisticsProvider.class);
+        var clElementStatisticsProvider = mock(ClElementStatisticsProvider.class);
         ClRuntimeParameterGroup parameters = CommonTestData.geParameterGroup("createparStat");
-        participantStatisticsProvider = new ParticipantStatisticsProvider(parameters.getDatabaseProviderParameters());
-        clElementStatisticsProvider = new ClElementStatisticsProvider(parameters.getDatabaseProviderParameters());
         clProvider = new ControlLoopProvider(parameters.getDatabaseProviderParameters());
         MonitoringProvider provider =
                 new MonitoringProvider(participantStatisticsProvider, clElementStatisticsProvider, clProvider);
+
+        when(participantStatisticsProvider.createParticipantStatistics(any()))
+                .thenReturn(inputParticipantStatistics.getStatisticsList());
+
+        when(participantStatisticsProvider.createParticipantStatistics(eq(null)))
+                .thenThrow(new PfModelRuntimeException(Response.Status.BAD_REQUEST, PARTICIPANT_STAT_LIST_IS_NULL));
+
         // Creating statistics data in db with null input
+
         assertThatThrownBy(() -> {
             provider.createParticipantStatistics(null);
-        }).hasMessageMatching(LIST_IS_NULL);
+        }).hasMessageMatching(STAT_LIST_IS_NULL);
 
         assertThatThrownBy(() -> {
             provider.createParticipantStatistics(invalidParticipantInput.getStatisticsList());
-        }).hasMessageMatching("participantStatisticsList is marked .*null but is null");
+        }).hasMessageMatching(PARTICIPANT_STAT_LIST_IS_NULL);
 
         // Creating statistics data from input json
         ParticipantStatisticsList createResponse =
@@ -123,32 +141,41 @@ class TestMonitoringProvider {
 
     @Test
     void testGetParticipantStatistics() throws Exception {
+        var participantStatisticsProvider = mock(ParticipantStatisticsProvider.class);
+        when(participantStatisticsProvider.getFilteredParticipantStatistics(eq(ID_NAME1), any(), any(), any(), eq(null),
+                eq(SORT_DESC), eq(0))).thenReturn(List.of(inputParticipantStatistics.getStatisticsList().get(0)));
+
+        when(participantStatisticsProvider.getFilteredParticipantStatistics(eq(ID_NAME1), any(),
+                eq(Instant.parse("2021-01-11T12:00:00.000Z")), eq(Instant.parse("2021-01-11T16:00:00.000Z")), eq(null),
+                eq(SORT_DESC), eq(0))).thenReturn(List.of());
+
+        when(participantStatisticsProvider.getFilteredParticipantStatistics(eq(ID_NAME2), any(), any(), any(), eq(null),
+                eq(SORT_DESC), eq(1))).thenReturn(List.of(inputParticipantStatistics.getStatisticsList().get(2)));
+
         ClRuntimeParameterGroup parameters = CommonTestData.geParameterGroup("getparStat");
-        participantStatisticsProvider = new ParticipantStatisticsProvider(parameters.getDatabaseProviderParameters());
-        clElementStatisticsProvider = new ClElementStatisticsProvider(parameters.getDatabaseProviderParameters());
         clProvider = new ControlLoopProvider(parameters.getDatabaseProviderParameters());
+        var clElementStatisticsProvider = mock(ClElementStatisticsProvider.class);
         MonitoringProvider provider =
                 new MonitoringProvider(participantStatisticsProvider, clElementStatisticsProvider, clProvider);
-
         provider.createParticipantStatistics(inputParticipantStatistics.getStatisticsList());
 
         assertThatThrownBy(() -> {
             provider.fetchFilteredParticipantStatistics(null, null, 0, null, null);
-        }).hasMessageMatching("name is marked .*null but is null");
+        }).hasMessageMatching(NAME_IS_NULL);
 
         // Fetch specific statistics record with name, version and record count
         ParticipantStatisticsList getResponse =
-                provider.fetchFilteredParticipantStatistics("name2", "1.001", 1, null, null);
+                provider.fetchFilteredParticipantStatistics(ID_NAME2, ID_VERSION1, 1, null, null);
         assertThat(getResponse.getStatisticsList()).hasSize(1);
         assertEquals(getResponse.getStatisticsList().get(0).toString().replaceAll("\\s+", ""),
                 inputParticipantStatistics.getStatisticsList().get(2).toString().replaceAll("\\s+", ""));
 
         // Fetch statistics using timestamp
-        getResponse = provider.fetchFilteredParticipantStatistics("name1", "1.001", 0, null,
+        getResponse = provider.fetchFilteredParticipantStatistics(ID_NAME1, ID_VERSION1, 0, null,
                 Instant.parse("2021-01-10T15:00:00.000Z"));
         assertThat(getResponse.getStatisticsList()).hasSize(1);
 
-        getResponse = provider.fetchFilteredParticipantStatistics("name1", "1.001", 0,
+        getResponse = provider.fetchFilteredParticipantStatistics(ID_NAME1, ID_VERSION1, 0,
                 Instant.parse("2021-01-11T12:00:00.000Z"), Instant.parse("2021-01-11T16:00:00.000Z"));
 
         assertThat(getResponse.getStatisticsList()).isEmpty();
@@ -156,21 +183,27 @@ class TestMonitoringProvider {
 
     @Test
     void testCreateClElementStatistics() throws Exception {
+        var clElementStatisticsProvider = mock(ClElementStatisticsProvider.class);
+        when(clElementStatisticsProvider.createClElementStatistics(any()))
+                .thenReturn(inputClElementStatistics.getClElementStatistics());
+
+        when(clElementStatisticsProvider.createClElementStatistics(eq(null)))
+                .thenThrow(new PfModelRuntimeException(Response.Status.BAD_REQUEST, CL_LIST_IS_NULL));
+
         ClRuntimeParameterGroup parameters = CommonTestData.geParameterGroup("createelemstat");
-        participantStatisticsProvider = new ParticipantStatisticsProvider(parameters.getDatabaseProviderParameters());
-        clElementStatisticsProvider = new ClElementStatisticsProvider(parameters.getDatabaseProviderParameters());
         clProvider = new ControlLoopProvider(parameters.getDatabaseProviderParameters());
 
+        var participantStatisticsProvider = mock(ParticipantStatisticsProvider.class);
         MonitoringProvider provider =
                 new MonitoringProvider(participantStatisticsProvider, clElementStatisticsProvider, clProvider);
         // Creating statistics data in db with null input
         assertThatThrownBy(() -> {
             provider.createClElementStatistics(null);
-        }).hasMessageMatching(LIST_IS_NULL);
+        }).hasMessageMatching(STAT_LIST_IS_NULL);
 
         assertThatThrownBy(() -> {
             provider.createClElementStatistics(invalidClElementInput.getClElementStatistics());
-        }).hasMessageMatching("clElementStatisticsList is marked .*null but is null");
+        }).hasMessageMatching(CL_LIST_IS_NULL);
 
         // Creating clElement statistics data from input json
         ClElementStatisticsList createResponse =
@@ -183,42 +216,46 @@ class TestMonitoringProvider {
 
     @Test
     void testGetClElementStatistics() throws Exception {
+        var participantStatisticsProvider = mock(ParticipantStatisticsProvider.class);
+        var clElementStatisticsProvider = mock(ClElementStatisticsProvider.class);
         ClRuntimeParameterGroup parameters = CommonTestData.geParameterGroup("getelemstat");
-        participantStatisticsProvider = new ParticipantStatisticsProvider(parameters.getDatabaseProviderParameters());
-        clElementStatisticsProvider = new ClElementStatisticsProvider(parameters.getDatabaseProviderParameters());
         clProvider = new ControlLoopProvider(parameters.getDatabaseProviderParameters());
 
+        when(clElementStatisticsProvider.getFilteredClElementStatistics(eq(ID_NAME1), any(), any(), any(), anyMap(),
+                eq(SORT_DESC), eq(0)))
+                        .thenReturn(List.of(inputClElementStatistics.getClElementStatistics().get(0),
+                                inputClElementStatistics.getClElementStatistics().get(1)));
+
         MonitoringProvider provider =
                 new MonitoringProvider(participantStatisticsProvider, clElementStatisticsProvider, clProvider);
         assertThatThrownBy(() -> {
             provider.fetchFilteredClElementStatistics(null, null, null, null, null, 0);
-        }).hasMessageMatching("name is marked .*null but is null");
+        }).hasMessageMatching(NAME_IS_NULL);
 
         provider.createClElementStatistics(inputClElementStatistics.getClElementStatistics());
 
         ClElementStatisticsList getResponse =
-                provider.fetchFilteredClElementStatistics("name1", null, null, null, null, 0);
+                provider.fetchFilteredClElementStatistics(ID_NAME1, null, null, null, null, 0);
 
         assertThat(getResponse.getClElementStatistics()).hasSize(2);
         assertEquals(getResponse.getClElementStatistics().get(0).toString().replaceAll("\\s+", ""),
                 inputClElementStatistics.getClElementStatistics().get(0).toString().replaceAll("\\s+", ""));
 
         // Fetch specific statistics record with name, id and record count
-        getResponse = provider.fetchFilteredClElementStatistics("name1", "1.001",
+        getResponse = provider.fetchFilteredClElementStatistics(ID_NAME1, ID_VERSION1,
                 "709c62b3-8918-41b9-a747-d21eb79c6c20", null, null, 0);
         assertThat(getResponse.getClElementStatistics()).hasSize(2);
 
         // Fetch statistics using timestamp
-        getResponse = provider.fetchFilteredClElementStatistics("name1", "1.001", null,
+        getResponse = provider.fetchFilteredClElementStatistics(ID_NAME1, ID_VERSION1, null,
                 Instant.parse("2021-01-10T13:45:00.000Z"), null, 0);
         assertThat(getResponse.getClElementStatistics()).hasSize(2);
     }
 
     @Test
     void testGetParticipantStatsPerCL() throws Exception {
-        ClRuntimeParameterGroup parameters = CommonTestData.geParameterGroup("getparStatCL");
-        participantStatisticsProvider = new ParticipantStatisticsProvider(parameters.getDatabaseProviderParameters());
-        clElementStatisticsProvider = new ClElementStatisticsProvider(parameters.getDatabaseProviderParameters());
+        var participantStatisticsProvider = mock(ParticipantStatisticsProvider.class);
+        var clElementStatisticsProvider = mock(ClElementStatisticsProvider.class);
         var mockClProvider = Mockito.mock(ControlLoopProvider.class);
         var provider =
                 new MonitoringProvider(participantStatisticsProvider, clElementStatisticsProvider, mockClProvider);
@@ -227,56 +264,63 @@ class TestMonitoringProvider {
 
         var controlLoop = new ControlLoop();
         var element = new ControlLoopElement();
-        element.setParticipantId(new ToscaConceptIdentifier("name1", "1.001"));
+        element.setParticipantId(new ToscaConceptIdentifier(ID_NAME1, ID_VERSION1));
         controlLoop.setElements(Map.of(UUID.randomUUID(), element));
-        when(mockClProvider.getControlLoop(new ToscaConceptIdentifier("testName", "1.001")))
-                .thenReturn(controlLoop);
+        when(mockClProvider.getControlLoop(new ToscaConceptIdentifier(ID_NAME2, ID_VERSION1))).thenReturn(controlLoop);
+
+        when(participantStatisticsProvider.getFilteredParticipantStatistics(eq(ID_NAME1), eq(ID_VERSION1), any(), any(),
+                eq(null), eq(SORT_DESC), eq(0)))
+                        .thenReturn(List.of(inputParticipantStatistics.getStatisticsList().get(0),
+                                inputParticipantStatistics.getStatisticsList().get(1)));
 
-        ParticipantStatisticsList getResponse = provider.fetchParticipantStatsPerControlLoop("testName", "1.001");
+        ParticipantStatisticsList getResponse = provider.fetchParticipantStatsPerControlLoop(ID_NAME2, ID_VERSION1);
         assertThat(getResponse.getStatisticsList()).hasSize(2);
         assertEquals(getResponse.getStatisticsList().get(0).toString().replaceAll("\\s+", ""),
                 inputParticipantStatistics.getStatisticsList().get(0).toString().replaceAll("\\s+", ""));
-        assertThat(provider.fetchParticipantStatsPerControlLoop("invalidCLName", "1.002").getStatisticsList())
+        assertThat(provider.fetchParticipantStatsPerControlLoop(ID_INVALID_NAME, ID_VERSION2).getStatisticsList())
                 .isEmpty();
     }
 
     @Test
     void testClElementStatsPerCL() throws Exception {
         // Setup a dummy Control loop data
-        ControlLoopElement mockClElement = new ControlLoopElement();
+        var mockClElement = new ControlLoopElement();
         mockClElement.setId(inputClElementStatistics.getClElementStatistics().get(0).getId());
         mockClElement.setParticipantId(new ToscaConceptIdentifier(
                 inputClElementStatistics.getClElementStatistics().get(0).getParticipantId().getName(),
                 inputClElementStatistics.getClElementStatistics().get(0).getParticipantId().getVersion()));
-        ControlLoop mockCL = new ControlLoop();
+        var mockCL = new ControlLoop();
         mockCL.setElements(new LinkedHashMap<>());
         mockCL.getElements().put(mockClElement.getId(), mockClElement);
 
-        ClRuntimeParameterGroup parameters = CommonTestData.geParameterGroup("getelemstatPerCL");
-        participantStatisticsProvider = new ParticipantStatisticsProvider(parameters.getDatabaseProviderParameters());
-        clElementStatisticsProvider = new ClElementStatisticsProvider(parameters.getDatabaseProviderParameters());
-        ControlLoopProvider mockClProvider = Mockito.mock(ControlLoopProvider.class);
+        var participantStatisticsProvider = mock(ParticipantStatisticsProvider.class);
+        var clElementStatisticsProvider = mock(ClElementStatisticsProvider.class);
+        var mockClProvider = Mockito.mock(ControlLoopProvider.class);
         var monitoringProvider =
                 new MonitoringProvider(participantStatisticsProvider, clElementStatisticsProvider, mockClProvider);
 
         // Mock controlloop data to be returned for the given CL Id
-        when(mockClProvider.getControlLoop(new ToscaConceptIdentifier("testCLName", "1.001"))).thenReturn(mockCL);
+        when(mockClProvider.getControlLoop(new ToscaConceptIdentifier(ID_NAME3, ID_VERSION1))).thenReturn(mockCL);
+
+        when(clElementStatisticsProvider.getFilteredClElementStatistics(eq(ID_NAME1), eq(ID_VERSION1), any(), any(),
+                anyMap(), eq(SORT_DESC), eq(0)))
+                        .thenReturn(List.of(inputClElementStatistics.getClElementStatistics().get(0),
+                                inputClElementStatistics.getClElementStatistics().get(1)));
 
         monitoringProvider.createClElementStatistics(inputClElementStatistics.getClElementStatistics());
 
         ClElementStatisticsList getResponse =
-                monitoringProvider.fetchClElementStatsPerControlLoop("testCLName", "1.001");
+                monitoringProvider.fetchClElementStatsPerControlLoop(ID_NAME3, ID_VERSION1);
 
         assertThat(getResponse.getClElementStatistics()).hasSize(2);
         assertEquals(getResponse.getClElementStatistics().get(1).toString().replaceAll("\\s+", ""),
                 inputClElementStatistics.getClElementStatistics().get(1).toString().replaceAll("\\s+", ""));
 
-        assertThat(
-                monitoringProvider.fetchClElementStatsPerControlLoop("invalidCLName", "1.002").getClElementStatistics())
-                        .isEmpty();
+        assertThat(monitoringProvider.fetchClElementStatsPerControlLoop(ID_INVALID_NAME, ID_VERSION2)
+                .getClElementStatistics()).isEmpty();
 
         Map<String, ToscaConceptIdentifier> clElementIds =
-                monitoringProvider.getAllClElementsIdPerControlLoop("testCLName", "1.001");
+                monitoringProvider.getAllClElementsIdPerControlLoop(ID_NAME3, ID_VERSION1);
         assertThat(clElementIds)
                 .containsKey(inputClElementStatistics.getClElementStatistics().get(0).getId().toString());
     }
index 77742ae..eaf8246 100644 (file)
@@ -141,7 +141,12 @@ class MonitoringQueryControllerTest extends CommonRestController {
 
         assertNotNull(result1);
         assertThat(result1.getClElementStatistics()).hasSize(2);
-        assertEquals(result1.getClElementStatistics().get(0), clElementStatisticsList.getClElementStatistics().get(0));
+
+        var clElementStat0 = clElementStatisticsList.getClElementStatistics().get(0);
+        for (var clElement : result1.getClElementStatistics()) {
+            assertEquals(clElement.getParticipantId().asConceptKey(), clElementStat0.getParticipantId().asConceptKey());
+            assertEquals(clElement.getId(), clElementStat0.getId());
+        }
 
         // Filter statistics based on timestamp
         Invocation.Builder invokeRequest2 = super.sendRequest(CLELEMENT_STATS_ENDPOINT + "?name="
@@ -155,7 +160,7 @@ class MonitoringQueryControllerTest extends CommonRestController {
 
         assertNotNull(result2);
         assertThat(result2.getClElementStatistics()).hasSize(1);
-        assertEquals(result1.getClElementStatistics().get(0), clElementStatisticsList.getClElementStatistics().get(0));
+        assertEquals(result2.getClElementStatistics().get(0), clElementStat0);
     }
 
     @Test
@@ -178,7 +183,7 @@ class MonitoringQueryControllerTest extends CommonRestController {
 
         assertNotNull(result1);
         assertThat(result1.getStatisticsList()).hasSize(2);
-        assertEquals(result1.getStatisticsList().get(0), participantStatisticsList.getStatisticsList().get(0));
+        assertThat(result1.getStatisticsList()).contains(participantStatisticsList.getStatisticsList().get(0));
 
         // Filter statistics based on timestamp
         Invocation.Builder invokeRequest2 = super.sendRequest(PARTICIPANT_STATS_ENDPOINT + "?name="
@@ -191,7 +196,7 @@ class MonitoringQueryControllerTest extends CommonRestController {
 
         assertNotNull(result2);
         assertThat(result2.getStatisticsList()).hasSize(1);
-        assertEquals(result1.getStatisticsList().get(0), participantStatisticsList.getStatisticsList().get(0));
+        assertEquals(result2.getStatisticsList().get(0), participantStatisticsList.getStatisticsList().get(0));
     }
 
     @Test
index ade2723..93433f5 100644 (file)
@@ -76,10 +76,8 @@ class SupervisionMessagesTest extends CommonRestController {
 
         clProvider = new ControlLoopProvider(controlLoopParameters.getDatabaseProviderParameters());
 
-        var participantStatisticsProvider =
-                new ParticipantStatisticsProvider(controlLoopParameters.getDatabaseProviderParameters());
-        var clElementStatisticsProvider =
-                new ClElementStatisticsProvider(controlLoopParameters.getDatabaseProviderParameters());
+        var participantStatisticsProvider = mock(ParticipantStatisticsProvider.class);
+        var clElementStatisticsProvider = mock(ClElementStatisticsProvider.class);
         var monitoringProvider =
                 new MonitoringProvider(participantStatisticsProvider, clElementStatisticsProvider, clProvider);
         var participantProvider = new ParticipantProvider(controlLoopParameters.getDatabaseProviderParameters());