diff options
24 files changed, 515 insertions, 239 deletions
diff --git a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ClElementStatisticsProvider.java b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ClElementStatisticsProvider.java index bdb0d4d9b..867c34aad 100644 --- a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ClElementStatisticsProvider.java +++ b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ClElementStatisticsProvider.java @@ -59,7 +59,7 @@ public class ClElementStatisticsProvider { @NonNull final List<ClElementStatistics> clElementStatisticsList) throws PfModelException { try { - var jpaClElementStatisticsList = ProviderUtils.getJpaAndValidate(clElementStatisticsList, + var jpaClElementStatisticsList = ProviderUtils.getJpaAndValidateList(clElementStatisticsList, JpaClElementStatistics::new, "control loop element statistics"); var jpaClElementStatisticsSaved = clElementStatisticsRepository.saveAll(jpaClElementStatisticsList); @@ -67,8 +67,7 @@ public class ClElementStatisticsProvider { // 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); + throw new PfModelException(Status.BAD_REQUEST, "Error in save control loop element statistics", e); } } diff --git a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ControlLoopProvider.java b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ControlLoopProvider.java index b4f99a51e..a61b97fa8 100644 --- a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ControlLoopProvider.java +++ b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ControlLoopProvider.java @@ -125,7 +125,7 @@ public class ControlLoopProvider extends AbstractModelsProvider { public List<ControlLoop> createControlLoops(@NonNull final List<ControlLoop> controlLoops) throws PfModelException { List<JpaControlLoop> jpaControlLoopList = - ProviderUtils.getJpaAndValidate(controlLoops, JpaControlLoop::new, "control loop"); + ProviderUtils.getJpaAndValidateList(controlLoops, JpaControlLoop::new, "control loop"); jpaControlLoopList.forEach(jpaControlLoop -> getPfDao().create(jpaControlLoop)); @@ -151,7 +151,7 @@ public class ControlLoopProvider extends AbstractModelsProvider { public List<ControlLoop> updateControlLoops(@NonNull final List<ControlLoop> controlLoops) throws PfModelException { List<JpaControlLoop> jpaControlLoopList = - ProviderUtils.getJpaAndValidate(controlLoops, JpaControlLoop::new, "control loop"); + ProviderUtils.getJpaAndValidateList(controlLoops, JpaControlLoop::new, "control loop"); // Return the created control loops List<ControlLoop> returnControlLoops = new ArrayList<>(controlLoops.size()); diff --git a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ParticipantProvider.java b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ParticipantProvider.java index dd669a6d8..2a6f21c07 100644 --- a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ParticipantProvider.java +++ b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ParticipantProvider.java @@ -20,36 +20,30 @@ package org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider; -import java.util.ArrayList; import java.util.List; -import java.util.stream.Collectors; -import javax.ws.rs.core.Response; +import java.util.Optional; +import javax.ws.rs.core.Response.Status; +import lombok.AllArgsConstructor; import lombok.NonNull; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.Participant; import org.onap.policy.clamp.controlloop.models.controlloop.persistence.concepts.JpaParticipant; +import org.onap.policy.clamp.controlloop.models.controlloop.persistence.repository.ParticipantRepository; 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.provider.PolicyModelsProviderParameters; -import org.onap.policy.models.provider.impl.AbstractModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaTypedEntityFilter; import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; /** * This class provides information on participant concepts in the database to callers. */ +@Transactional +@AllArgsConstructor @Component -public class ParticipantProvider extends AbstractModelsProvider { - /** - * Create a provider for participants. - * - * @param parameters the parameters for database access - * @throws PfModelException on initiation errors - */ - public ParticipantProvider(@NonNull PolicyModelsProviderParameters parameters) throws PfModelException { - super(parameters); - this.init(); - } +public class ParticipantProvider { + + private ParticipantRepository participantRepository; /** * Get participants. @@ -59,74 +53,73 @@ public class ParticipantProvider extends AbstractModelsProvider { * @return the participants found * @throws PfModelException on errors getting participants */ + @Transactional(readOnly = true) public List<Participant> getParticipants(final String name, final String version) throws PfModelException { - return asParticipantList(getPfDao().getFiltered(JpaParticipant.class, name, version)); + return ProviderUtils.asEntityList(participantRepository.getFiltered(JpaParticipant.class, name, version)); } /** - * Get filtered participants. + * Get all participants. * - * @param filter the filter for the participants to get * @return the participants found * @throws PfModelException on errors getting policies */ - public List<Participant> getFilteredParticipants(@NonNull final ToscaTypedEntityFilter<Participant> filter) { - - return filter.filter( - asParticipantList(getPfDao().getFiltered(JpaParticipant.class, filter.getName(), filter.getVersion()))); + @Transactional(readOnly = true) + public List<Participant> getParticipants() throws PfModelException { + return ProviderUtils.asEntityList(participantRepository.findAll()); } /** - * Creates participants. + * Get participant. * - * @param participants a specification of the participants to create - * @return the participants created - * @throws PfModelException on errors creating participants + * @param name the name of the participant to get + * @param version the version of the participant to get + * @return the participant found + * @throws PfModelException on errors getting participant */ - public List<Participant> createParticipants(@NonNull final List<Participant> participants) throws PfModelException { - - List<JpaParticipant> jpaParticipantList = - ProviderUtils.getJpaAndValidate(participants, JpaParticipant::new, "participant"); - - jpaParticipantList.forEach(jpaParticipant -> getPfDao().create(jpaParticipant)); - - // Return the created participants - List<Participant> returnParticipants = new ArrayList<>(participants.size()); - - for (Participant participant : participants) { - var jpaParticipant = getPfDao().get(JpaParticipant.class, - new PfConceptKey(participant.getName(), participant.getVersion())); - returnParticipants.add(jpaParticipant.toAuthorative()); + @Transactional(readOnly = true) + public Optional<Participant> findParticipant(@NonNull final String name, @NonNull final String version) + throws PfModelException { + try { + return participantRepository.findById(new PfConceptKey(name, version)).map(JpaParticipant::toAuthorative); + } catch (IllegalArgumentException e) { + throw new PfModelException(Status.BAD_REQUEST, "Error in find Participant", e); } - - return returnParticipants; } /** - * Updates participants. + * Get filtered participants. * - * @param participants a specification of the participants to update - * @return the participants updated - * @throws PfModelException on errors updating participants + * @param filter the filter for the participants to get + * @return the participants found + * @throws PfModelException on errors getting policies */ - public List<Participant> updateParticipants(@NonNull final List<Participant> participants) throws PfModelException { + @Transactional(readOnly = true) + public List<Participant> getFilteredParticipants(@NonNull final ToscaTypedEntityFilter<Participant> filter) + throws PfModelException { - List<JpaParticipant> jpaParticipantList = - ProviderUtils.getJpaAndValidate(participants, JpaParticipant::new, "participant"); - - jpaParticipantList.forEach(jpaParticipant -> getPfDao().update(jpaParticipant)); - - // Return the created participants - List<Participant> returnParticipants = new ArrayList<>(participants.size()); + return filter.filter(ProviderUtils.asEntityList( + participantRepository.getFiltered(JpaParticipant.class, filter.getName(), filter.getVersion()))); + } - for (Participant participant : participants) { - var jpaParticipant = getPfDao().get(JpaParticipant.class, - new PfConceptKey(participant.getName(), participant.getVersion())); - returnParticipants.add(jpaParticipant.toAuthorative()); + /** + * Saves participant. + * + * @param participant participant to save + * @return the participant created + * @throws PfModelException on errors creating participants + */ + public Participant saveParticipant(@NonNull final Participant participant) throws PfModelException { + try { + var result = participantRepository + .save(ProviderUtils.getJpaAndValidate(participant, JpaParticipant::new, "participant")); + + // Return the saved participant + return result.toAuthorative(); + } catch (IllegalArgumentException e) { + throw new PfModelException(Status.BAD_REQUEST, "Error in save Participant", e); } - - return returnParticipants; } /** @@ -137,30 +130,23 @@ public class ParticipantProvider extends AbstractModelsProvider { * @return the participant deleted * @throws PfModelRuntimeException on errors deleting participants */ - public Participant deleteParticipant(@NonNull final String name, @NonNull final String version) { - - var participantKey = new PfConceptKey(name, version); - - JpaParticipant jpaDeleteParticipant = getPfDao().get(JpaParticipant.class, participantKey); - - if (jpaDeleteParticipant == null) { - String errorMessage = - "delete of participant \"" + participantKey.getId() + "\" failed, participant does not exist"; - throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, errorMessage); + public Participant deleteParticipant(@NonNull final String name, @NonNull final String version) + throws PfModelException { + try { + var participantKey = new PfConceptKey(name, version); + + var jpaDeleteParticipantOpt = participantRepository.findById(participantKey); + + if (jpaDeleteParticipantOpt.isEmpty()) { + String errorMessage = + "delete of participant \"" + participantKey.getId() + "\" failed, participant does not exist"; + throw new PfModelRuntimeException(Status.BAD_REQUEST, errorMessage); + } + participantRepository.delete(jpaDeleteParticipantOpt.get()); + + return jpaDeleteParticipantOpt.get().toAuthorative(); + } catch (IllegalArgumentException e) { + throw new PfModelException(Status.BAD_REQUEST, "Error in delete Participant", e); } - - getPfDao().delete(jpaDeleteParticipant); - - return jpaDeleteParticipant.toAuthorative(); - } - - /** - * Convert JPA participant list to an authorative participant list. - * - * @param jpaParticipantList the list to convert - * @return the authorative list - */ - private List<Participant> asParticipantList(List<JpaParticipant> jpaParticipantList) { - return jpaParticipantList.stream().map(JpaParticipant::toAuthorative).collect(Collectors.toList()); } } diff --git a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ParticipantStatisticsProvider.java b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ParticipantStatisticsProvider.java index 06c7a11f8..811412205 100644 --- a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ParticipantStatisticsProvider.java +++ b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ParticipantStatisticsProvider.java @@ -57,15 +57,13 @@ public class ParticipantStatisticsProvider { @Transactional(readOnly = true) public List<ParticipantStatistics> getParticipantStatistics(final String name, final String version, final Instant timestamp) { - if (name != null && version != null && timestamp != null) { 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(participantStatisticsRepository.findAll()); } + return asParticipantStatisticsList(participantStatisticsRepository.findAll()); } /** @@ -113,7 +111,7 @@ public class ParticipantStatisticsProvider { @NonNull final List<ParticipantStatistics> participantStatisticsList) throws PfModelException { try { - var jpaParticipantStatisticsList = ProviderUtils.getJpaAndValidate(participantStatisticsList, + var jpaParticipantStatisticsList = ProviderUtils.getJpaAndValidateList(participantStatisticsList, JpaParticipantStatistics::new, "Participant Statistics"); var jpaParticipantStatisticsSaved = participantStatisticsRepository.saveAll(jpaParticipantStatisticsList); @@ -121,7 +119,7 @@ public class ParticipantStatisticsProvider { // Return the saved participant statistics return asParticipantStatisticsList(jpaParticipantStatisticsSaved); } catch (IllegalArgumentException e) { - throw new PfModelException(Status.INTERNAL_SERVER_ERROR, "Error in save participant statistics", e); + throw new PfModelException(Status.BAD_REQUEST, "Error in save participant statistics", e); } } diff --git a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ProviderUtils.java b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ProviderUtils.java index 3cce9c55c..3b0400b4f 100644 --- a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ProviderUtils.java +++ b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ProviderUtils.java @@ -23,6 +23,7 @@ package org.onap.policy.clamp.controlloop.models.controlloop.persistence.provide import java.util.ArrayList; import java.util.List; import java.util.function.Supplier; +import java.util.stream.Collectors; import javax.ws.rs.core.Response; import lombok.AccessLevel; import lombok.NoArgsConstructor; @@ -30,11 +31,20 @@ import org.onap.policy.common.parameters.BeanValidationResult; import org.onap.policy.models.base.PfAuthorative; import org.onap.policy.models.base.PfConcept; import org.onap.policy.models.base.PfModelRuntimeException; +import org.onap.policy.models.tosca.authorative.concepts.ToscaEntity; @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class ProviderUtils { - protected static <A, J extends PfConcept & PfAuthorative<A>> List<J> getJpaAndValidate( + /** + * Convert a list of concepts to a list of Jpa objects. + * + * @param authorativeConceptList the list of concepts + * @param jpaSupplier the Jpa Supplier + * @param conceptDescription the description used for validation result + * @return the list of Jpa objects + */ + public static <A, J extends PfConcept & PfAuthorative<A>> List<J> getJpaAndValidateList( List<A> authorativeConceptList, Supplier<J> jpaSupplier, String conceptDescription) { var validationResult = new BeanValidationResult(conceptDescription + " List", authorativeConceptList); @@ -53,4 +63,31 @@ public final class ProviderUtils { } return jpaConceptList; } + + protected static <A, J extends PfConcept & PfAuthorative<A>> J getJpaAndValidate(A authorativeConcept, + Supplier<J> jpaSupplier, String conceptDescription) { + var validationResult = new BeanValidationResult(conceptDescription, authorativeConcept); + + var jpaConcept = jpaSupplier.get(); + jpaConcept.fromAuthorative(authorativeConcept); + + validationResult.addResult(jpaConcept.validate(conceptDescription)); + + if (!validationResult.isValid()) { + throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, validationResult.getResult()); + } + return jpaConcept; + } + + /** + * Convert JPA control loop list to an authorative control loop list. + * + * @param <T> the type of TOSCA entity + * @param <J> the type of JPA TOSCA entity + * @param jpaEntityList the list to convert + * @return the authorative list + */ + public static <T extends ToscaEntity, J extends PfAuthorative<T>> List<T> asEntityList(List<J> jpaEntityList) { + return jpaEntityList.stream().map(J::toAuthorative).collect(Collectors.toList()); + } } diff --git a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/ControlLoopRepository.java b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/ControlLoopRepository.java new file mode 100644 index 000000000..1a5fd5a56 --- /dev/null +++ b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/ControlLoopRepository.java @@ -0,0 +1,31 @@ +/*- + * ============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.JpaControlLoop; +import org.onap.policy.models.base.PfConceptKey; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface ControlLoopRepository extends JpaRepository<JpaControlLoop, PfConceptKey>, FilterRepository { + +} diff --git a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/ParticipantRepository.java b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/ParticipantRepository.java new file mode 100644 index 000000000..671d23bbe --- /dev/null +++ b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/ParticipantRepository.java @@ -0,0 +1,31 @@ +/*- + * ============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.JpaParticipant; +import org.onap.policy.models.base.PfConceptKey; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface ParticipantRepository extends JpaRepository<JpaParticipant, PfConceptKey>, FilterRepository { + +} diff --git a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/ToscaNodeTemplateRepository.java b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/ToscaNodeTemplateRepository.java new file mode 100644 index 000000000..a8f830fed --- /dev/null +++ b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/ToscaNodeTemplateRepository.java @@ -0,0 +1,30 @@ +/*- + * ============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.models.base.PfConceptKey; +import org.onap.policy.models.tosca.simple.concepts.JpaToscaNodeTemplate; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ToscaNodeTemplateRepository + extends JpaRepository<JpaToscaNodeTemplate, PfConceptKey>, FilterRepository { + +} diff --git a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/ToscaNodeTemplatesRepository.java b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/ToscaNodeTemplatesRepository.java new file mode 100644 index 000000000..7bd7d1013 --- /dev/null +++ b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/ToscaNodeTemplatesRepository.java @@ -0,0 +1,29 @@ +/*- + * ============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.models.base.PfConceptKey; +import org.onap.policy.models.tosca.simple.concepts.JpaToscaNodeTemplates; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ToscaNodeTemplatesRepository extends JpaRepository<JpaToscaNodeTemplates, PfConceptKey> { + +} diff --git a/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/ToscaServiceTemplateRepository.java b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/ToscaServiceTemplateRepository.java new file mode 100644 index 000000000..a5d5fe766 --- /dev/null +++ b/models/src/main/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/ToscaServiceTemplateRepository.java @@ -0,0 +1,30 @@ +/*- + * ============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.models.base.PfConceptKey; +import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface ToscaServiceTemplateRepository + extends JpaRepository<JpaToscaServiceTemplate, PfConceptKey>, FilterRepository { + +} diff --git a/models/src/test/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ClElementStatisticsProviderTest.java b/models/src/test/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ClElementStatisticsProviderTest.java index cf4136d3e..82ce8d789 100644 --- a/models/src/test/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ClElementStatisticsProviderTest.java +++ b/models/src/test/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ClElementStatisticsProviderTest.java @@ -62,11 +62,13 @@ class ClElementStatisticsProviderTest { inputClElementStats = CODER.decode(originalJson, ClElementStatisticsList.class); var clElementStatisticsRepository = mock(ClElementStatisticsRepository.class); - var jpaClElementStatisticsList = ProviderUtils.getJpaAndValidate(inputClElementStats.getClElementStatistics(), - JpaClElementStatistics::new, "control loop element statistics"); + var jpaClElementStatisticsList = + ProviderUtils.getJpaAndValidateList(inputClElementStats.getClElementStatistics(), + JpaClElementStatistics::new, "control loop element statistics"); for (var clElementStat : jpaClElementStatisticsList) { - when(clElementStatisticsRepository.findAllById(List.of(clElementStat.getKey()))) + when(clElementStatisticsRepository.getById(eq(clElementStat.getKey()))).thenReturn(clElementStat); + when(clElementStatisticsRepository.findAllById(eq(List.of(clElementStat.getKey())))) .thenReturn(List.of(clElementStat)); } diff --git a/models/src/test/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ParticipantProviderTest.java b/models/src/test/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ParticipantProviderTest.java index 681ca96ce..9b48735f6 100644 --- a/models/src/test/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ParticipantProviderTest.java +++ b/models/src/test/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ParticipantProviderTest.java @@ -23,129 +23,127 @@ 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.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.jupiter.api.AfterEach; +import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.Participant; -import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ParticipantState; +import org.onap.policy.clamp.controlloop.models.controlloop.persistence.concepts.JpaParticipant; +import org.onap.policy.clamp.controlloop.models.controlloop.persistence.repository.ParticipantRepository; 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.base.PfConceptKey; import org.onap.policy.models.tosca.authorative.concepts.ToscaTypedEntityFilter; class ParticipantProviderTest { private static final Coder CODER = new StandardCoder(); - private static final String PARTICIPANT_JSON = - "src/test/resources/providers/TestParticipant.json"; + private static final String PARTICIPANT_JSON = "src/test/resources/providers/TestParticipant.json"; private static final String LIST_IS_NULL = ".*. is marked .*ull but is null"; - private static AtomicInteger dbNameCounter = new AtomicInteger(); - - private PolicyModelsProviderParameters parameters; - private ParticipantProvider participantProvider; private List<Participant> inputParticipants = new ArrayList<>(); - private Participant updateParticipants; + private List<JpaParticipant> jpaParticipantList; private String originalJson = ResourceUtils.getResourceAsString(PARTICIPANT_JSON); @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:participantProviderTestDb" + dbNameCounter.getAndIncrement()); - parameters.setDatabaseUser("policy"); - parameters.setDatabasePassword("P01icY"); - parameters.setPersistenceUnit("ToscaConceptTest"); - - participantProvider = new ParticipantProvider(parameters); inputParticipants.add(CODER.decode(originalJson, Participant.class)); - - } - - @AfterEach - void teardown() { - participantProvider.close(); + jpaParticipantList = ProviderUtils.getJpaAndValidateList(inputParticipants, JpaParticipant::new, "participant"); } @Test - void testParticipantCreate() throws Exception { + void testParticipantSave() throws Exception { + var participantRepository = mock(ParticipantRepository.class); + for (var participant : jpaParticipantList) { + when(participantRepository.getById(new PfConceptKey(participant.getName(), participant.getVersion()))) + .thenReturn(participant); + } + var participantProvider = new ParticipantProvider(participantRepository); + assertThatThrownBy(() -> { - participantProvider.createParticipants(null); + participantProvider.saveParticipant(null); }).hasMessageMatching(LIST_IS_NULL); - List<Participant> createdParticipants = new ArrayList<>(); - createdParticipants.addAll(participantProvider - .createParticipants(inputParticipants)); + when(participantRepository.save(any())).thenReturn(jpaParticipantList.get(0)); - assertEquals(createdParticipants.get(0), - inputParticipants.get(0)); - } + Participant savedParticipant = participantProvider.saveParticipant(inputParticipants.get(0)); + assertEquals(savedParticipant, inputParticipants.get(0)); + + when(participantRepository.save(any())).thenThrow(IllegalArgumentException.class); + assertThatThrownBy(() -> { + participantProvider.saveParticipant(inputParticipants.get(0)); + }).hasMessageMatching("Error in save Participant"); + } @Test void testGetControlLoops() throws Exception { + var participantRepository = mock(ParticipantRepository.class); + var participantProvider = new ParticipantProvider(participantRepository); - List<Participant> getResponse; - - //Return empty list when no data present in db - getResponse = participantProvider.getParticipants(null, null); + // Return empty list when no data present in db + List<Participant> getResponse = participantProvider.getParticipants(null, null); assertThat(getResponse).isEmpty(); - participantProvider.createParticipants(inputParticipants); String name = inputParticipants.get(0).getName(); String version = inputParticipants.get(0).getVersion(); + when(participantRepository.getFiltered(any(), eq(name), eq(version))) + .thenReturn(List.of(jpaParticipantList.get(0))); assertEquals(1, participantProvider.getParticipants(name, version).size()); - assertThat(participantProvider.getParticipants("invalid_name", - "1.0.1")).isEmpty(); + assertThat(participantProvider.getParticipants("invalid_name", "1.0.1")).isEmpty(); + + assertThat(participantProvider.findParticipant("invalid_name", "1.0.1")).isEmpty(); + + when(participantRepository.findAll()).thenReturn(jpaParticipantList); + assertThat(participantProvider.getParticipants()).hasSize(inputParticipants.size()); + + when(participantRepository.findById(any())).thenThrow(IllegalArgumentException.class); + + assertThatThrownBy(() -> { + participantProvider.findParticipant("notValid", "notValid"); + }).hasMessageMatching("Error in find Participant"); assertThatThrownBy(() -> { participantProvider.getFilteredParticipants(null); }).hasMessageMatching("filter is marked .*ull but is null"); + when(participantRepository.getFiltered(eq(JpaParticipant.class), eq(null), eq(null))) + .thenReturn(jpaParticipantList); + final ToscaTypedEntityFilter<Participant> filter = ToscaTypedEntityFilter.<Participant>builder() .type("org.onap.domain.pmsh.PMSHControlLoopDefinition").build(); assertEquals(1, participantProvider.getFilteredParticipants(filter).size()); - } - @Test - void testUpdateParticipant() throws Exception { - assertThatThrownBy(() -> { - participantProvider.updateParticipants(null); - }).hasMessageMatching("participants is marked .*ull but is null"); - - participantProvider.createParticipants(inputParticipants); - updateParticipants = inputParticipants.get(0); - updateParticipants.setParticipantState(ParticipantState.ACTIVE); - List<Participant> participantList = new ArrayList<>(); - participantList.add(updateParticipants); - List<Participant> updateResponse = new ArrayList<>(); - updateResponse = participantProvider.updateParticipants(participantList); - - assertEquals(ParticipantState.ACTIVE, updateResponse.get(0).getParticipantState()); } @Test void testDeleteParticipant() throws Exception { + var participantRepository = mock(ParticipantRepository.class); + var participantProvider = new ParticipantProvider(participantRepository); + assertThatThrownBy(() -> { participantProvider.deleteParticipant("Invalid_name", "1.0.1"); }).hasMessageMatching(".*.failed, participant does not exist"); - Participant deletedParticipant; - List<Participant> participantList = participantProvider.createParticipants(inputParticipants); String name = inputParticipants.get(0).getName(); String version = inputParticipants.get(0).getVersion(); - deletedParticipant = participantProvider.deleteParticipant(name, version); - assertEquals(participantList.get(0), deletedParticipant); + when(participantRepository.findById(any())).thenReturn(Optional.of(jpaParticipantList.get(0))); + + Participant deletedParticipant = participantProvider.deleteParticipant(name, version); + assertEquals(inputParticipants.get(0), deletedParticipant); + when(participantRepository.findById(any())).thenThrow(IllegalArgumentException.class); + assertThatThrownBy(() -> { + participantProvider.deleteParticipant(name, version); + }).hasMessageMatching("Error in delete Participant"); } } diff --git a/models/src/test/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ParticipantStatisticsProviderTest.java b/models/src/test/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ParticipantStatisticsProviderTest.java index c6e1f817d..16f4958a9 100644 --- a/models/src/test/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ParticipantStatisticsProviderTest.java +++ b/models/src/test/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/provider/ParticipantStatisticsProviderTest.java @@ -59,11 +59,12 @@ class ParticipantStatisticsProviderTest { inputParticipantStatistics = CODER.decode(originalJson, ParticipantStatisticsList.class); var jpaParticipantStatisticsList = - ProviderUtils.getJpaAndValidate(inputParticipantStatistics.getStatisticsList(), + ProviderUtils.getJpaAndValidateList(inputParticipantStatistics.getStatisticsList(), JpaParticipantStatistics::new, "Participant Statistics"); for (var participantStat : jpaParticipantStatisticsList) { - when(participantStatisticsRepository.findAllById(List.of(participantStat.getKey()))) + when(participantStatisticsRepository.getById(eq(participantStat.getKey()))).thenReturn(participantStat); + when(participantStatisticsRepository.findAllById(eq(List.of(participantStat.getKey())))) .thenReturn(List.of(participantStat)); } @@ -89,10 +90,9 @@ class ParticipantStatisticsProviderTest { @Test void testGetControlLoops() throws Exception { - List<ParticipantStatistics> getResponse; - // Return empty list when no data present in db - getResponse = participantStatisticsProvider.getParticipantStatistics(null, null, null); + List<ParticipantStatistics> getResponse = + participantStatisticsProvider.getParticipantStatistics(null, null, null); assertThat(getResponse).isEmpty(); participantStatisticsProvider.createParticipantStatistics(inputParticipantStatistics.getStatisticsList()); diff --git a/models/src/test/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/FilterRepositoryImplTest.java b/models/src/test/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/FilterRepositoryImplTest.java new file mode 100644 index 000000000..8b5357457 --- /dev/null +++ b/models/src/test/java/org/onap/policy/clamp/controlloop/models/controlloop/persistence/repository/FilterRepositoryImplTest.java @@ -0,0 +1,106 @@ +/*- + * ============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 static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoops; +import org.onap.policy.clamp.controlloop.models.controlloop.persistence.concepts.JpaControlLoop; +import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ProviderUtils; +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.dao.PfDao; +import org.onap.policy.models.dao.PfFilterParameters; +import org.onap.policy.models.provider.PolicyModelsProviderParameters; +import org.onap.policy.models.provider.impl.ModelsProvider; + +class FilterRepositoryImplTest { + private static final String CONTROL_LOOP_JSON = "src/test/resources/providers/TestControlLoops.json"; + private static final Coder CODER = new StandardCoder(); + private static final AtomicInteger dbNameCounter = new AtomicInteger(); + private static final String originalJson = ResourceUtils.getResourceAsString(CONTROL_LOOP_JSON); + private static List<JpaControlLoop> jpaControlLoops; + private PfDao pfDao; + + @BeforeEach + void beforeSetupDao() throws Exception { + var 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:controlLoopProviderTestDb" + dbNameCounter.getAndDecrement()); + parameters.setDatabaseUser("policy"); + parameters.setDatabasePassword("P01icY"); + parameters.setPersistenceUnit("ToscaConceptTest"); + + pfDao = ModelsProvider.init(parameters); + var inputControlLoops = CODER.decode(originalJson, ControlLoops.class); + jpaControlLoops = ProviderUtils.getJpaAndValidateList(inputControlLoops.getControlLoopList(), + JpaControlLoop::new, "ControlLoops"); + + pfDao.createCollection(jpaControlLoops); + } + + @Test + void testGetPfDao() { + assertThat(new FilterRepositoryImpl().getPfDao()).isNotNull(); + } + + @Test + void testGetFilteredParams() { + var filterRepositoryImpl = new FilterRepositoryImpl() { + @Override + protected PfDao getPfDao() { + return pfDao; + } + }; + var result = filterRepositoryImpl.getFiltered(JpaControlLoop.class, null, null); + assertThat(result).hasSize(2); + + result = filterRepositoryImpl.getFiltered(JpaControlLoop.class, jpaControlLoops.get(0).getName(), null); + assertThat(result).hasSize(1); + } + + @Test + void testGetFiltered() { + var filterRepositoryImpl = new FilterRepositoryImpl() { + @Override + protected PfDao getPfDao() { + return pfDao; + } + }; + + // @formatter:off + PfFilterParameters filterParams = PfFilterParameters + .builder() + .name(jpaControlLoops.get(0).getName()) + .build(); + // @formatter:on + + var result = filterRepositoryImpl.getFiltered(JpaControlLoop.class, filterParams); + assertThat(result).hasSize(1); + } +} diff --git a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/commissioning/CommissioningProvider.java b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/commissioning/CommissioningProvider.java index d055ba266..eac1ac305 100644 --- a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/commissioning/CommissioningProvider.java +++ b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/commissioning/CommissioningProvider.java @@ -104,7 +104,7 @@ public class CommissioningProvider { synchronized (lockit) { serviceTemplateProvider.createServiceTemplate(serviceTemplate); - List<Participant> participantList = participantProvider.getParticipants(null, null); + List<Participant> participantList = participantProvider.getParticipants(); if (!participantList.isEmpty()) { supervisionHandler.handleSendCommissionMessage(serviceTemplate.getName(), serviceTemplate.getVersion()); } @@ -137,7 +137,7 @@ public class CommissioningProvider { } synchronized (lockit) { - List<Participant> participantList = participantProvider.getParticipants(null, null); + List<Participant> participantList = participantProvider.getParticipants(); if (!participantList.isEmpty()) { supervisionHandler.handleSendDeCommissionMessage(); } @@ -145,8 +145,7 @@ public class CommissioningProvider { } var response = new CommissioningResponse(); - response.setAffectedControlLoopDefinitions( - Collections.singletonList(new ToscaConceptIdentifier(name, version))); + response.setAffectedControlLoopDefinitions(List.of(new ToscaConceptIdentifier(name, version))); return response; } @@ -262,13 +261,11 @@ public class CommissioningProvider { * @return the tosca service template * @throws PfModelException on errors getting tosca service template */ - public String getToscaServiceTemplateReduced(String name, String version) - throws PfModelException { + public String getToscaServiceTemplateReduced(String name, String version) throws PfModelException { var serviceTemplateList = serviceTemplateProvider.getServiceTemplateList(name, version); - List<ToscaServiceTemplate> filteredServiceTemplateList = filterToscaNodeTemplateInstance( - serviceTemplateList); + List<ToscaServiceTemplate> filteredServiceTemplateList = filterToscaNodeTemplateInstance(serviceTemplateList); if (filteredServiceTemplateList.isEmpty()) { throw new PfModelException(Status.BAD_REQUEST, "Invalid Service Template"); diff --git a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/instantiation/ControlLoopInstantiationProvider.java b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/instantiation/ControlLoopInstantiationProvider.java index 98ceacc3a..40d9b249d 100644 --- a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/instantiation/ControlLoopInstantiationProvider.java +++ b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/instantiation/ControlLoopInstantiationProvider.java @@ -350,7 +350,7 @@ public class ControlLoopInstantiationProvider { } synchronized (lockit) { - var participants = participantProvider.getParticipants(null, null); + var participants = participantProvider.getParticipants(); if (participants.isEmpty()) { throw new ControlLoopException(Status.BAD_REQUEST, "No participants registered"); } diff --git a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionHandler.java b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionHandler.java index f011d9392..7f0b85588 100644 --- a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionHandler.java +++ b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionHandler.java @@ -174,16 +174,15 @@ public class SupervisionHandler { public void handleParticipantMessage(ParticipantDeregister participantDeregisterMessage) { LOGGER.debug("Participant Deregister received {}", participantDeregisterMessage); try { - var participantList = - participantProvider.getParticipants(participantDeregisterMessage.getParticipantId().getName(), + var participantOpt = + participantProvider.findParticipant(participantDeregisterMessage.getParticipantId().getName(), participantDeregisterMessage.getParticipantId().getVersion()); - if (participantList != null) { - for (Participant participant : participantList) { - participant.setParticipantState(ParticipantState.TERMINATED); - participant.setHealthStatus(ParticipantHealthStatus.OFF_LINE); - } - participantProvider.updateParticipants(participantList); + if (participantOpt.isPresent()) { + var participant = participantOpt.get(); + participant.setParticipantState(ParticipantState.TERMINATED); + participant.setHealthStatus(ParticipantHealthStatus.OFF_LINE); + participantProvider.saveParticipant(participant); } } catch (PfModelException pfme) { LOGGER.warn("Model exception occured with participant id {}", @@ -202,15 +201,14 @@ public class SupervisionHandler { public void handleParticipantMessage(ParticipantUpdateAck participantUpdateAckMessage) { LOGGER.debug("Participant Update Ack received {}", participantUpdateAckMessage); try { - var participantList = - participantProvider.getParticipants(participantUpdateAckMessage.getParticipantId().getName(), + var participantOpt = + participantProvider.findParticipant(participantUpdateAckMessage.getParticipantId().getName(), participantUpdateAckMessage.getParticipantId().getVersion()); - if (participantList != null) { - for (Participant participant : participantList) { - participant.setParticipantState(participantUpdateAckMessage.getState()); - } - participantProvider.updateParticipants(participantList); + if (participantOpt.isPresent()) { + var participant = participantOpt.get(); + participant.setParticipantState(participantUpdateAckMessage.getState()); + participantProvider.saveParticipant(participant); } else { LOGGER.warn("Participant not found in database {}", participantUpdateAckMessage.getParticipantId()); } @@ -439,10 +437,10 @@ public class SupervisionHandler { if (participantMessage.getParticipantId() == null) { exceptionOccured(Response.Status.NOT_FOUND, "Participant ID on PARTICIPANT_STATUS message is null"); } - List<Participant> participantList = participantProvider.getParticipants( - participantMessage.getParticipantId().getName(), participantMessage.getParticipantId().getVersion()); + var participantOpt = participantProvider.findParticipant(participantMessage.getParticipantId().getName(), + participantMessage.getParticipantId().getVersion()); - if (CollectionUtils.isEmpty(participantList)) { + if (participantOpt.isEmpty()) { var participant = new Participant(); participant.setName(participantMessage.getParticipantId().getName()); participant.setVersion(participantMessage.getParticipantId().getVersion()); @@ -451,14 +449,13 @@ public class SupervisionHandler { participant.setParticipantState(participantState); participant.setHealthStatus(healthStatus); - participantList.add(participant); - participantProvider.createParticipants(participantList); + participantProvider.saveParticipant(participant); } else { - for (Participant participant : participantList) { - participant.setParticipantState(participantState); - participant.setHealthStatus(healthStatus); - } - participantProvider.updateParticipants(participantList); + var participant = participantOpt.get(); + participant.setParticipantState(participantState); + participant.setHealthStatus(healthStatus); + + participantProvider.saveParticipant(participant); } } diff --git a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionScanner.java b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionScanner.java index 900a117bd..5ebacdac7 100644 --- a/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionScanner.java +++ b/runtime-controlloop/src/main/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionScanner.java @@ -23,7 +23,6 @@ package org.onap.policy.clamp.controlloop.runtime.supervision; import java.util.HashMap; -import java.util.List; import java.util.Map; import org.apache.commons.lang3.tuple.Pair; import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoop; @@ -121,7 +120,7 @@ public class SupervisionScanner { if (counterCheck) { try { - for (Participant participant : participantProvider.getParticipants(null, null)) { + for (var participant : participantProvider.getParticipants()) { scanParticipantStatus(participant); } } catch (PfModelException pfme) { @@ -188,7 +187,7 @@ public class SupervisionScanner { participantStatusCounter.setFault(id); participant.setHealthStatus(ParticipantHealthStatus.OFF_LINE); } - participantProvider.updateParticipants(List.of(participant)); + participantProvider.saveParticipant(participant); } } diff --git a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/commissioning/CommissioningProviderTest.java b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/commissioning/CommissioningProviderTest.java index 3fd74f22e..22fb51cb5 100644 --- a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/commissioning/CommissioningProviderTest.java +++ b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/commissioning/CommissioningProviderTest.java @@ -24,6 +24,7 @@ package org.onap.policy.clamp.controlloop.runtime.commissioning; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategies; @@ -63,7 +64,6 @@ class CommissioningProviderTest { private ControlLoopProvider clProvider = null; private static final Coder CODER = new StandardCoder(); private final ObjectMapper mapper = new ObjectMapper(); - private ParticipantProvider participantProvider; @AfterEach void close() throws Exception { @@ -73,9 +73,6 @@ class CommissioningProviderTest { if (clProvider != null) { clProvider.close(); } - if (participantProvider != null) { - participantProvider.close(); - } } /** @@ -89,7 +86,7 @@ class CommissioningProviderTest { modelsProvider = CommonTestData.getPolicyModelsProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); clProvider = new ControlLoopProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); - participantProvider = new ParticipantProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); + var participantProvider = mock(ParticipantProvider.class); CommissioningProvider provider = new CommissioningProvider(new ServiceTemplateProvider(modelsProvider), clProvider, null, participantProvider); @@ -127,7 +124,7 @@ class CommissioningProviderTest { modelsProvider = CommonTestData.getPolicyModelsProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); clProvider = new ControlLoopProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); - participantProvider = new ParticipantProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); + var participantProvider = mock(ParticipantProvider.class); CommissioningProvider provider = new CommissioningProvider(new ServiceTemplateProvider(modelsProvider), clProvider, null, participantProvider); @@ -157,7 +154,7 @@ class CommissioningProviderTest { modelsProvider = CommonTestData.getPolicyModelsProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); clProvider = new ControlLoopProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); - participantProvider = new ParticipantProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); + var participantProvider = mock(ParticipantProvider.class); CommissioningProvider provider = new CommissioningProvider(new ServiceTemplateProvider(modelsProvider), clProvider, null, participantProvider); @@ -186,7 +183,7 @@ class CommissioningProviderTest { modelsProvider = CommonTestData.getPolicyModelsProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); clProvider = new ControlLoopProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); - participantProvider = new ParticipantProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); + var participantProvider = mock(ParticipantProvider.class); CommissioningProvider provider = new CommissioningProvider(new ServiceTemplateProvider(modelsProvider), clProvider, null, participantProvider); @@ -215,7 +212,7 @@ class CommissioningProviderTest { modelsProvider = CommonTestData.getPolicyModelsProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); clProvider = new ControlLoopProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); - participantProvider = new ParticipantProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); + var participantProvider = mock(ParticipantProvider.class); CommissioningProvider provider = new CommissioningProvider(new ServiceTemplateProvider(modelsProvider), clProvider, null, participantProvider); @@ -261,7 +258,7 @@ class CommissioningProviderTest { modelsProvider = CommonTestData.getPolicyModelsProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); clProvider = new ControlLoopProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); - participantProvider = new ParticipantProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); + var participantProvider = mock(ParticipantProvider.class); CommissioningProvider provider = new CommissioningProvider(new ServiceTemplateProvider(modelsProvider), clProvider, null, participantProvider); @@ -290,7 +287,7 @@ class CommissioningProviderTest { modelsProvider = CommonTestData.getPolicyModelsProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); clProvider = new ControlLoopProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); - participantProvider = new ParticipantProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); + var participantProvider = mock(ParticipantProvider.class); CommissioningProvider provider = new CommissioningProvider(new ServiceTemplateProvider(modelsProvider), clProvider, null, participantProvider); diff --git a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/instantiation/ControlLoopInstantiationProviderTest.java b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/instantiation/ControlLoopInstantiationProviderTest.java index 564109e5d..caad5a4e9 100644 --- a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/instantiation/ControlLoopInstantiationProviderTest.java +++ b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/instantiation/ControlLoopInstantiationProviderTest.java @@ -27,6 +27,7 @@ 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 static org.mockito.Mockito.when; import java.io.IOException; import java.util.ArrayList; @@ -105,7 +106,6 @@ class ControlLoopInstantiationProviderTest { private static CommissioningProvider commissioningProvider; private static ControlLoopProvider clProvider; private static PolicyModelsProvider modelsProvider; - private static ParticipantProvider participantProvider; @BeforeAll public static void setUpBeforeClass() throws Exception { @@ -123,7 +123,7 @@ class ControlLoopInstantiationProviderTest { modelsProvider = CommonTestData.getPolicyModelsProvider(controlLoopParameters.getDatabaseProviderParameters()); clProvider = new ControlLoopProvider(controlLoopParameters.getDatabaseProviderParameters()); - participantProvider = new ParticipantProvider(controlLoopParameters.getDatabaseProviderParameters()); + var participantProvider = Mockito.mock(ParticipantProvider.class); var participantStatisticsProvider = Mockito.mock(ParticipantStatisticsProvider.class); var clElementStatisticsProvider = mock(ClElementStatisticsProvider.class); @@ -131,7 +131,6 @@ class ControlLoopInstantiationProviderTest { participantProvider); var monitoringProvider = new MonitoringProvider(participantStatisticsProvider, clElementStatisticsProvider, clProvider); - var participantProvider = new ParticipantProvider(controlLoopParameters.getDatabaseProviderParameters()); var controlLoopUpdatePublisher = Mockito.mock(ControlLoopUpdatePublisher.class); var controlLoopStateChangePublisher = Mockito.mock(ControlLoopStateChangePublisher.class); var participantRegisterAckPublisher = Mockito.mock(ParticipantRegisterAckPublisher.class); @@ -162,6 +161,7 @@ class ControlLoopInstantiationProviderTest { @Test void testIntanceResponses() throws PfModelException { + var participantProvider = Mockito.mock(ParticipantProvider.class); var instantiationProvider = new ControlLoopInstantiationProvider(clProvider, commissioningProvider, supervisionHandler, participantProvider); var instancePropertyList = instantiationProvider.createInstanceProperties(serviceTemplate); @@ -180,7 +180,9 @@ class ControlLoopInstantiationProviderTest { @Test void testInstantiationCrud() throws Exception { - participantProvider.createParticipants(CommonTestData.createParticipants()); + var participantProvider = Mockito.mock(ParticipantProvider.class); + var participants = CommonTestData.createParticipants(); + when(participantProvider.getParticipants()).thenReturn(participants); ControlLoops controlLoopsCreate = InstantiationUtils.getControlLoopsFromResource(CL_INSTANTIATION_CREATE_JSON, "Crud"); @@ -242,6 +244,7 @@ class ControlLoopInstantiationProviderTest { ControlLoops controlLoopsDb = new ControlLoops(); controlLoopsDb.setControlLoopList(new ArrayList<>()); + var participantProvider = Mockito.mock(ParticipantProvider.class); var instantiationProvider = new ControlLoopInstantiationProvider(clProvider, commissioningProvider, supervisionHandler, participantProvider); @@ -262,6 +265,7 @@ class ControlLoopInstantiationProviderTest { assertThat(getControlLoopsFromDb(controlLoops).getControlLoopList()).isEmpty(); ControlLoop controlLoop0 = controlLoops.getControlLoopList().get(0); + var participantProvider = Mockito.mock(ParticipantProvider.class); var instantiationProvider = new ControlLoopInstantiationProvider(clProvider, commissioningProvider, supervisionHandler, participantProvider); @@ -295,8 +299,8 @@ class ControlLoopInstantiationProviderTest { private void assertThatDeleteThrownBy(ControlLoops controlLoops, ControlLoopState state) throws Exception { ControlLoop controlLoop = controlLoops.getControlLoopList().get(0); - controlLoop.setState(state); + var participantProvider = Mockito.mock(ParticipantProvider.class); var instantiationProvider = new ControlLoopInstantiationProvider(clProvider, commissioningProvider, supervisionHandler, participantProvider); @@ -316,6 +320,7 @@ class ControlLoopInstantiationProviderTest { ControlLoops controlLoopsDb = getControlLoopsFromDb(controlLoopsCreate); assertThat(controlLoopsDb.getControlLoopList()).isEmpty(); + var participantProvider = Mockito.mock(ParticipantProvider.class); var instantiationProvider = new ControlLoopInstantiationProvider(clProvider, commissioningProvider, supervisionHandler, participantProvider); @@ -336,6 +341,7 @@ class ControlLoopInstantiationProviderTest { ControlLoops controlLoops = InstantiationUtils .getControlLoopsFromResource(CL_INSTANTIATION_DEFINITION_NAME_NOT_FOUND_JSON, "ClElementNotFound"); + var participantProvider = Mockito.mock(ParticipantProvider.class); var provider = new ControlLoopInstantiationProvider(clProvider, commissioningProvider, supervisionHandler, participantProvider); @@ -355,6 +361,7 @@ class ControlLoopInstantiationProviderTest { assertThat(getControlLoopsFromDb(controlLoops).getControlLoopList()).isEmpty(); + var participantProvider = Mockito.mock(ParticipantProvider.class); var provider = new ControlLoopInstantiationProvider(clProvider, commissioningProvider, supervisionHandler, participantProvider); assertThatThrownBy(() -> provider.createControlLoops(controlLoops)) @@ -363,6 +370,7 @@ class ControlLoopInstantiationProviderTest { @Test void testIssueControlLoopCommand_OrderedStateInvalid() throws ControlLoopRuntimeException, IOException { + var participantProvider = Mockito.mock(ParticipantProvider.class); var instantiationProvider = new ControlLoopInstantiationProvider(clProvider, commissioningProvider, supervisionHandler, participantProvider); assertThatThrownBy(() -> instantiationProvider.issueControlLoopCommand(new InstantiationCommand())) @@ -376,6 +384,7 @@ class ControlLoopInstantiationProviderTest { InstantiationUtils.getControlLoopsFromResource(CL_INSTANTIATION_CREATE_JSON, "V1"); assertThat(getControlLoopsFromDb(controlLoopsV1).getControlLoopList()).isEmpty(); + var participantProvider = Mockito.mock(ParticipantProvider.class); var instantiationProvider = new ControlLoopInstantiationProvider(clProvider, commissioningProvider, supervisionHandler, participantProvider); diff --git a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/instantiation/rest/InstantiationControllerTest.java b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/instantiation/rest/InstantiationControllerTest.java index e361ff469..0fc473106 100644 --- a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/instantiation/rest/InstantiationControllerTest.java +++ b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/instantiation/rest/InstantiationControllerTest.java @@ -326,7 +326,10 @@ class InstantiationControllerTest extends CommonRestController { var controlLoops = InstantiationUtils.getControlLoopsFromResource(CL_INSTANTIATION_CREATE_JSON, "Command"); instantiationProvider.createControlLoops(controlLoops); - participantProvider.createParticipants(CommonTestData.createParticipants()); + var participants = CommonTestData.createParticipants(); + for (var participant : participants) { + participantProvider.saveParticipant(participant); + } InstantiationCommand command = InstantiationUtils.getInstantiationCommandFromResource(CL_INSTANTIATION_CHANGE_STATE_JSON, "Command"); diff --git a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionHandlerTest.java b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionHandlerTest.java index a314b30a0..abaa52c12 100644 --- a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionHandlerTest.java +++ b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionHandlerTest.java @@ -29,6 +29,7 @@ import static org.mockito.Mockito.when; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.UUID; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -136,8 +137,8 @@ class SupervisionHandlerTest { participant.setParticipantType(participantType); var participantProvider = mock(ParticipantProvider.class); - when(participantProvider.getParticipants(participantId.getName(), participantId.getVersion())) - .thenReturn(List.of(participant)); + when(participantProvider.findParticipant(participantId.getName(), participantId.getVersion())) + .thenReturn(Optional.of(participant)); var participantDeregisterMessage = new ParticipantDeregister(); participantDeregisterMessage.setMessageId(UUID.randomUUID()); @@ -151,7 +152,7 @@ class SupervisionHandlerTest { handler.handleParticipantMessage(participantDeregisterMessage); - verify(participantProvider).updateParticipants(anyList()); + verify(participantProvider).saveParticipant(any()); verify(participantDeregisterAckPublisher).send(participantDeregisterMessage.getMessageId()); } @@ -175,7 +176,7 @@ class SupervisionHandlerTest { handler.handleParticipantMessage(participantRegisterMessage); - verify(participantProvider).createParticipants(anyList()); + verify(participantProvider).saveParticipant(any()); verify(participantRegisterAckPublisher).send(participantRegisterMessage.getMessageId(), participantId, participantType); } @@ -188,8 +189,8 @@ class SupervisionHandlerTest { participant.setParticipantType(participantType); var participantProvider = mock(ParticipantProvider.class); - when(participantProvider.getParticipants(participantId.getName(), participantId.getVersion())) - .thenReturn(List.of(participant)); + when(participantProvider.findParticipant(participantId.getName(), participantId.getVersion())) + .thenReturn(Optional.of(participant)); var participantUpdateAckMessage = new ParticipantUpdateAck(); participantUpdateAckMessage.setParticipantId(participantId); @@ -202,7 +203,7 @@ class SupervisionHandlerTest { handler.handleParticipantMessage(participantUpdateAckMessage); - verify(participantProvider).updateParticipants(anyList()); + verify(participantProvider).saveParticipant(any()); } @Test @@ -221,7 +222,7 @@ class SupervisionHandlerTest { mock(ControlLoopUpdatePublisher.class), mock(ParticipantUpdatePublisher.class)); handler.handleParticipantMessage(participantStatusMessage); - verify(participantProvider).createParticipants(anyList()); + verify(participantProvider).saveParticipant(any()); verify(monitoringProvider).createParticipantStatistics(anyList()); } diff --git a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionScannerTest.java b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionScannerTest.java index 50672a84e..62029f009 100644 --- a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionScannerTest.java +++ b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/supervision/SupervisionScannerTest.java @@ -20,7 +20,6 @@ package org.onap.policy.clamp.controlloop.runtime.supervision; -import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.mock; @@ -192,8 +191,8 @@ class SupervisionScannerTest { participant.setParticipantState(ParticipantState.ACTIVE); participant.setDefinition(new ToscaConceptIdentifier("unknown", "0.0.0")); participant.setParticipantType(new ToscaConceptIdentifier("ParticipantType1", "1.0.0")); - var participantProvider = new ParticipantProvider(clRuntimeParameterGroup.getDatabaseProviderParameters()); - participantProvider.updateParticipants(List.of(participant)); + var participantProvider = mock(ParticipantProvider.class); + when(participantProvider.getParticipants()).thenReturn(List.of(participant)); var controlLoopUpdatePublisher = mock(ControlLoopUpdatePublisher.class); var participantStatusReqPublisher = mock(ParticipantStatusReqPublisher.class); @@ -206,13 +205,10 @@ class SupervisionScannerTest { supervisionScanner.handleParticipantStatus(participant.getKey().asIdentifier()); supervisionScanner.run(true); - verify(participantStatusReqPublisher, times(1)).send(any(ToscaConceptIdentifier.class)); - - List<Participant> participants = participantProvider.getParticipants(null, null); - assertThat(participants.get(0).getHealthStatus()).isEqualTo(ParticipantHealthStatus.NOT_HEALTHY); + verify(participantStatusReqPublisher).send(any(ToscaConceptIdentifier.class)); + verify(participantProvider).saveParticipant(any()); supervisionScanner.run(true); - participants = participantProvider.getParticipants(null, null); - assertThat(participants.get(0).getHealthStatus()).isEqualTo(ParticipantHealthStatus.OFF_LINE); + verify(participantProvider, times(2)).saveParticipant(any()); } } diff --git a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/SupervisionMessagesTest.java b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/SupervisionMessagesTest.java index 93433f59c..b64bd9fbe 100644 --- a/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/SupervisionMessagesTest.java +++ b/runtime-controlloop/src/test/java/org/onap/policy/clamp/controlloop/runtime/supervision/comm/SupervisionMessagesTest.java @@ -80,7 +80,7 @@ class SupervisionMessagesTest extends CommonRestController { var clElementStatisticsProvider = mock(ClElementStatisticsProvider.class); var monitoringProvider = new MonitoringProvider(participantStatisticsProvider, clElementStatisticsProvider, clProvider); - var participantProvider = new ParticipantProvider(controlLoopParameters.getDatabaseProviderParameters()); + var participantProvider = mock(ParticipantProvider.class); var serviceTemplateProvider = Mockito.mock(ServiceTemplateProvider.class); var controlLoopUpdatePublisher = Mockito.mock(ControlLoopUpdatePublisher.class); var controlLoopStateChangePublisher = Mockito.mock(ControlLoopStateChangePublisher.class); |