From 873803eca00830dc3ecb61e610d90710f64a8242 Mon Sep 17 00:00:00 2001 From: "a.sreekumar" Date: Mon, 7 Feb 2022 16:05:17 +0000 Subject: Move PAP database provider to spring boot default This review makes PAP talk to DB directly using the spring repositories instead of going to policy-models-provider. The models-provider methods that were just used by PAP (and not used anymore) will be removed in a different review. Also a bug identified with the usage of GeneratedValue in PfGeneratedIdKey (which is just used by PAP in statistics & audit) will also be fixed in a separate review as part of POLICY-3897. CSIT changes: https://gerrit.onap.org/r/c/policy/docker/+/127033 WIP OOM review: https://gerrit.onap.org/r/c/oom/+/127035 Change-Id: Idb13ba7eb2767cc718672b582a6518fcfc95320f Issue-ID: POLICY-3867 Signed-off-by: a.sreekumar --- main/pom.xml | 5 - .../org/onap/policy/pap/main/PapConstants.java | 3 +- .../main/PolicyModelsProviderFactoryWrapper.java | 63 -- .../policy/pap/main/comm/PdpHeartbeatListener.java | 16 +- .../policy/pap/main/comm/PdpMessageGenerator.java | 39 +- .../policy/pap/main/comm/PdpModifyRequestMap.java | 77 +- .../pap/main/comm/PdpStatusMessageHandler.java | 108 +- .../pap/main/notification/DeploymentStatus.java | 19 +- .../pap/main/notification/PolicyNotifier.java | 29 +- .../pap/main/parameters/PapParameterGroup.java | 6 +- .../main/parameters/PdpModifyRequestMapParams.java | 14 +- .../pap/main/rest/PdpGroupHealthCheckProvider.java | 27 +- .../pap/main/rest/PdpGroupQueryControllerV1.java | 19 +- .../pap/main/rest/PdpGroupQueryProvider.java | 64 -- .../pap/main/rest/PdpGroupStateChangeProvider.java | 40 +- .../pap/main/rest/PolicyAuditControllerV1.java | 29 +- .../policy/pap/main/rest/PolicyAuditManager.java | 16 +- .../policy/pap/main/rest/PolicyAuditProvider.java | 62 -- .../rest/PolicyComponentsHealthCheckProvider.java | 29 +- .../pap/main/rest/PolicyStatusControllerV1.java | 17 +- .../policy/pap/main/rest/PolicyStatusProvider.java | 78 +- .../policy/pap/main/rest/PolicyUndeployerImpl.java | 11 +- .../onap/policy/pap/main/rest/ProviderBase.java | 74 +- .../org/onap/policy/pap/main/rest/SessionData.java | 63 +- .../pap/main/rest/StatisticsRestControllerV1.java | 41 +- .../pap/main/rest/StatisticsRestProvider.java | 107 -- .../policy/pap/main/service/PdpGroupService.java | 27 +- .../pap/main/service/PdpStatisticsService.java | 46 +- .../pap/main/service/PolicyAuditService.java | 15 +- .../main/service/ToscaServiceTemplateService.java | 14 + .../policy/pap/main/startstop/PapActivator.java | 59 +- .../pap/main/startstop/PapDatabaseInitializer.java | 33 +- main/src/main/resources/META-INF/persistence.xml | 67 -- main/src/main/resources/application.yaml | 10 +- .../policy/pap/main/comm/CommonRequestBase.java | 12 +- .../pap/main/comm/PdpHeartbeatListenerTest.java | 47 +- .../pap/main/comm/PdpModifyRequestMapTest.java | 41 +- .../main/notification/DeploymentStatusTest.java | 13 +- .../pap/main/notification/PolicyNotifierTest.java | 27 +- .../parameters/TestPdpModifyRequestMapParams.java | 23 +- .../policy/pap/main/rest/CommonPapRestServer.java | 4 +- .../onap/policy/pap/main/rest/ProviderSuper.java | 49 +- .../rest/TestPdpGroupCreateOrUpdateProvider.java | 1124 ++++++++++---------- .../pap/main/rest/TestPdpGroupDeleteProvider.java | 19 +- .../pap/main/rest/TestPdpGroupDeployProvider.java | 102 +- .../main/rest/TestPdpGroupHealthCheckProvider.java | 20 +- .../pap/main/rest/TestPolicyAuditManager.java | 5 +- .../pap/main/rest/TestPolicyAuditProvider.java | 105 -- .../TestPolicyComponentsHealthCheckProvider.java | 17 +- .../pap/main/rest/TestPolicyStatusProvider.java | 10 +- .../policy/pap/main/rest/TestProviderBase.java | 46 +- .../onap/policy/pap/main/rest/TestSessionData.java | 102 +- .../onap/policy/pap/main/rest/e2e/End2EndBase.java | 116 +- .../main/rest/e2e/PdpGroupCreateOrUpdateTest.java | 15 +- .../pap/main/rest/e2e/PdpGroupDeleteTest.java | 18 +- .../pap/main/rest/e2e/PdpGroupDeployTest.java | 18 +- .../pap/main/rest/e2e/PdpGroupQueryTest.java | 14 +- .../pap/main/rest/e2e/PdpGroupStateChangeTest.java | 17 +- .../policy/pap/main/rest/e2e/PolicyAuditTest.java | 39 +- .../policy/pap/main/rest/e2e/PolicyStatusTest.java | 16 +- .../policy/pap/main/rest/e2e/StatisticsTest.java | 47 +- .../pap/main/service/PdpGroupServiceTest.java | 37 +- .../pap/main/service/PdpStatisticsServiceTest.java | 25 +- .../pap/main/service/PolicyAuditServiceTest.java | 18 +- .../pap/main/startstop/TestPapActivator.java | 9 +- main/src/test/resources/META-INF/persistence.xml | 68 -- main/src/test/resources/config/application.yaml | 8 - 67 files changed, 1482 insertions(+), 2076 deletions(-) delete mode 100644 main/src/main/java/org/onap/policy/pap/main/PolicyModelsProviderFactoryWrapper.java delete mode 100644 main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupQueryProvider.java delete mode 100644 main/src/main/java/org/onap/policy/pap/main/rest/PolicyAuditProvider.java delete mode 100644 main/src/main/java/org/onap/policy/pap/main/rest/StatisticsRestProvider.java delete mode 100644 main/src/main/resources/META-INF/persistence.xml delete mode 100644 main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditProvider.java delete mode 100644 main/src/test/resources/META-INF/persistence.xml (limited to 'main') diff --git a/main/pom.xml b/main/pom.xml index b19920e5..621fb45e 100644 --- a/main/pom.xml +++ b/main/pom.xml @@ -90,11 +90,6 @@ policy-models-pdp ${policy.models.version} - - org.onap.policy.models - policy-models-provider - ${policy.models.version} - org.onap.policy.common utils-test diff --git a/main/src/main/java/org/onap/policy/pap/main/PapConstants.java b/main/src/main/java/org/onap/policy/pap/main/PapConstants.java index f38a82e0..df43c69f 100644 --- a/main/src/main/java/org/onap/policy/pap/main/PapConstants.java +++ b/main/src/main/java/org/onap/policy/pap/main/PapConstants.java @@ -3,6 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +33,6 @@ public final class PapConstants { public static final String REG_STATISTICS_MANAGER = "object:manager/statistics"; public static final String REG_PDP_MODIFY_LOCK = "lock:pdp"; public static final String REG_PDP_MODIFY_MAP = "object:pdp/modify/map"; - public static final String REG_POLICY_NOTIFIER = "object:policy/notifier"; - public static final String REG_PAP_DAO_FACTORY = "object:pap/dao/factory"; // topic names public static final String TOPIC_POLICY_PDP_PAP = "POLICY-PDP-PAP"; diff --git a/main/src/main/java/org/onap/policy/pap/main/PolicyModelsProviderFactoryWrapper.java b/main/src/main/java/org/onap/policy/pap/main/PolicyModelsProviderFactoryWrapper.java deleted file mode 100644 index 404b72d2..00000000 --- a/main/src/main/java/org/onap/policy/pap/main/PolicyModelsProviderFactoryWrapper.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.pap.main; - -import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.provider.PolicyModelsProvider; -import org.onap.policy.models.provider.PolicyModelsProviderFactory; -import org.onap.policy.models.provider.PolicyModelsProviderParameters; - -/** - * Wraps a {@link PolicyModelsProviderFactoryWrapper}. - */ -public class PolicyModelsProviderFactoryWrapper implements AutoCloseable { - private final PolicyModelsProviderParameters params; - private final PolicyModelsProviderFactory factory; - - /** - * Constructs the object. - * - * @param params DAO configuration parameters - */ - public PolicyModelsProviderFactoryWrapper(PolicyModelsProviderParameters params) { - this.params = params; - this.factory = new PolicyModelsProviderFactory(); - } - - @Override - public void close() throws Exception { - /* - * PolicyModelsProviderFactory should, in theory, implement AutoCloseable so it - * can close the entity manager factory and release all data. Since it doesn't - * this method does nothing for now. - */ - } - - /** - * Creates a provider based on models-pap. - * - * @return a new provider - * @throws PfModelException if an error occurs - */ - public PolicyModelsProvider create() throws PfModelException { - return factory.createPolicyModelsProvider(params); - } -} diff --git a/main/src/main/java/org/onap/policy/pap/main/comm/PdpHeartbeatListener.java b/main/src/main/java/org/onap/policy/pap/main/comm/PdpHeartbeatListener.java index 15242a92..4e4709e9 100644 --- a/main/src/main/java/org/onap/policy/pap/main/comm/PdpHeartbeatListener.java +++ b/main/src/main/java/org/onap/policy/pap/main/comm/PdpHeartbeatListener.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. * Modifications Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,10 +23,12 @@ package org.onap.policy.pap.main.comm; import lombok.AllArgsConstructor; +import lombok.NoArgsConstructor; import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; import org.onap.policy.common.endpoints.listeners.TypedMessageListener; import org.onap.policy.models.pdp.concepts.PdpStatus; -import org.onap.policy.pap.main.parameters.PdpParameters; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; /** * Listener for PDP Status messages which either represent registration or heart beat. @@ -34,16 +36,16 @@ import org.onap.policy.pap.main.parameters.PdpParameters; * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ @AllArgsConstructor +@NoArgsConstructor +@Component public class PdpHeartbeatListener implements TypedMessageListener { - private final PdpParameters params; + @Autowired + private PdpStatusMessageHandler pdpStatusMessageHandler; - private final boolean savePdpStatistics; @Override public void onTopicEvent(final CommInfrastructure infra, final String topic, final PdpStatus message) { - - final var handler = new PdpStatusMessageHandler(params, savePdpStatistics); - handler.handlePdpStatus(message); + pdpStatusMessageHandler.handlePdpStatus(message); } } diff --git a/main/src/main/java/org/onap/policy/pap/main/comm/PdpMessageGenerator.java b/main/src/main/java/org/onap/policy/pap/main/comm/PdpMessageGenerator.java index 02609535..255b93e0 100644 --- a/main/src/main/java/org/onap/policy/pap/main/comm/PdpMessageGenerator.java +++ b/main/src/main/java/org/onap/policy/pap/main/comm/PdpMessageGenerator.java @@ -4,7 +4,7 @@ * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,16 +32,17 @@ import org.onap.policy.models.pdp.concepts.PdpStateChange; import org.onap.policy.models.pdp.concepts.PdpSubGroup; import org.onap.policy.models.pdp.concepts.PdpUpdate; import org.onap.policy.models.pdp.enums.PdpState; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; import org.onap.policy.pap.main.notification.DeploymentStatus; import org.onap.policy.pap.main.notification.PolicyNotifier; import org.onap.policy.pap.main.parameters.PapParameterGroup; +import org.onap.policy.pap.main.service.PolicyStatusService; +import org.onap.policy.pap.main.service.ToscaServiceTemplateService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.event.EventListener; @@ -65,16 +66,20 @@ public class PdpMessageGenerator { */ protected PdpModifyRequestMap requestMap; - /** - * Factory for PAP DAO. - */ - protected PolicyModelsProviderFactoryWrapper modelProviderWrapper; - /** * Heart beat interval, in milliseconds, to pass to PDPs, or {@code null}. */ private Long heartBeatMs; + @Autowired + private ToscaServiceTemplateService toscaService; + + @Autowired + private PolicyStatusService policyStatusService; + + @Autowired + private PolicyNotifier policyNotifier; + /** * Constructs the object. * @@ -90,7 +95,6 @@ public class PdpMessageGenerator { */ @EventListener(ApplicationReadyEvent.class) public void initialize() { - modelProviderWrapper = Registry.get(PapConstants.REG_PAP_DAO_FACTORY, PolicyModelsProviderFactoryWrapper.class); updateLock = Registry.get(PapConstants.REG_PDP_MODIFY_LOCK, Object.class); requestMap = Registry.get(PapConstants.REG_PDP_MODIFY_MAP, PdpModifyRequestMap.class); @@ -126,16 +130,14 @@ public class PdpMessageGenerator { * Method to return a list of policies. * * @param subGroup PdpSubGroup to retrieve policies from - * @param databaseProvider PolicyModelsProvider used to retrieve list of policies + * @throws PfModelException the exception * @returns a list of ToscaPolicy **/ - public List getToscaPolicies(final PdpSubGroup subGroup, - final PolicyModelsProvider databaseProvider) - throws PfModelException { + public List getToscaPolicies(final PdpSubGroup subGroup) throws PfModelException { final List policies = new LinkedList<>(); for (final ToscaConceptIdentifier policyIdentifier : subGroup.getPolicies()) { - policies.addAll(databaseProvider.getPolicyList(policyIdentifier.getName(), policyIdentifier.getVersion())); + policies.addAll(toscaService.getPolicyList(policyIdentifier.getName(), policyIdentifier.getVersion())); } LOGGER.debug("Created ToscaPolicy list - {}", policies); @@ -164,14 +166,12 @@ public class PdpMessageGenerator { * @param pdpType the pdp type * @param pdpInstanceId the pdp instance * @param pdpState the new state as per the PDP_STATE_CHANGE change message - * @param databaseProvider the database provider * @param policies list of policies as per the PDP_UPDATE message * @throws PfModelException the exception */ protected void updateDeploymentStatus(final String pdpGroupName, final String pdpType, final String pdpInstanceId, - PdpState pdpState, final PolicyModelsProvider databaseProvider, List policies) - throws PfModelException { - var deploymentStatus = new DeploymentStatus(databaseProvider); + PdpState pdpState, List policies) { + var deploymentStatus = new DeploymentStatus(policyStatusService); deploymentStatus.loadByGroup(pdpGroupName); if (pdpState.equals(PdpState.PASSIVE)) { deploymentStatus.deleteDeployment(pdpInstanceId); @@ -183,7 +183,6 @@ public class PdpMessageGenerator { } var notification = new PolicyNotification(); deploymentStatus.flush(notification); - PolicyNotifier notifier = Registry.get(PapConstants.REG_POLICY_NOTIFIER); - notifier.publish(notification); + policyNotifier.publish(notification); } } diff --git a/main/src/main/java/org/onap/policy/pap/main/comm/PdpModifyRequestMap.java b/main/src/main/java/org/onap/policy/pap/main/comm/PdpModifyRequestMap.java index f231130a..e23026be 100644 --- a/main/src/main/java/org/onap/policy/pap/main/comm/PdpModifyRequestMap.java +++ b/main/src/main/java/org/onap/policy/pap/main/comm/PdpModifyRequestMap.java @@ -4,7 +4,7 @@ * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,7 +32,6 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; -import lombok.Setter; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.pap.concepts.PolicyNotification; import org.onap.policy.models.pdp.concepts.Pdp; @@ -44,9 +43,7 @@ import org.onap.policy.models.pdp.concepts.PdpStatus; import org.onap.policy.models.pdp.concepts.PdpSubGroup; import org.onap.policy.models.pdp.concepts.PdpUpdate; import org.onap.policy.models.pdp.enums.PdpState; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; import org.onap.policy.pap.main.comm.msgdata.Request; import org.onap.policy.pap.main.comm.msgdata.RequestListener; import org.onap.policy.pap.main.comm.msgdata.StateChangeReq; @@ -55,12 +52,16 @@ import org.onap.policy.pap.main.notification.DeploymentStatus; import org.onap.policy.pap.main.notification.PolicyNotifier; import org.onap.policy.pap.main.parameters.PdpModifyRequestMapParams; import org.onap.policy.pap.main.parameters.RequestParams; +import org.onap.policy.pap.main.service.PdpGroupService; +import org.onap.policy.pap.main.service.PolicyStatusService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; /** * Maps a PDP name to requests that modify PDPs. */ +@Component public class PdpModifyRequestMap { private static final Logger logger = LoggerFactory.getLogger(PdpModifyRequestMap.class); @@ -74,17 +75,12 @@ public class PdpModifyRequestMap { /** * PDP modification lock. */ - private final Object modifyLock; + private Object modifyLock; /** * The configuration parameters. */ - private final PdpModifyRequestMapParams params; - - /** - * Factory for PAP DAO. - */ - private final PolicyModelsProviderFactoryWrapper daoFactory; + private PdpModifyRequestMapParams params; /** * Used to notify when policy updates completes. @@ -95,28 +91,46 @@ public class PdpModifyRequestMap { * Used to undeploy policies from the system, when they cannot be deployed to a PDP. * *

- * Note: there's a "catch-22" here. The request map needs an undeployer, but the - * undeployer needs the request map. Consequently, the request map is created first, - * then the undeployer, and finally, this field is set. + * Note: The request map needs an undeployer during creation, and the undeployer + * needs the request map when it's initialize method is called. */ - @Setter - private PolicyUndeployer policyUndeployer; + private final PolicyUndeployer policyUndeployer; + + private final PdpGroupService pdpGroupService; + private final PolicyStatusService policyStatusService; + + private final PdpStatusMessageHandler pdpStatusMessageHandler; /** * Constructs the object. * - * @param params configuration parameters + * @param pdpGroupService the pdpGroupService + * @param policyStatusService the policyStatusService + * @param pdpStatusMessageHandler the pdpStatusMessageHandler + * @param policyUndeployer the policyUndeployer + * @param policyNotifier the policyNotifier + */ + public PdpModifyRequestMap(PdpGroupService pdpGroupService, PolicyStatusService policyStatusService, + PdpStatusMessageHandler pdpStatusMessageHandler, PolicyUndeployer policyUndeployer, + PolicyNotifier policyNotifier) { + this.pdpGroupService = pdpGroupService; + this.policyStatusService = policyStatusService; + this.pdpStatusMessageHandler = pdpStatusMessageHandler; + this.policyUndeployer = policyUndeployer; + this.policyNotifier = policyNotifier; + } + + /** + * Initializes the requestMap. * - * @throws IllegalArgumentException if a required parameter is not set + * @param params the parameters. */ - public PdpModifyRequestMap(PdpModifyRequestMapParams params) { + public void initialize(PdpModifyRequestMapParams params) { params.validate(); this.params = params; this.modifyLock = params.getModifyLock(); - this.daoFactory = params.getDaoFactory(); - this.policyNotifier = params.getPolicyNotifier(); } /** @@ -267,13 +281,13 @@ public class PdpModifyRequestMap { synchronized (modifyLock) { logger.info("check for PDP records older than {}ms", params.getMaxPdpAgeMs()); - try (PolicyModelsProvider dao = daoFactory.create()) { + try { PdpGroupFilter filter = PdpGroupFilter.builder().groupState(PdpState.ACTIVE).build(); - List groups = dao.getFilteredPdpGroups(filter); + List groups = pdpGroupService.getFilteredPdpGroups(filter); List updates = new ArrayList<>(1); - var status = new DeploymentStatus(dao); + var status = new DeploymentStatus(policyStatusService); Instant minAge = Instant.now().minusMillis(params.getMaxPdpAgeMs()); @@ -287,7 +301,7 @@ public class PdpModifyRequestMap { } if (!updates.isEmpty()) { - dao.updatePdpGroups(updates); + pdpGroupService.updatePdpGroups(updates); var notification = new PolicyNotification(); status.flush(notification); @@ -295,7 +309,7 @@ public class PdpModifyRequestMap { policyNotifier.publish(notification); } - } catch (PfModelException | RuntimeException e) { + } catch (RuntimeException e) { logger.warn("failed to remove expired PDPs", e); } } @@ -352,14 +366,6 @@ public class PdpModifyRequestMap { return new PdpRequests(pdpName, policyNotifier); } - /** - * Makes a handler for PDP responses. - * @return a response handler - */ - protected PdpStatusMessageHandler makePdpResponseHandler() { - return new PdpStatusMessageHandler(params.getParams(), params.isSavePdpStatistics()); - } - /** * Listener for singleton request events. */ @@ -419,8 +425,7 @@ public class PdpModifyRequestMap { * Update PDP time stamps. Also send pdp-update and pdp-state-change, as * necessary, if the response does not reflect what's in the DB. */ - var handler = makePdpResponseHandler(); - handler.handlePdpStatus(response); + pdpStatusMessageHandler.handlePdpStatus(response); } /** diff --git a/main/src/main/java/org/onap/policy/pap/main/comm/PdpStatusMessageHandler.java b/main/src/main/java/org/onap/policy/pap/main/comm/PdpStatusMessageHandler.java index fa90266d..070261db 100644 --- a/main/src/main/java/org/onap/policy/pap/main/comm/PdpStatusMessageHandler.java +++ b/main/src/main/java/org/onap/policy/pap/main/comm/PdpStatusMessageHandler.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019-2021 Nordix Foundation. * Modifications Copyright (C) 2019-2021 AT&T Intellectual Property. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,13 +43,16 @@ import org.onap.policy.models.pdp.concepts.PdpStatistics; import org.onap.policy.models.pdp.concepts.PdpStatus; import org.onap.policy.models.pdp.concepts.PdpSubGroup; import org.onap.policy.models.pdp.enums.PdpState; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.onap.policy.pap.main.PolicyPapException; +import org.onap.policy.pap.main.parameters.PapParameterGroup; import org.onap.policy.pap.main.parameters.PdpParameters; +import org.onap.policy.pap.main.service.PdpGroupService; +import org.onap.policy.pap.main.service.PdpStatisticsService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; /** @@ -57,6 +60,8 @@ import org.slf4j.LoggerFactory; * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ + +@Component public class PdpStatusMessageHandler extends PdpMessageGenerator { private static final Logger LOGGER = LoggerFactory.getLogger(PdpStatusMessageHandler.class); @@ -64,6 +69,10 @@ public class PdpStatusMessageHandler extends PdpMessageGenerator { private final boolean savePdpStatistics; + private final PdpGroupService pdpGroupService; + + private final PdpStatisticsService pdpStatisticsService; + /** * List to store policies present in db. */ @@ -82,13 +91,17 @@ public class PdpStatusMessageHandler extends PdpMessageGenerator { /** * Constructs the object. * - * @param params PDP parameters + * @param parameterGroup the parameterGroup + * @param pdpGroupService the pdpGroupService + * @param pdpStatisticsService the pdpStatisticsService */ - public PdpStatusMessageHandler(PdpParameters params, boolean savePdpStatistics) { + public PdpStatusMessageHandler(PapParameterGroup parameterGroup, PdpGroupService pdpGroupService, + PdpStatisticsService pdpStatisticsService) { super(true); - super.initialize(); - this.params = params; - this.savePdpStatistics = savePdpStatistics; + this.params = parameterGroup.getPdpParameters(); + this.savePdpStatistics = parameterGroup.isSavePdpStatisticsInDb(); + this.pdpGroupService = pdpGroupService; + this.pdpStatisticsService = pdpStatisticsService; } /** @@ -109,11 +122,11 @@ public class PdpStatusMessageHandler extends PdpMessageGenerator { } synchronized (updateLock) { - try (PolicyModelsProvider databaseProvider = modelProviderWrapper.create()) { + try { if (message.getPdpSubgroup() == null) { - handlePdpRegistration(message, databaseProvider); + handlePdpRegistration(message); } else { - handlePdpHeartbeat(message, databaseProvider); + handlePdpHeartbeat(message); } } catch (final PolicyPapException exp) { LOGGER.error("Operation Failed", exp); @@ -159,36 +172,34 @@ public class PdpStatusMessageHandler extends PdpMessageGenerator { return false; } - private void handlePdpRegistration(final PdpStatus message, final PolicyModelsProvider databaseProvider) - throws PfModelException, PolicyPapException { - if (!findAndUpdatePdpGroup(message, databaseProvider)) { + private void handlePdpRegistration(final PdpStatus message) throws PfModelException, PolicyPapException { + if (!findAndUpdatePdpGroup(message)) { final var errorMessage = "Failed to register PDP. No matching PdpGroup/SubGroup Found - "; LOGGER.debug("{}{}", errorMessage, message); throw new PolicyPapException(errorMessage + message); } } - private boolean findAndUpdatePdpGroup(final PdpStatus message, final PolicyModelsProvider databaseProvider) + private boolean findAndUpdatePdpGroup(final PdpStatus message) throws PfModelException { var pdpGroupFound = false; final PdpGroupFilter filter = PdpGroupFilter.builder().name(message.getPdpGroup()).groupState(PdpState.ACTIVE).build(); - final List pdpGroups = databaseProvider.getFilteredPdpGroups(filter); + final List pdpGroups = pdpGroupService.getFilteredPdpGroups(filter); if (!pdpGroups.isEmpty()) { - pdpGroupFound = registerPdp(message, databaseProvider, pdpGroups.get(0)); + pdpGroupFound = registerPdp(message, pdpGroups.get(0)); } return pdpGroupFound; } - private boolean registerPdp(final PdpStatus message, final PolicyModelsProvider databaseProvider, - final PdpGroup finalizedPdpGroup) throws PfModelException { + private boolean registerPdp(final PdpStatus message, final PdpGroup finalizedPdpGroup) throws PfModelException { Optional subGroup; var pdpGroupFound = false; subGroup = findPdpSubGroup(message, finalizedPdpGroup); if (subGroup.isPresent()) { - policies = getToscaPolicies(subGroup.get(), databaseProvider); + policies = getToscaPolicies(subGroup.get()); policiesToBeDeployed = policies.stream().collect(Collectors .toMap(ToscaPolicy::getIdentifier, policy -> policy)); policiesToBeUndeployed = null; @@ -196,18 +207,17 @@ public class PdpStatusMessageHandler extends PdpMessageGenerator { LOGGER.debug("Found pdpGroup - {}, going for registration of PDP - {}", finalizedPdpGroup, message); Optional pdp = findPdpInstance(message, subGroup.get()); if (pdp.isPresent()) { - updatePdpHealthStatus(message, subGroup.get(), pdp.get(), finalizedPdpGroup, databaseProvider); + updatePdpHealthStatus(message, subGroup.get(), pdp.get(), finalizedPdpGroup); } else { - updatePdpSubGroup(finalizedPdpGroup, subGroup.get(), message, databaseProvider); + updatePdpSubGroup(finalizedPdpGroup, subGroup.get(), message); } - sendPdpMessage(finalizedPdpGroup.getName(), subGroup.get(), message.getName(), null, databaseProvider); + sendPdpMessage(finalizedPdpGroup.getName(), subGroup.get(), message.getName(), null); pdpGroupFound = true; } return pdpGroupFound; } - private void updatePdpSubGroup(final PdpGroup pdpGroup, final PdpSubGroup pdpSubGroup, final PdpStatus message, - final PolicyModelsProvider databaseProvider) throws PfModelException { + private void updatePdpSubGroup(final PdpGroup pdpGroup, final PdpSubGroup pdpSubGroup, final PdpStatus message) { final var pdpInstance = new Pdp(); pdpInstance.setInstanceId(message.getName()); @@ -219,27 +229,26 @@ public class PdpStatusMessageHandler extends PdpMessageGenerator { pdpSubGroup.setCurrentInstanceCount(pdpSubGroup.getCurrentInstanceCount() + 1); - databaseProvider.updatePdpSubGroup(pdpGroup.getName(), pdpSubGroup); + pdpGroupService.updatePdpSubGroup(pdpGroup.getName(), pdpSubGroup); LOGGER.debug("Updated PdpSubGroup in DB - {} belonging to PdpGroup - {}", pdpSubGroup, pdpGroup.getName()); } - private void handlePdpHeartbeat(final PdpStatus message, final PolicyModelsProvider databaseProvider) - throws PfModelException { + private void handlePdpHeartbeat(final PdpStatus message) throws PfModelException { final PdpGroupFilter filter = PdpGroupFilter.builder().name(message.getPdpGroup()).groupState(PdpState.ACTIVE).build(); - final List pdpGroups = databaseProvider.getFilteredPdpGroups(filter); + final List pdpGroups = pdpGroupService.getFilteredPdpGroups(filter); if (!pdpGroups.isEmpty()) { var pdpGroup = pdpGroups.get(0); Optional pdpSubgroup = findPdpSubGroup(message, pdpGroup); if (pdpSubgroup.isPresent()) { Optional pdpInstance = findPdpInstance(message, pdpSubgroup.get()); if (pdpInstance.isPresent()) { - processPdpDetails(message, pdpSubgroup.get(), pdpInstance.get(), pdpGroup, databaseProvider); + processPdpDetails(message, pdpSubgroup.get(), pdpInstance.get(), pdpGroup); } else { LOGGER.debug("PdpInstance not Found in DB. Sending Pdp for registration - {}", message); - registerPdp(message, databaseProvider, pdpGroup); + registerPdp(message, pdpGroup); } } } @@ -268,10 +277,9 @@ public class PdpStatusMessageHandler extends PdpMessageGenerator { } private void processPdpDetails(final PdpStatus message, final PdpSubGroup pdpSubGroup, final Pdp pdpInstance, - final PdpGroup pdpGroup, final PolicyModelsProvider databaseProvider) - throws PfModelException { + final PdpGroup pdpGroup) throws PfModelException { // all policies - policies = getToscaPolicies(pdpSubGroup, databaseProvider); + policies = getToscaPolicies(pdpSubGroup); Map policyMap = policies.stream().collect(Collectors.toMap(ToscaPolicy::getIdentifier, policy -> policy)); @@ -285,13 +293,13 @@ public class PdpStatusMessageHandler extends PdpMessageGenerator { policiesToBeDeployed.keySet().removeAll(message.getPolicies()); if (PdpState.TERMINATED.equals(message.getState())) { - processPdpTermination(pdpSubGroup, pdpInstance, pdpGroup, databaseProvider); + processPdpTermination(pdpSubGroup, pdpInstance, pdpGroup); } else if (validatePdpDetails(message, pdpGroup, pdpSubGroup, pdpInstance)) { LOGGER.debug("PdpInstance details are correct. Saving current state in DB - {}", pdpInstance); - updatePdpHealthStatus(message, pdpSubGroup, pdpInstance, pdpGroup, databaseProvider); + updatePdpHealthStatus(message, pdpSubGroup, pdpInstance, pdpGroup); if (savePdpStatistics) { - processPdpStatistics(message, pdpSubGroup, pdpInstance, pdpGroup, databaseProvider); + processPdpStatistics(message, pdpSubGroup, pdpInstance, pdpGroup); } else { LOGGER.debug("Not processing PdpStatistics - {}", message.getStatistics()); } @@ -299,28 +307,26 @@ public class PdpStatusMessageHandler extends PdpMessageGenerator { LOGGER.debug("PdpInstance details are not correct. Sending PdpUpdate message - {}", pdpInstance); LOGGER.debug("Policy list in DB - {}. Policy list in heartbeat - {}", pdpSubGroup.getPolicies(), message.getPolicies()); - updatePdpHealthStatus(message, pdpSubGroup, pdpInstance, pdpGroup, databaseProvider); - sendPdpMessage(pdpGroup.getName(), pdpSubGroup, pdpInstance.getInstanceId(), pdpInstance.getPdpState(), - databaseProvider); + updatePdpHealthStatus(message, pdpSubGroup, pdpInstance, pdpGroup); + sendPdpMessage(pdpGroup.getName(), pdpSubGroup, pdpInstance.getInstanceId(), pdpInstance.getPdpState()); } } private void processPdpStatistics(final PdpStatus message, final PdpSubGroup pdpSubGroup, final Pdp pdpInstance, - final PdpGroup pdpGroup, final PolicyModelsProvider databaseProvider) throws PfModelException { + final PdpGroup pdpGroup) { if (validatePdpStatisticsDetails(message, pdpInstance, pdpGroup, pdpSubGroup)) { LOGGER.debug("PdpStatistics details are correct. Saving current statistics in DB - {}", message.getStatistics()); - createPdpStatistics(message.getStatistics(), databaseProvider); + createPdpStatistics(message.getStatistics()); } else { LOGGER.debug("PdpStatistics details are not correct - {}", message.getStatistics()); } } - private void processPdpTermination(final PdpSubGroup pdpSubGroup, final Pdp pdpInstance, final PdpGroup pdpGroup, - final PolicyModelsProvider databaseProvider) throws PfModelException { + private void processPdpTermination(final PdpSubGroup pdpSubGroup, final Pdp pdpInstance, final PdpGroup pdpGroup) { pdpSubGroup.getPdpInstances().remove(pdpInstance); pdpSubGroup.setCurrentInstanceCount(pdpSubGroup.getCurrentInstanceCount() - 1); - databaseProvider.updatePdpSubGroup(pdpGroup.getName(), pdpSubGroup); + pdpGroupService.updatePdpSubGroup(pdpGroup.getName(), pdpSubGroup); LOGGER.debug("Deleted PdpInstance - {} belonging to PdpSubGroup - {} and PdpGroup - {}", pdpInstance, pdpSubGroup, pdpGroup); @@ -363,24 +369,22 @@ public class PdpStatusMessageHandler extends PdpMessageGenerator { } private void updatePdpHealthStatus(final PdpStatus message, final PdpSubGroup pdpSubgroup, final Pdp pdpInstance, - final PdpGroup pdpGroup, final PolicyModelsProvider databaseProvider) throws PfModelException { + final PdpGroup pdpGroup) { pdpInstance.setHealthy(message.getHealthy()); pdpInstance.setMessage(message.getDescription()); pdpInstance.setLastUpdate(Instant.now()); - databaseProvider.updatePdp(pdpGroup.getName(), pdpSubgroup.getPdpType(), pdpInstance); + pdpGroupService.updatePdp(pdpGroup.getName(), pdpSubgroup.getPdpType(), pdpInstance); LOGGER.debug("Updated Pdp in DB - {}", pdpInstance); } - private void createPdpStatistics(final PdpStatistics pdpStatistics, final PolicyModelsProvider databaseProvider) - throws PfModelException { - databaseProvider.createPdpStatistics(Arrays.asList(pdpStatistics)); + private void createPdpStatistics(final PdpStatistics pdpStatistics) { + pdpStatisticsService.createPdpStatistics(Arrays.asList(pdpStatistics)); LOGGER.debug("Created PdpStatistics in DB - {}", pdpStatistics); } private void sendPdpMessage(final String pdpGroupName, final PdpSubGroup subGroup, final String pdpInstanceId, - final PdpState pdpState, final PolicyModelsProvider databaseProvider) - throws PfModelException { + final PdpState pdpState) { final List polsToBeDeployed = new LinkedList<>(policiesToBeDeployed.values()); final var pdpUpdatemessage = createPdpUpdateMessage(pdpGroupName, subGroup, pdpInstanceId, @@ -388,7 +392,7 @@ public class PdpStatusMessageHandler extends PdpMessageGenerator { final var pdpStateChangeMessage = createPdpStateChangeMessage(pdpGroupName, subGroup, pdpInstanceId, pdpState); updateDeploymentStatus(pdpGroupName, subGroup.getPdpType(), pdpInstanceId, pdpStateChangeMessage.getState(), - databaseProvider, pdpUpdatemessage.getPoliciesToBeDeployed()); + pdpUpdatemessage.getPoliciesToBeDeployed()); requestMap.addRequest(pdpUpdatemessage, pdpStateChangeMessage); LOGGER.debug("Sent PdpUpdate message - {}", pdpUpdatemessage); diff --git a/main/src/main/java/org/onap/policy/pap/main/notification/DeploymentStatus.java b/main/src/main/java/org/onap/policy/pap/main/notification/DeploymentStatus.java index 087383f4..20e59339 100644 --- a/main/src/main/java/org/onap/policy/pap/main/notification/DeploymentStatus.java +++ b/main/src/main/java/org/onap/policy/pap/main/notification/DeploymentStatus.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,13 +33,12 @@ import java.util.function.BiPredicate; import java.util.stream.Collectors; import lombok.AccessLevel; import lombok.Getter; -import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.pap.concepts.PolicyNotification; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus.State; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; import org.onap.policy.pap.main.notification.StatusAction.Action; +import org.onap.policy.pap.main.service.PolicyStatusService; /** * Collection of Policy Deployment Status records. The sequence of method invocations @@ -70,16 +70,16 @@ public class DeploymentStatus { */ private DeploymentTracker tracker = new DeploymentTracker(); - private PolicyModelsProvider provider; + private PolicyStatusService policyStatusService; /** * Constructs the object. * - * @param provider the provider to use to access the DB + * @param policyStatusService the policyStatusService */ - public DeploymentStatus(PolicyModelsProvider provider) { - this.provider = provider; + public DeploymentStatus(PolicyStatusService policyStatusService) { + this.policyStatusService = policyStatusService; } /** @@ -100,16 +100,15 @@ public class DeploymentStatus { * Loads policy deployment status associated with the given PDP group. * * @param pdpGroup group whose records are to be loaded - * @throws PfModelException if an error occurs */ - public void loadByGroup(String pdpGroup) throws PfModelException { + public void loadByGroup(String pdpGroup) { if (pdpGroupLoaded.contains(pdpGroup)) { return; } pdpGroupLoaded.add(pdpGroup); - for (PdpPolicyStatus status : provider.getGroupPolicyStatus(pdpGroup)) { + for (PdpPolicyStatus status : policyStatusService.getGroupPolicyStatus(pdpGroup)) { var status2 = new StatusAction(Action.UNCHANGED, status); recordMap.put(new StatusKey(status), status2); tracker.add(status2); @@ -153,7 +152,7 @@ public class DeploymentStatus { } } - provider.cudPolicyStatus(created, updated, deleted); + policyStatusService.cudPolicyStatus(created, updated, deleted); /* * update the records to indicate everything is now unchanged (i.e., matches what diff --git a/main/src/main/java/org/onap/policy/pap/main/notification/PolicyNotifier.java b/main/src/main/java/org/onap/policy/pap/main/notification/PolicyNotifier.java index 824d1dbd..14eb263a 100644 --- a/main/src/main/java/org/onap/policy/pap/main/notification/PolicyNotifier.java +++ b/main/src/main/java/org/onap/policy/pap/main/notification/PolicyNotifier.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,30 +23,32 @@ package org.onap.policy.pap.main.notification; import java.util.Set; -import lombok.AllArgsConstructor; -import org.onap.policy.models.base.PfModelException; +import lombok.RequiredArgsConstructor; +import lombok.Setter; import org.onap.policy.models.pap.concepts.PolicyNotification; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; import org.onap.policy.pap.main.comm.Publisher; import org.onap.policy.pap.main.comm.QueueToken; +import org.onap.policy.pap.main.service.PolicyStatusService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; /** * Notifier for completion of policy updates. */ -@AllArgsConstructor +@RequiredArgsConstructor +@Component public class PolicyNotifier { private static final Logger logger = LoggerFactory.getLogger(PolicyNotifier.class); + private final PolicyStatusService policyStatusService; + /** * Notification publisher. */ - private final Publisher publisher; - - private final PolicyModelsProviderFactoryWrapper daoFactory; + @Setter + private Publisher publisher; /** * Processes a response from a PDP. @@ -59,8 +62,8 @@ public class PolicyNotifier { public synchronized void processResponse(String pdp, String pdpGroup, Set expectedPolicies, Set actualPolicies) { - try (PolicyModelsProvider dao = daoFactory.create()) { - DeploymentStatus status = makeDeploymentTracker(dao); + try { + DeploymentStatus status = makeDeploymentTracker(); status.loadByGroup(pdpGroup); status.completeDeploy(pdp, expectedPolicies, actualPolicies); @@ -69,7 +72,7 @@ public class PolicyNotifier { publish(notification); - } catch (PfModelException | RuntimeException e) { + } catch (RuntimeException e) { logger.warn("cannot update deployment status", e); } } @@ -88,7 +91,7 @@ public class PolicyNotifier { // the following methods may be overridden by junit tests - protected DeploymentStatus makeDeploymentTracker(PolicyModelsProvider dao) { - return new DeploymentStatus(dao); + protected DeploymentStatus makeDeploymentTracker() { + return new DeploymentStatus(policyStatusService); } } diff --git a/main/src/main/java/org/onap/policy/pap/main/parameters/PapParameterGroup.java b/main/src/main/java/org/onap/policy/pap/main/parameters/PapParameterGroup.java index 4f08069f..6165d422 100644 --- a/main/src/main/java/org/onap/policy/pap/main/parameters/PapParameterGroup.java +++ b/main/src/main/java/org/onap/policy/pap/main/parameters/PapParameterGroup.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,7 +32,6 @@ import org.onap.policy.common.parameters.annotations.NotBlank; import org.onap.policy.common.parameters.annotations.NotNull; import org.onap.policy.common.parameters.annotations.Valid; import org.onap.policy.common.parameters.validation.ParameterGroupConstraint; -import org.onap.policy.models.provider.PolicyModelsProviderParameters; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; @@ -51,9 +50,6 @@ public class PapParameterGroup extends ParameterGroupImpl { @Valid @ParameterGroupConstraint private PdpParameters pdpParameters; - @Valid - @ParameterGroupConstraint - private PolicyModelsProviderParameters databaseProviderParameters; private boolean savePdpStatisticsInDb; @Valid @ParameterGroupConstraint diff --git a/main/src/main/java/org/onap/policy/pap/main/parameters/PdpModifyRequestMapParams.java b/main/src/main/java/org/onap/policy/pap/main/parameters/PdpModifyRequestMapParams.java index 4cf5ace8..bca00e87 100644 --- a/main/src/main/java/org/onap/policy/pap/main/parameters/PdpModifyRequestMapParams.java +++ b/main/src/main/java/org/onap/policy/pap/main/parameters/PdpModifyRequestMapParams.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,10 +26,8 @@ import lombok.Getter; import org.onap.policy.common.endpoints.listeners.RequestIdDispatcher; import org.onap.policy.models.pdp.concepts.PdpMessage; import org.onap.policy.models.pdp.concepts.PdpStatus; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; import org.onap.policy.pap.main.comm.Publisher; import org.onap.policy.pap.main.comm.TimerManager; -import org.onap.policy.pap.main.notification.PolicyNotifier; /** @@ -45,8 +43,6 @@ public class PdpModifyRequestMapParams { private PdpParameters params; private TimerManager updateTimers; private TimerManager stateChangeTimers; - private PolicyModelsProviderFactoryWrapper daoFactory; - private PolicyNotifier policyNotifier; private boolean savePdpStatistics; /** @@ -80,13 +76,5 @@ public class PdpModifyRequestMapParams { if (stateChangeTimers == null) { throw new IllegalArgumentException("missing stateChangeTimers"); } - - if (daoFactory == null) { - throw new IllegalArgumentException("missing DAO factory"); - } - - if (policyNotifier == null) { - throw new IllegalArgumentException("missing policy notifier"); - } } } diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupHealthCheckProvider.java b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupHealthCheckProvider.java index 74a89046..6043909e 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupHealthCheckProvider.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupHealthCheckProvider.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,16 +24,14 @@ package org.onap.policy.pap.main.rest; import java.util.ArrayList; import java.util.List; +import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.tuple.Pair; -import org.onap.policy.common.utils.services.Registry; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.pdp.concepts.Pdp; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpSubGroup; import org.onap.policy.models.pdp.concepts.Pdps; -import org.onap.policy.models.provider.PolicyModelsProvider; -import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; +import org.onap.policy.pap.main.service.PdpGroupService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; @@ -45,10 +43,13 @@ import org.springframework.stereotype.Service; * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ @Service +@RequiredArgsConstructor public class PdpGroupHealthCheckProvider { private static final Logger LOGGER = LoggerFactory.getLogger(PdpGroupHealthCheckProvider.class); + private final PdpGroupService pdpGroupService; + /** * Returns health status of all PDPs. * @@ -58,18 +59,14 @@ public class PdpGroupHealthCheckProvider { public Pair fetchPdpGroupHealthStatus() throws PfModelException { final var pdps = new Pdps(); - final PolicyModelsProviderFactoryWrapper modelProviderWrapper = - Registry.get(PapConstants.REG_PAP_DAO_FACTORY, PolicyModelsProviderFactoryWrapper.class); - try (PolicyModelsProvider databaseProvider = modelProviderWrapper.create()) { - final List groups = databaseProvider.getPdpGroups(null); - final List pdpList = new ArrayList<>(); - for (final PdpGroup group : groups) { - for (final PdpSubGroup subGroup : group.getPdpSubgroups()) { - pdpList.addAll(subGroup.getPdpInstances()); - } + final List groups = pdpGroupService.getPdpGroups(); + final List pdpList = new ArrayList<>(); + for (final PdpGroup group : groups) { + for (final PdpSubGroup subGroup : group.getPdpSubgroups()) { + pdpList.addAll(subGroup.getPdpInstances()); } - pdps.setPdpList(pdpList); } + pdps.setPdpList(pdpList); LOGGER.debug("PdpGroup HealthCheck Response - {}", pdps); return Pair.of(HttpStatus.OK, pdps); } diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupQueryControllerV1.java b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupQueryControllerV1.java index 03a853ba..18a39333 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupQueryControllerV1.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupQueryControllerV1.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019,2021 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,9 +32,11 @@ import io.swagger.annotations.ExtensionProperty; import io.swagger.annotations.ResponseHeader; import java.util.UUID; import lombok.RequiredArgsConstructor; -import org.apache.commons.lang3.tuple.Pair; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.pdp.concepts.PdpGroups; +import org.onap.policy.pap.main.service.PdpGroupService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; @@ -52,7 +54,9 @@ import org.springframework.web.bind.annotation.RestController; @RequiredArgsConstructor public class PdpGroupQueryControllerV1 extends PapRestControllerV1 { - private final PdpGroupQueryProvider provider; + private static final Logger LOGGER = LoggerFactory.getLogger(PdpGroupQueryControllerV1.class); + + private final PdpGroupService pdpGroupService; /** * Queries details of all PDP groups. @@ -94,8 +98,11 @@ public class PdpGroupQueryControllerV1 extends PapRestControllerV1 { required = false, value = REQUEST_ID_NAME) final UUID requestId) throws PfModelException { - final Pair pair = provider.fetchPdpGroupDetails(); - return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.status(pair.getLeft())), requestId) - .body(pair.getRight()); + final var pdpGroups = new PdpGroups(); + pdpGroups.setGroups(pdpGroupService.getPdpGroups()); + LOGGER.debug("PdpGroup Query Response - {}", pdpGroups); + + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.status(HttpStatus.OK)), requestId) + .body(pdpGroups); } } diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupQueryProvider.java b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupQueryProvider.java deleted file mode 100644 index f1a22f50..00000000 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupQueryProvider.java +++ /dev/null @@ -1,64 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. - * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.pap.main.rest; - -import org.apache.commons.lang3.tuple.Pair; -import org.onap.policy.common.utils.services.Registry; -import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.pdp.concepts.PdpGroups; -import org.onap.policy.models.provider.PolicyModelsProvider; -import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Service; - -/** - * Provider for PAP component to query details of all PDP groups. - * - * @author Ram Krishna Verma (ram.krishna.verma@est.tech) - */ -@Service -public class PdpGroupQueryProvider { - - private static final Logger LOGGER = LoggerFactory.getLogger(PdpGroupQueryProvider.class); - - /** - * Queries details of all PDP groups. - * - * @return a pair containing the status and the response - * @throws PfModelException in case of errors - */ - public Pair fetchPdpGroupDetails() throws PfModelException { - - final var pdpGroups = new PdpGroups(); - final PolicyModelsProviderFactoryWrapper modelProviderWrapper = - Registry.get(PapConstants.REG_PAP_DAO_FACTORY, PolicyModelsProviderFactoryWrapper.class); - try (PolicyModelsProvider databaseProvider = modelProviderWrapper.create()) { - pdpGroups.setGroups(databaseProvider.getPdpGroups(null)); - } - LOGGER.debug("PdpGroup Query Response - {}", pdpGroups); - return Pair.of(HttpStatus.OK, pdpGroups); - } -} diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupStateChangeProvider.java b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupStateChangeProvider.java index 5aaaf4ab..b1f7f665 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupStateChangeProvider.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupStateChangeProvider.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019-2021 Nordix Foundation. * Modifications Copyright (C) 2019-2021 AT&T Intellectual Property. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,11 +31,12 @@ import org.onap.policy.models.pdp.concepts.Pdp; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpSubGroup; import org.onap.policy.models.pdp.enums.PdpState; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.onap.policy.pap.main.comm.PdpMessageGenerator; +import org.onap.policy.pap.main.service.PdpGroupService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; @@ -49,6 +50,9 @@ public class PdpGroupStateChangeProvider extends PdpMessageGenerator { private static final Logger LOGGER = LoggerFactory.getLogger(PdpGroupStateChangeProvider.class); + @Autowired + private PdpGroupService pdpGroupService; + /** * Constructs the object. */ @@ -83,43 +87,37 @@ public class PdpGroupStateChangeProvider extends PdpMessageGenerator { } private void handleActiveState(final String groupName) throws PfModelException { - try (PolicyModelsProvider databaseProvider = modelProviderWrapper.create()) { - final List pdpGroups = databaseProvider.getPdpGroups(groupName); - if (!pdpGroups.isEmpty() && !PdpState.ACTIVE.equals(pdpGroups.get(0).getPdpGroupState())) { - updatePdpGroupAndPdp(databaseProvider, pdpGroups, PdpState.ACTIVE); - sendPdpMessage(pdpGroups.get(0), PdpState.ACTIVE, databaseProvider); - } + final List pdpGroups = pdpGroupService.getPdpGroups(groupName); + if (!pdpGroups.isEmpty() && !PdpState.ACTIVE.equals(pdpGroups.get(0).getPdpGroupState())) { + updatePdpGroupAndPdp(pdpGroups, PdpState.ACTIVE); + sendPdpMessage(pdpGroups.get(0), PdpState.ACTIVE); } } private void handlePassiveState(final String groupName) throws PfModelException { - try (PolicyModelsProvider databaseProvider = modelProviderWrapper.create()) { - final List pdpGroups = databaseProvider.getPdpGroups(groupName); - if (!pdpGroups.isEmpty() && !PdpState.PASSIVE.equals(pdpGroups.get(0).getPdpGroupState())) { - updatePdpGroupAndPdp(databaseProvider, pdpGroups, PdpState.PASSIVE); - sendPdpMessage(pdpGroups.get(0), PdpState.PASSIVE, databaseProvider); - } + final List pdpGroups = pdpGroupService.getPdpGroups(groupName); + if (!pdpGroups.isEmpty() && !PdpState.PASSIVE.equals(pdpGroups.get(0).getPdpGroupState())) { + updatePdpGroupAndPdp(pdpGroups, PdpState.PASSIVE); + sendPdpMessage(pdpGroups.get(0), PdpState.PASSIVE); } } - private void updatePdpGroupAndPdp(final PolicyModelsProvider databaseProvider, final List pdpGroups, - final PdpState pdpState) throws PfModelException { + private void updatePdpGroupAndPdp(final List pdpGroups, final PdpState pdpState) { pdpGroups.get(0).setPdpGroupState(pdpState); for (final PdpSubGroup subGroup : pdpGroups.get(0).getPdpSubgroups()) { for (final Pdp pdp : subGroup.getPdpInstances()) { pdp.setPdpState(pdpState); } } - databaseProvider.updatePdpGroups(pdpGroups); + pdpGroupService.updatePdpGroups(pdpGroups); LOGGER.debug("Updated PdpGroup and Pdp in DB - {} ", pdpGroups); } - private void sendPdpMessage(final PdpGroup pdpGroup, final PdpState pdpState, - final PolicyModelsProvider databaseProvider) throws PfModelException { + private void sendPdpMessage(final PdpGroup pdpGroup, final PdpState pdpState) throws PfModelException { String pdpGroupName = pdpGroup.getName(); for (final PdpSubGroup subGroup : pdpGroup.getPdpSubgroups()) { - List policies = getToscaPolicies(subGroup, databaseProvider); + List policies = getToscaPolicies(subGroup); for (final Pdp pdp : subGroup.getPdpInstances()) { String pdpInstanceId = pdp.getInstanceId(); final var pdpUpdatemessage = @@ -128,7 +126,7 @@ public class PdpGroupStateChangeProvider extends PdpMessageGenerator { final var pdpStateChangeMessage = createPdpStateChangeMessage(pdpGroupName, subGroup, pdpInstanceId, pdpState); updateDeploymentStatus(pdpGroupName, subGroup.getPdpType(), pdpInstanceId, - pdpStateChangeMessage.getState(), databaseProvider, pdpUpdatemessage.getPoliciesToBeDeployed()); + pdpStateChangeMessage.getState(), pdpUpdatemessage.getPoliciesToBeDeployed()); requestMap.addRequest(pdpUpdatemessage, pdpStateChangeMessage); LOGGER.debug("Sent PdpUpdate message - {}", pdpUpdatemessage); LOGGER.debug("Sent PdpStateChange message - {}", pdpStateChangeMessage); diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyAuditControllerV1.java b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyAuditControllerV1.java index e195a79b..9eeef2be 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyAuditControllerV1.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyAuditControllerV1.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2021 Bell Canada. All rights reserved. + * Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,7 +32,7 @@ import java.util.UUID; import lombok.RequiredArgsConstructor; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.pap.concepts.PolicyAudit; -import org.onap.policy.models.pap.persistence.provider.PolicyAuditProvider.AuditFilter; +import org.onap.policy.pap.main.service.PolicyAuditService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; @@ -53,7 +53,7 @@ public class PolicyAuditControllerV1 extends PapRestControllerV1 { public static final String NO_AUDIT_RECORD_FOUND = "No records found matching the input parameters"; - private final PolicyAuditProvider provider; + private final PolicyAuditService policyAuditService; /** * Queries audit information of all policies. @@ -111,9 +111,8 @@ public class PolicyAuditControllerV1 extends PapRestControllerV1 { value = "endTime") final Long endTime) throws PfModelException { - return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId) - .body(provider.getAuditRecords(AuditFilter.builder().recordNum(recordCount) - .fromDate(convertEpochtoInstant(startTime)).toDate(convertEpochtoInstant(endTime)).build())); + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId).body(policyAuditService + .getAuditRecords(recordCount, convertEpochtoInstant(startTime), convertEpochtoInstant(endTime))); } /** @@ -173,10 +172,8 @@ public class PolicyAuditControllerV1 extends PapRestControllerV1 { value = "endTime") final Long endTime, @ApiParam(value = "PDP Group Name") @PathVariable("pdpGroupName") String pdpGroupName) throws PfModelException { - return makeOkOrNotFoundResponse(requestId, - provider.getAuditRecords( - AuditFilter.builder().recordNum(recordCount).fromDate((convertEpochtoInstant(startTime))) - .toDate(convertEpochtoInstant(endTime)).pdpGroup(pdpGroupName).build())); + return makeOkOrNotFoundResponse(requestId, policyAuditService.getAuditRecords(pdpGroupName, recordCount, + convertEpochtoInstant(startTime), convertEpochtoInstant(endTime))); } /** @@ -242,10 +239,8 @@ public class PolicyAuditControllerV1 extends PapRestControllerV1 { @ApiParam(value = "Policy Version") @PathVariable(value = "policyVersion") String policyVersion) throws PfModelException { - return makeOkOrNotFoundResponse(requestId, - provider.getAuditRecords(AuditFilter.builder().recordNum(recordCount) - .fromDate(convertEpochtoInstant(startTime)).toDate(convertEpochtoInstant(endTime)) - .pdpGroup(pdpGroupName).name(policyName).version(policyVersion).build())); + return makeOkOrNotFoundResponse(requestId, policyAuditService.getAuditRecords(pdpGroupName, policyName, + policyVersion, recordCount, convertEpochtoInstant(startTime), convertEpochtoInstant(endTime))); } /** @@ -310,10 +305,8 @@ public class PolicyAuditControllerV1 extends PapRestControllerV1 { value = "Policy Version") @PathVariable(required = true, value = "policyVersion") String policyVersion) throws PfModelException { - return makeOkOrNotFoundResponse(requestId, - provider - .getAuditRecords(AuditFilter.builder().recordNum(recordCount).fromDate(convertEpochtoInstant(startTime)) - .toDate(convertEpochtoInstant(endTime)).name(policyName).version(policyVersion).build())); + return makeOkOrNotFoundResponse(requestId, policyAuditService.getAuditRecords(policyName, policyVersion, + recordCount, convertEpochtoInstant(startTime), convertEpochtoInstant(endTime))); } private ResponseEntity makeOkOrNotFoundResponse(UUID requestId, Collection result) { diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyAuditManager.java b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyAuditManager.java index c200bb13..f720d0ca 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyAuditManager.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyAuditManager.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,8 +29,8 @@ import lombok.AccessLevel; import lombok.Getter; import org.onap.policy.models.pap.concepts.PolicyAudit; import org.onap.policy.models.pap.concepts.PolicyAudit.AuditAction; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; +import org.onap.policy.pap.main.service.PolicyAuditService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -48,15 +49,18 @@ public class PolicyAuditManager { @Getter(value = AccessLevel.PROTECTED) private List auditRecords = new ArrayList<>(); - private PolicyModelsProvider provider; + private PolicyAuditService policyAuditService; /** - * Default constructor. + * Constructs the object. + * + * @param policyAuditService the service */ - public PolicyAuditManager(PolicyModelsProvider provider) { - this.provider = provider; + public PolicyAuditManager(PolicyAuditService policyAuditService) { + this.policyAuditService = policyAuditService; } + /** * Builds an audit object. * @@ -107,7 +111,7 @@ public class PolicyAuditManager { if (!auditRecords.isEmpty()) { logger.info("sending audit records to database: {}", auditRecords); try { - provider.createAuditRecords(auditRecords); + policyAuditService.createAuditRecords(auditRecords); auditRecords.clear(); } catch (RuntimeException excpt) { // not throwing the exception to not stop the main request. diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyAuditProvider.java b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyAuditProvider.java deleted file mode 100644 index c3c77a4a..00000000 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyAuditProvider.java +++ /dev/null @@ -1,62 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2021 Bell Canada. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.pap.main.rest; - -import java.util.Collection; -import org.onap.policy.common.utils.services.Registry; -import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.pap.concepts.PolicyAudit; -import org.onap.policy.models.pap.persistence.provider.PolicyAuditProvider.AuditFilter; -import org.onap.policy.models.provider.PolicyModelsProvider; -import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; -import org.springframework.boot.context.event.ApplicationReadyEvent; -import org.springframework.context.event.EventListener; -import org.springframework.stereotype.Service; - -/** - * Provider for PAP component to query policy audit information. - */ -@Service -public class PolicyAuditProvider { - - /** - * Factory for PAP DAO. - */ - private PolicyModelsProviderFactoryWrapper daoFactory; - - @EventListener(ApplicationReadyEvent.class) - public void initialize() { - this.daoFactory = Registry.get(PapConstants.REG_PAP_DAO_FACTORY, PolicyModelsProviderFactoryWrapper.class); - } - - /** - * Gets the audit record of all policies. - * - * @param auditFilter the filter for the query - * @return the audit record of all policies - * @throws PfModelException if a DB error occurs - */ - public Collection getAuditRecords(AuditFilter auditFilter) - throws PfModelException { - try (PolicyModelsProvider dao = daoFactory.create()) { - return dao.getAuditRecords(auditFilter); - } - } -} diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyComponentsHealthCheckProvider.java b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyComponentsHealthCheckProvider.java index 7a490166..d2a730eb 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyComponentsHealthCheckProvider.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyComponentsHealthCheckProvider.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019-2020 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2020-2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2020-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,6 +40,7 @@ import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; +import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.tuple.Pair; import org.onap.policy.common.endpoints.http.client.HttpClient; import org.onap.policy.common.endpoints.http.client.HttpClientConfigException; @@ -47,20 +48,16 @@ import org.onap.policy.common.endpoints.http.client.HttpClientFactory; import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance; import org.onap.policy.common.endpoints.parameters.RestClientParameters; import org.onap.policy.common.endpoints.report.HealthCheckReport; -import org.onap.policy.common.utils.services.Registry; -import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pdp.concepts.Pdp; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpSubGroup; import org.onap.policy.models.pdp.enums.PdpHealthStatus; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; import org.onap.policy.pap.main.parameters.PapParameterGroup; +import org.onap.policy.pap.main.service.PdpGroupService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; @@ -71,6 +68,7 @@ import org.springframework.stereotype.Service; * @author Yehui Wang (yehui.wang@est.tech) */ @Service +@RequiredArgsConstructor public class PolicyComponentsHealthCheckProvider { private static final Logger LOGGER = LoggerFactory.getLogger(PolicyComponentsHealthCheckProvider.class); @@ -80,8 +78,9 @@ public class PolicyComponentsHealthCheckProvider { private static List clients = new ArrayList<>(); private ExecutorService clientHealthCheckExecutorService; - @Autowired - private PapParameterGroup papParameterGroup; + private final PapParameterGroup papParameterGroup; + + private final PdpGroupService pdpGroupService; @Value("${server.ssl.enabled:false}") private boolean isHttps; @@ -157,14 +156,14 @@ public class PolicyComponentsHealthCheckProvider { // Check PDPs, read status from DB try { - List groups = fetchPdpGroups(); + List groups = pdpGroupService.getPdpGroups(); Map> pdpListWithType = fetchPdpsHealthStatus(groups); if (isHealthy && (!verifyNumberOfPdps(groups) || pdpListWithType.values().stream().flatMap(List::stream) .anyMatch(pdp -> !PdpHealthStatus.HEALTHY.equals(pdp.getHealthy())))) { isHealthy = false; } result.put(PapConstants.POLICY_PDPS, pdpListWithType); - } catch (final PfModelException exp) { + } catch (final PfModelRuntimeException exp) { result.put(PapConstants.POLICY_PDPS, exp.getErrorResponse()); isHealthy = false; } @@ -198,16 +197,6 @@ public class PolicyComponentsHealthCheckProvider { return flag; } - private List fetchPdpGroups() throws PfModelException { - List groups = new ArrayList<>(); - final PolicyModelsProviderFactoryWrapper modelProviderWrapper = - Registry.get(PapConstants.REG_PAP_DAO_FACTORY, PolicyModelsProviderFactoryWrapper.class); - try (PolicyModelsProvider databaseProvider = modelProviderWrapper.create()) { - groups = databaseProvider.getPdpGroups(null); - } - return groups; - } - private HealthCheckReport fetchPolicyComponentHealthStatus(HttpClient httpClient) { HealthCheckReport clientReport; try { diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyStatusControllerV1.java b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyStatusControllerV1.java index 43227475..b0de1e7c 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyStatusControllerV1.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyStatusControllerV1.java @@ -4,7 +4,7 @@ * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,7 +34,6 @@ import io.swagger.annotations.ResponseHeader; import java.util.Collection; import java.util.UUID; import lombok.RequiredArgsConstructor; -import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pap.concepts.PolicyStatus; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus; @@ -120,7 +119,7 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { } return makeListOrNotFoundResponse(requestId, result); - } catch (PfModelException | PfModelRuntimeException e) { + } catch (PfModelRuntimeException e) { logger.warn(GET_DEPLOYMENTS_FAILED, e); return addLoggingHeaders( addVersionControlHeaders(ResponseEntity.status(e.getErrorResponse().getResponseCode().getStatusCode())), @@ -183,7 +182,7 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId).body(result); } - } catch (PfModelException | PfModelRuntimeException e) { + } catch (PfModelRuntimeException e) { logger.warn(GET_DEPLOYMENTS_FAILED, e); return addLoggingHeaders( addVersionControlHeaders(ResponseEntity.status(e.getErrorResponse().getResponseCode().getStatusCode())), @@ -244,7 +243,7 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { .body(result.iterator().next()); } - } catch (PfModelException | PfModelRuntimeException e) { + } catch (PfModelRuntimeException e) { logger.warn(GET_DEPLOYMENTS_FAILED, e); return addLoggingHeaders( addVersionControlHeaders(ResponseEntity.status(e.getErrorResponse().getResponseCode().getStatusCode())), @@ -299,7 +298,7 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId) .body(provider.getPolicyStatus()); - } catch (PfModelException | PfModelRuntimeException e) { + } catch (PfModelRuntimeException e) { logger.warn(GET_DEPLOYMENTS_FAILED, e); return addLoggingHeaders( addVersionControlHeaders(ResponseEntity.status(e.getErrorResponse().getResponseCode().getStatusCode())), @@ -365,7 +364,7 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { } return makeListOrNotFoundResponse(requestId, result); - } catch (PfModelException | PfModelRuntimeException e) { + } catch (PfModelRuntimeException e) { logger.warn(GET_DEPLOYMENTS_FAILED, e); return addLoggingHeaders( addVersionControlHeaders(ResponseEntity.status(e.getErrorResponse().getResponseCode().getStatusCode())), @@ -434,7 +433,7 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { .body(result); } - } catch (PfModelException | PfModelRuntimeException e) { + } catch (PfModelRuntimeException e) { logger.warn(GET_DEPLOYMENTS_FAILED, e); return addLoggingHeaders( addVersionControlHeaders(ResponseEntity.status(e.getErrorResponse().getResponseCode().getStatusCode())), @@ -502,7 +501,7 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 { .body(result.iterator().next()); } - } catch (PfModelException | PfModelRuntimeException e) { + } catch (PfModelRuntimeException e) { logger.warn(GET_DEPLOYMENTS_FAILED, e); return addLoggingHeaders( addVersionControlHeaders(ResponseEntity.status(e.getErrorResponse().getResponseCode().getStatusCode())), diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyStatusProvider.java b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyStatusProvider.java index dd133a1a..631c9c03 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyStatusProvider.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyStatusProvider.java @@ -3,7 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -26,48 +26,30 @@ import com.google.re2j.Pattern; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; -import org.onap.policy.common.utils.services.Registry; -import org.onap.policy.models.base.PfModelException; +import lombok.RequiredArgsConstructor; import org.onap.policy.models.pap.concepts.PolicyStatus; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierOptVersion; -import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; import org.onap.policy.pap.main.notification.DeploymentTracker; -import org.springframework.boot.context.event.ApplicationReadyEvent; -import org.springframework.context.event.EventListener; +import org.onap.policy.pap.main.service.PolicyStatusService; import org.springframework.stereotype.Service; /** * Provider for PAP component to query policy deployment status. */ @Service +@RequiredArgsConstructor public class PolicyStatusProvider { - /** - * Factory for PAP DAO. - */ - private PolicyModelsProviderFactoryWrapper daoFactory; - - /** - * Constructs the object. Loads all deployed policies into the internal cache. - */ - @EventListener(ApplicationReadyEvent.class) - public void initialize() { - this.daoFactory = Registry.get(PapConstants.REG_PAP_DAO_FACTORY, PolicyModelsProviderFactoryWrapper.class); - } + private final PolicyStatusService policyStatusService; /** * Gets the deployment status of all policies. * * @return the deployment status of all policies - * @throws PfModelException if a DB error occurs */ - public Collection getStatus() throws PfModelException { - try (PolicyModelsProvider dao = daoFactory.create()) { - return accumulate(dao.getAllPolicyStatus()); - } + public Collection getStatus() { + return accumulate(policyStatusService.getAllPolicyStatus()); } /** @@ -75,12 +57,9 @@ public class PolicyStatusProvider { * * @param policy policy of interest * @return the deployment status of all policies - * @throws PfModelException if a DB error occurs */ - public Collection getStatus(ToscaConceptIdentifierOptVersion policy) throws PfModelException { - try (PolicyModelsProvider dao = daoFactory.create()) { - return accumulate(dao.getAllPolicyStatus(policy)); - } + public Collection getStatus(ToscaConceptIdentifierOptVersion policy) { + return accumulate(policyStatusService.getAllPolicyStatus(policy)); } /** @@ -88,16 +67,12 @@ public class PolicyStatusProvider { * * @param patternString policy of interest * @return the deployment status of all policies - * @throws PfModelException if a DB error occurs */ - public Collection getByRegex(String patternString) throws PfModelException { + public Collection getByRegex(String patternString) { // try to make pattern out of regex final var pattern = Pattern.compile(patternString); // get all the statuses - final List policyStatuses; - try (PolicyModelsProvider dao = daoFactory.create()) { - policyStatuses = dao.getAllPolicyStatus(); - } + final List policyStatuses = policyStatusService.getAllPolicyStatus(); // filter out statuses with the wrong name final Collection pdpPolicyStatuses = filterWithPattern(pattern, policyStatuses); @@ -129,41 +104,30 @@ public class PolicyStatusProvider { * Gets the status of all policies. * * @return the status of all policies - * @throws PfModelException if a DB error occurs */ - public Collection getPolicyStatus() throws PfModelException { - try (PolicyModelsProvider dao = daoFactory.create()) { - return dao.getAllPolicyStatus(); - } + public Collection getPolicyStatus() { + return policyStatusService.getAllPolicyStatus(); } /** * Gets the status of policies in a PdpGroup. * * @param pdpGroupName the pdp group - * @return the deployment status of policies - * @throws PfModelException if a DB error occurs */ - public Collection getPolicyStatus(String pdpGroupName) throws PfModelException { - try (PolicyModelsProvider dao = daoFactory.create()) { - return dao.getGroupPolicyStatus(pdpGroupName); - } + public Collection getPolicyStatus(String pdpGroupName) { + return policyStatusService.getGroupPolicyStatus(pdpGroupName); } /** * Gets the status of a policy in a PdpGroup. * * @param pdpGroupName the pdp group - * @param policy the policy + * @param policy the policy * @return the deployment status of the policy - * @throws PfModelException if a DB error occurs */ - public Collection getPolicyStatus(String pdpGroupName, ToscaConceptIdentifierOptVersion policy) - throws PfModelException { - try (PolicyModelsProvider dao = daoFactory.create()) { - return dao.getAllPolicyStatus(policy).stream().filter(p -> p.getPdpGroup().equals(pdpGroupName)) - .collect(Collectors.toList()); - } + public Collection getPolicyStatus(String pdpGroupName, ToscaConceptIdentifierOptVersion policy) { + return policyStatusService.getAllPolicyStatus(policy).stream().filter(p -> p.getPdpGroup().equals(pdpGroupName)) + .collect(Collectors.toList()); } /** @@ -172,10 +136,8 @@ public class PolicyStatusProvider { * @param pdpGroupName the pdp group * @param patternString regex * @return the deployment status of policies - * @throws PfModelException if a DB error occurs */ - public Collection getPolicyStatusByRegex(String pdpGroupName, String patternString) - throws PfModelException { + public Collection getPolicyStatusByRegex(String pdpGroupName, String patternString) { final var pattern = Pattern.compile(patternString); // get all the statuses final Collection policyStatuses = getPolicyStatus(pdpGroupName); diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyUndeployerImpl.java b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyUndeployerImpl.java index ea55f815..004d4ada 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyUndeployerImpl.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyUndeployerImpl.java @@ -4,7 +4,7 @@ * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2020-2021 Nordix Foundation. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,20 +36,15 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.onap.policy.pap.main.comm.PolicyUndeployer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; /** * Implementation of policy undeployer. */ +@Component public class PolicyUndeployerImpl extends ProviderBase implements PolicyUndeployer { private static final Logger logger = LoggerFactory.getLogger(PolicyUndeployerImpl.class); - /** - * Constructs the object. - */ - public PolicyUndeployerImpl() { - super.initialize(); - } - @Override public void undeploy(String group, String subgroup, Collection policies) throws PfModelException { diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/ProviderBase.java b/main/src/main/java/org/onap/policy/pap/main/rest/ProviderBase.java index ad6ff21e..c1c63c7f 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/ProviderBase.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/ProviderBase.java @@ -4,7 +4,7 @@ * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2020-2021 Nordix Foundation. - * Modifications Copyright (C) 2020 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2020,2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,14 +32,17 @@ import org.onap.policy.models.pdp.concepts.Pdp; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpSubGroup; import org.onap.policy.models.pdp.concepts.PdpUpdate; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierOptVersion; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; import org.onap.policy.pap.main.comm.PdpModifyRequestMap; import org.onap.policy.pap.main.notification.PolicyNotifier; +import org.onap.policy.pap.main.service.PdpGroupService; +import org.onap.policy.pap.main.service.PolicyAuditService; +import org.onap.policy.pap.main.service.PolicyStatusService; +import org.onap.policy.pap.main.service.ToscaServiceTemplateService; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.event.EventListener; @@ -71,10 +74,63 @@ public abstract class ProviderBase { */ private PolicyNotifier notifier; + private ToscaServiceTemplateService toscaService; + + private PdpGroupService pdpGroupService; + + private PolicyStatusService policyStatusService; + + private PolicyAuditService policyAuditService; + + /** + * The setter method for injecting into Spring context. + * + * @param toscaService the toscaService to set + */ + @Autowired + public final void setToscaService(ToscaServiceTemplateService toscaService) { + this.toscaService = toscaService; + } + + /** + * The setter method for injecting into Spring context. + * + * @param pdpGroupService the pdpGroupService to set + */ + @Autowired + public final void setPdpGroupService(PdpGroupService pdpGroupService) { + this.pdpGroupService = pdpGroupService; + } + /** - * Factory for PAP DAO. + * The setter method for injecting into Spring context. + * + * @param policyStatusService the policyStatusService to set + */ + @Autowired + public final void setPolicyStatusService(PolicyStatusService policyStatusService) { + this.policyStatusService = policyStatusService; + } + + /** + * The setter method for injecting into Spring context. + * + * @param policyAuditService the policyAuditService to set */ - private PolicyModelsProviderFactoryWrapper daoFactory; + @Autowired + public final void setPolicyAuditService(PolicyAuditService policyAuditService) { + this.policyAuditService = policyAuditService; + } + + /** + * The setter method for injecting into Spring context. + * + * @param policyNotifier the policyNotifier to set + */ + @Autowired + public final void setPolicyNotifier(PolicyNotifier policyNotifier) { + this.notifier = policyNotifier; + } /** * Initializes the parameters.. @@ -83,8 +139,6 @@ public abstract class ProviderBase { public void initialize() { this.updateLock = Registry.get(PapConstants.REG_PDP_MODIFY_LOCK, Object.class); this.requestMap = Registry.get(PapConstants.REG_PDP_MODIFY_MAP, PdpModifyRequestMap.class); - this.daoFactory = Registry.get(PapConstants.REG_PAP_DAO_FACTORY, PolicyModelsProviderFactoryWrapper.class); - this.notifier = Registry.get(PapConstants.REG_POLICY_NOTIFIER, PolicyNotifier.class); } /** @@ -102,15 +156,15 @@ public abstract class ProviderBase { SessionData data; var notif = new PolicyNotification(); - try (PolicyModelsProvider dao = daoFactory.create()) { + try { - data = new SessionData(dao, user); + data = new SessionData(user, toscaService, pdpGroupService, policyStatusService, policyAuditService); processor.accept(data, request); // make all of the DB updates data.updateDb(notif); - } catch (PfModelException | PfModelRuntimeException e) { + } catch (PfModelRuntimeException e) { throw e; } catch (RuntimeException e) { diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/SessionData.java b/main/src/main/java/org/onap/policy/pap/main/rest/SessionData.java index 32103159..2abce9b1 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/SessionData.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/SessionData.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,7 +41,6 @@ import org.onap.policy.models.pdp.concepts.PdpGroupFilter; import org.onap.policy.models.pdp.concepts.PdpStateChange; import org.onap.policy.models.pdp.concepts.PdpUpdate; import org.onap.policy.models.pdp.enums.PdpState; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierOptVersion; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; @@ -48,6 +48,10 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType; import org.onap.policy.models.tosca.authorative.concepts.ToscaTypedEntityFilter; import org.onap.policy.models.tosca.authorative.concepts.ToscaTypedEntityFilter.ToscaTypedEntityFilterBuilder; import org.onap.policy.pap.main.notification.DeploymentStatus; +import org.onap.policy.pap.main.service.PdpGroupService; +import org.onap.policy.pap.main.service.PolicyAuditService; +import org.onap.policy.pap.main.service.PolicyStatusService; +import org.onap.policy.pap.main.service.ToscaServiceTemplateService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -62,11 +66,6 @@ public class SessionData { */ private static final Pattern VERSION_PREFIX_PAT = Pattern.compile("[^.]+(?:[.][^.]+)?"); - /** - * DB provider. - */ - private final PolicyModelsProvider dao; - /** * Maps a group name to its group data. This accumulates the set of groups to be created and updated when the REST * call completes. @@ -117,16 +116,25 @@ public class SessionData { private PolicyAuditManager auditManager; + private ToscaServiceTemplateService toscaService; + + private PdpGroupService pdpGroupService; + /** * Constructs the object. * - * @param dao DAO provider * @param user user triggering the request - */ - public SessionData(PolicyModelsProvider dao, String user) { - this.dao = dao; - this.deployStatus = makeDeploymentStatus(dao); - this.auditManager = makePolicyAuditManager(dao); + * @param policyAuditService the policyAuditService + * @param policyStatusService the policyStatusService + * @param pdpGroupService the pdpGroupService + * @param toscaService the toscaService + */ + public SessionData(String user, ToscaServiceTemplateService toscaService, PdpGroupService pdpGroupService, + PolicyStatusService policyStatusService, PolicyAuditService policyAuditService) { + this.toscaService = toscaService; + this.pdpGroupService = pdpGroupService; + this.deployStatus = makeDeploymentStatus(policyStatusService); + this.auditManager = makePolicyAuditManager(policyAuditService); this.user = user; } @@ -143,7 +151,7 @@ public class SessionData { ToscaPolicyType type = typeCache.get(desiredType); if (type == null) { - List lst = dao.getPolicyTypeList(desiredType.getName(), desiredType.getVersion()); + List lst = toscaService.getPolicyTypeList(desiredType.getName(), desiredType.getVersion()); if (lst.isEmpty()) { return null; } @@ -168,10 +176,10 @@ public class SessionData { ToscaPolicy policy = policyCache.get(desiredPolicy); if (policy == null) { ToscaTypedEntityFilterBuilder filterBuilder = - ToscaTypedEntityFilter.builder().name(desiredPolicy.getName()); + ToscaTypedEntityFilter.builder().name(desiredPolicy.getName()); setPolicyFilterVersion(filterBuilder, desiredPolicy.getVersion()); - List lst = dao.getFilteredPolicyList(filterBuilder.build()); + List lst = toscaService.getFilteredPolicyList(filterBuilder.build()); if (lst.isEmpty()) { return null; } @@ -336,7 +344,7 @@ public class SessionData { GroupData data = groupCache.get(name); if (data == null) { - List lst = dao.getPdpGroups(name); + List lst = pdpGroupService.getPdpGroups(name); if (lst.isEmpty()) { logger.info("unknown group {}", name); return null; @@ -372,7 +380,7 @@ public class SessionData { PdpGroupFilter filter = PdpGroupFilter.builder().policyTypeList(Collections.singletonList(type)) .groupState(PdpState.ACTIVE).build(); - List groups = dao.getFilteredPdpGroups(filter); + List groups = pdpGroupService.getFilteredPdpGroups(filter); data = groups.stream().map(this::addGroup).collect(Collectors.toList()); type2groups.put(type, data); @@ -423,17 +431,15 @@ public class SessionData { * Update the DB with the changes. * * @param notification notification to which to add policy status - * - * @throws PfModelException if an error occurred */ - public void updateDb(PolicyNotification notification) throws PfModelException { + public void updateDb(PolicyNotification notification) { // create new groups List created = groupCache.values().stream().filter(GroupData::isNew).collect(Collectors.toList()); if (!created.isEmpty()) { if (logger.isInfoEnabled()) { created.forEach(group -> logger.info("creating DB group {}", group.getGroup().getName())); } - dao.createPdpGroups(created.stream().map(GroupData::getGroup).collect(Collectors.toList())); + pdpGroupService.createPdpGroups(created.stream().map(GroupData::getGroup).collect(Collectors.toList())); } // update existing groups @@ -443,7 +449,7 @@ public class SessionData { if (logger.isInfoEnabled()) { updated.forEach(group -> logger.info("updating DB group {}", group.getGroup().getName())); } - dao.updatePdpGroups(updated.stream().map(GroupData::getGroup).collect(Collectors.toList())); + pdpGroupService.updatePdpGroups(updated.stream().map(GroupData::getGroup).collect(Collectors.toList())); } // send audits records to DB @@ -457,11 +463,10 @@ public class SessionData { * Deletes a group from the DB, immediately (i.e., without caching the request to be executed later). * * @param group the group to be deleted - * @throws PfModelException if an error occurred */ - public void deleteGroupFromDb(PdpGroup group) throws PfModelException { + public void deleteGroupFromDb(PdpGroup group) { logger.info("deleting DB group {}", group.getName()); - dao.deletePdpGroup(group.getName()); + pdpGroupService.deletePdpGroup(group.getName()); } /** @@ -525,11 +530,11 @@ public class SessionData { // these may be overridden by junit tests - protected DeploymentStatus makeDeploymentStatus(PolicyModelsProvider dao) { - return new DeploymentStatus(dao); + protected DeploymentStatus makeDeploymentStatus(PolicyStatusService policyStatusService) { + return new DeploymentStatus(policyStatusService); } - protected PolicyAuditManager makePolicyAuditManager(PolicyModelsProvider dao) { - return new PolicyAuditManager(dao); + protected PolicyAuditManager makePolicyAuditManager(PolicyAuditService policyAuditService) { + return new PolicyAuditManager(policyAuditService); } } diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/StatisticsRestControllerV1.java b/main/src/main/java/org/onap/policy/pap/main/rest/StatisticsRestControllerV1.java index 641e2ba9..f1251cbd 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/StatisticsRestControllerV1.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/StatisticsRestControllerV1.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019-2021 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,9 +35,8 @@ import java.util.List; import java.util.Map; import java.util.UUID; import lombok.RequiredArgsConstructor; -import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.pdp.concepts.PdpStatistics; -import org.onap.policy.models.pdp.persistence.provider.PdpFilterParameters; +import org.onap.policy.pap.main.service.PdpStatisticsService; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -56,7 +55,7 @@ import org.springframework.web.bind.annotation.RestController; @RequiredArgsConstructor public class StatisticsRestControllerV1 extends PapRestControllerV1 { - private final StatisticsRestProvider provider; + private final PdpStatisticsService pdpStatisticsService; /** * get statistics of PAP. @@ -77,15 +76,13 @@ public class StatisticsRestControllerV1 extends PapRestControllerV1 { required = false, value = REQUEST_ID_NAME) final UUID requestId) { return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId) - .body(provider.fetchCurrentStatistics()); + .body(pdpStatisticsService.fetchCurrentStatistics()); } /** * get all statistics of PDP groups. * - * * @return a response - * @throws PfModelException the exception */ @GetMapping("pdps/statistics") @ApiOperation(value = "Fetch statistics for all PDP Groups and subgroups in the system", @@ -126,10 +123,9 @@ public class StatisticsRestControllerV1 extends PapRestControllerV1 { value = "startTime") final Long startTime, @ApiParam(value = "End time in epoch timestamp") @RequestParam( required = false, - value = "endTime") final Long endTime) throws PfModelException { - return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId) - .body(provider.fetchDatabaseStatistics(PdpFilterParameters.builder().recordNum(recordCount) - .startTime(convertEpochtoInstant(startTime)).endTime(convertEpochtoInstant(endTime)).build())); + value = "endTime") final Long endTime) { + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId).body(pdpStatisticsService + .fetchDatabaseStatistics(recordCount, convertEpochtoInstant(startTime), convertEpochtoInstant(endTime))); } /** @@ -137,7 +133,6 @@ public class StatisticsRestControllerV1 extends PapRestControllerV1 { * * @param groupName name of the PDP group * @return a response - * @throws PfModelException the exception */ @GetMapping("pdps/statistics/{group}") @ApiOperation(value = "Fetch current statistics for given PDP Group", @@ -178,10 +173,10 @@ public class StatisticsRestControllerV1 extends PapRestControllerV1 { value = "startTime") final Long startTime, @ApiParam(value = "End time in epoch timestamp") @RequestParam( required = false, - value = "endTime") final Long endTime) throws PfModelException { + value = "endTime") final Long endTime) { return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId) - .body(provider.fetchDatabaseStatistics(PdpFilterParameters.builder().group(groupName).recordNum(recordCount) - .startTime(convertEpochtoInstant(startTime)).endTime(convertEpochtoInstant(endTime)).build())); + .body(pdpStatisticsService.fetchDatabaseStatistics(groupName, recordCount, convertEpochtoInstant(startTime), + convertEpochtoInstant(endTime))); } /** @@ -190,7 +185,6 @@ public class StatisticsRestControllerV1 extends PapRestControllerV1 { * @param groupName name of the PDP group * @param subType type of the sub PDP group * @return a response - * @throws PfModelException the exception */ @GetMapping("pdps/statistics/{group}/{type}") @ApiOperation(value = "Fetch statistics for the specified subgroup", @@ -232,11 +226,10 @@ public class StatisticsRestControllerV1 extends PapRestControllerV1 { value = "startTime") final Long startTime, @ApiParam(value = "End time in epoch timestamp") @RequestParam( required = false, - value = "endTime") final Long endTime) throws PfModelException { + value = "endTime") final Long endTime) { return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId) - .body(provider.fetchDatabaseStatistics( - PdpFilterParameters.builder().group(groupName).subGroup(subType).recordNum(recordCount) - .startTime(convertEpochtoInstant(startTime)).endTime(convertEpochtoInstant(endTime)).build())); + .body(pdpStatisticsService.fetchDatabaseStatistics(groupName, subType, recordCount, + convertEpochtoInstant(startTime), convertEpochtoInstant(endTime))); } /** @@ -247,7 +240,6 @@ public class StatisticsRestControllerV1 extends PapRestControllerV1 { * @param pdpName the name of the PDP * @param recordCount the count of the query response, optional, default return all statistics stored * @return a response - * @throws PfModelException the exception */ @GetMapping("pdps/statistics/{group}/{type}/{pdp}") @ApiOperation(value = "Fetch statistics for the specified pdp", @@ -291,11 +283,10 @@ public class StatisticsRestControllerV1 extends PapRestControllerV1 { value = "startTime") final Long startTime, @ApiParam(value = "End time in epoch timestamp") @RequestParam( required = false, - value = "endTime") final Long endTime) throws PfModelException { + value = "endTime") final Long endTime) { return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId) - .body(provider.fetchDatabaseStatistics( - PdpFilterParameters.builder().group(groupName).subGroup(subType).name(pdpName).recordNum(recordCount) - .startTime(convertEpochtoInstant(startTime)).endTime(convertEpochtoInstant(endTime)).build())); + .body(pdpStatisticsService.fetchDatabaseStatistics(groupName, subType, pdpName, recordCount, + convertEpochtoInstant(startTime), convertEpochtoInstant(endTime))); } private Instant convertEpochtoInstant(Long epochSecond) { diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/StatisticsRestProvider.java b/main/src/main/java/org/onap/policy/pap/main/rest/StatisticsRestProvider.java deleted file mode 100644 index 51f10fef..00000000 --- a/main/src/main/java/org/onap/policy/pap/main/rest/StatisticsRestProvider.java +++ /dev/null @@ -1,107 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2020-2021 Nordix Foundation. - * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.pap.main.rest; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import javax.ws.rs.core.Response; -import org.onap.policy.common.utils.services.Registry; -import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.base.PfModelRuntimeException; -import org.onap.policy.models.pdp.concepts.PdpStatistics; -import org.onap.policy.models.pdp.persistence.provider.PdpFilterParameters; -import org.onap.policy.models.provider.PolicyModelsProvider; -import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; -import org.onap.policy.pap.main.startstop.PapActivator; -import org.springframework.stereotype.Service; - -/** - * Class to fetch statistics of pap component. - * - * @author Ram Krishna Verma (ram.krishna.verma@est.tech) - */ -@Service -public class StatisticsRestProvider { - private static final String GET_STATISTICS_ERR_MSG = "database query failed"; - - /** - * Returns the current statistics of pap component. - * - * @return Report containing statistics of pap component - */ - public StatisticsReport fetchCurrentStatistics() { - final var report = new StatisticsReport(); - report.setCode(Registry.get(PapConstants.REG_PAP_ACTIVATOR, PapActivator.class).isAlive() ? 200 : 500); - - PapStatisticsManager mgr = Registry.get(PapConstants.REG_STATISTICS_MANAGER, PapStatisticsManager.class); - report.setTotalPdpCount(mgr.getTotalPdpCount()); - report.setTotalPdpGroupCount(mgr.getTotalPdpGroupCount()); - report.setTotalPolicyDownloadCount(mgr.getTotalPolicyDownloadCount()); - report.setPolicyDownloadSuccessCount(mgr.getPolicyDownloadSuccessCount()); - report.setPolicyDownloadFailureCount(mgr.getPolicyDownloadFailureCount()); - report.setTotalPolicyDeployCount(mgr.getTotalPolicyDeployCount()); - report.setPolicyDeploySuccessCount(mgr.getPolicyDeploySuccessCount()); - report.setPolicyDeployFailureCount(mgr.getPolicyDeployFailureCount()); - - return report; - } - - /** - * Returns statistics of pdp component from database. - * - * @param filter record filter - * @return Report containing statistics of pdp component - * @throws PfModelException when database can not found - */ - public Map>> fetchDatabaseStatistics(PdpFilterParameters filter) - throws PfModelException { - final PolicyModelsProviderFactoryWrapper modelProviderWrapper = - Registry.get(PapConstants.REG_PAP_DAO_FACTORY, PolicyModelsProviderFactoryWrapper.class); - try (PolicyModelsProvider databaseProvider = modelProviderWrapper.create()) { - return generatePdpStatistics(databaseProvider.getFilteredPdpStatistics(filter)); - - } catch (final PfModelException exp) { - throw new PfModelRuntimeException(Response.Status.INTERNAL_SERVER_ERROR, GET_STATISTICS_ERR_MSG); - } - } - - /** - * generate the statistics of pap component by group/subgroup. - * - */ - private Map>> generatePdpStatistics(List pdpStatisticsList) { - Map>> groupMap = new HashMap<>(); - if (pdpStatisticsList != null) { - pdpStatisticsList.stream().forEach(s -> { - String curGroup = s.getPdpGroupName(); - String curSubGroup = s.getPdpSubGroupName(); - groupMap.computeIfAbsent(curGroup, curGroupMap -> new HashMap<>()) - .computeIfAbsent(curSubGroup, curSubGroupList -> new ArrayList<>()).add(s); - }); - } - return groupMap; - } -} diff --git a/main/src/main/java/org/onap/policy/pap/main/service/PdpGroupService.java b/main/src/main/java/org/onap/policy/pap/main/service/PdpGroupService.java index f3b1d6f9..5f0520ff 100644 --- a/main/src/main/java/org/onap/policy/pap/main/service/PdpGroupService.java +++ b/main/src/main/java/org/onap/policy/pap/main/service/PdpGroupService.java @@ -33,7 +33,6 @@ import org.onap.policy.models.base.PfReferenceKey; import org.onap.policy.models.pdp.concepts.Pdp; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpGroupFilter; -import org.onap.policy.models.pdp.concepts.PdpGroups; import org.onap.policy.models.pdp.concepts.PdpSubGroup; import org.onap.policy.models.pdp.enums.PdpState; import org.onap.policy.models.pdp.persistence.concepts.JpaPdp; @@ -69,7 +68,7 @@ public class PdpGroupService { * @param pdpGroup the name of group * @return the PDP groups found */ - public List getPdpGroupByName(@NonNull String pdpGroup) { + public List getPdpGroups(@NonNull String pdpGroup) { return asPdpGroups(pdpGroupRepository.findByKeyName(pdpGroup)); } @@ -79,7 +78,7 @@ public class PdpGroupService { * @param pdpState the state of pdpGroup * @return the PDP groups found */ - public List getPdpGroupByState(@NonNull PdpState pdpState) { + public List getPdpGroups(@NonNull PdpState pdpState) { return asPdpGroups(pdpGroupRepository.findByPdpGroupState(pdpState)); } @@ -90,7 +89,7 @@ public class PdpGroupService { * @param state the state of pdpGroup * @return the PDP groups found */ - public List getPdpGroupByNameAndState(@NonNull String pdpGroup, @NonNull PdpState state) { + public List getPdpGroups(@NonNull String pdpGroup, @NonNull PdpState state) { return asPdpGroups(pdpGroupRepository.findByKeyNameAndPdpGroupState(pdpGroup, state)); } @@ -110,9 +109,21 @@ public class PdpGroupService { * @param pdpGroups the PDP groups to create * @return the PDP groups created */ - public PdpGroups savePdpGroups(@NonNull final List pdpGroups) { + public List createPdpGroups(@NonNull final List pdpGroups) { + return savePdpGroups(pdpGroups); + } + + /** + * Updates PDP groups. + * + * @param pdpGroups the PDP groups to create + * @return the PDP groups created + */ + public List updatePdpGroups(@NonNull final List pdpGroups) { + return savePdpGroups(pdpGroups); + } - // Return the created PDP groups + private List savePdpGroups(final List pdpGroups) { List returnPdpGroupList = new ArrayList<>(); for (PdpGroup pdpGroup : pdpGroups) { @@ -131,9 +142,7 @@ public class PdpGroupService { "Failed saving PdpGroup. " + exc.getMessage(), exc); } } - PdpGroups returnPdpGroups = new PdpGroups(); - returnPdpGroups.setGroups(returnPdpGroupList); - return returnPdpGroups; + return returnPdpGroupList; } /** diff --git a/main/src/main/java/org/onap/policy/pap/main/service/PdpStatisticsService.java b/main/src/main/java/org/onap/policy/pap/main/service/PdpStatisticsService.java index 79112cd2..c9a831ee 100644 --- a/main/src/main/java/org/onap/policy/pap/main/service/PdpStatisticsService.java +++ b/main/src/main/java/org/onap/policy/pap/main/service/PdpStatisticsService.java @@ -26,17 +26,23 @@ import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import javax.ws.rs.core.Response; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.onap.policy.common.parameters.BeanValidationResult; +import org.onap.policy.common.utils.services.Registry; import org.onap.policy.models.base.PfGeneratedIdKey; import org.onap.policy.models.base.PfKey; import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pdp.concepts.PdpStatistics; import org.onap.policy.models.pdp.persistence.concepts.JpaPdpStatistics; +import org.onap.policy.pap.main.PapConstants; import org.onap.policy.pap.main.repository.PdpStatisticsRepository; +import org.onap.policy.pap.main.rest.PapStatisticsManager; +import org.onap.policy.pap.main.rest.StatisticsReport; +import org.onap.policy.pap.main.startstop.PapActivator; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; @@ -52,8 +58,32 @@ public class PdpStatisticsService { private static final int DEFAULT_RECORD_COUNT = 10; private static final int MAX_RECORD_COUNT = 100; + private AtomicLong generatedId = new AtomicLong(); + private final PdpStatisticsRepository pdpStatisticsRepository; + /** + * Returns the current statistics of pap component. + * + * @return Report containing statistics of pap component + */ + public StatisticsReport fetchCurrentStatistics() { + final var report = new StatisticsReport(); + report.setCode(Registry.get(PapConstants.REG_PAP_ACTIVATOR, PapActivator.class).isAlive() ? 200 : 500); + + PapStatisticsManager mgr = Registry.get(PapConstants.REG_STATISTICS_MANAGER, PapStatisticsManager.class); + report.setTotalPdpCount(mgr.getTotalPdpCount()); + report.setTotalPdpGroupCount(mgr.getTotalPdpGroupCount()); + report.setTotalPolicyDownloadCount(mgr.getTotalPolicyDownloadCount()); + report.setPolicyDownloadSuccessCount(mgr.getPolicyDownloadSuccessCount()); + report.setPolicyDownloadFailureCount(mgr.getPolicyDownloadFailureCount()); + report.setTotalPolicyDeployCount(mgr.getTotalPolicyDeployCount()); + report.setPolicyDeploySuccessCount(mgr.getPolicyDeploySuccessCount()); + report.setPolicyDeployFailureCount(mgr.getPolicyDeployFailureCount()); + + return report; + } + /** * Creates PDP statistics. * @@ -68,7 +98,9 @@ public class PdpStatisticsService { if (!validationResult.isValid()) { throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, validationResult.getResult()); } - pdpStatisticsRepository.save(jpaPdpStatistics); + //TODO: Fix this as part of POLICY-3897 + jpaPdpStatistics.getKey().setGeneratedId(generatedId.incrementAndGet()); + pdpStatisticsRepository.saveAndFlush(jpaPdpStatistics); pdpStatistics.setGeneratedId(jpaPdpStatistics.getKey().getGeneratedId()); } @@ -95,8 +127,8 @@ public class PdpStatisticsService { * @param endTime end time of the records to be returned * @return pdpStatistics grouped by pdpGroup */ - public Map>> fetchDatabaseStatistics(String pdpGroup, String pdpSubGroup, - String pdp, int recordCount, Instant startTime, Instant endTime) { + public Map>> fetchDatabaseStatistics(@NonNull String pdpGroup, + @NonNull String pdpSubGroup, @NonNull String pdp, int recordCount, Instant startTime, Instant endTime) { Pageable recordSize = getRecordSize(recordCount); if (startTime != null && endTime != null) { @@ -128,8 +160,8 @@ public class PdpStatisticsService { * @param endTime end time of the records to be returned * @return pdpStatistics grouped by pdpGroup */ - public Map>> fetchDatabaseStatistics(String pdpGroup, String pdpSubGroup, - int recordCount, Instant startTime, Instant endTime) { + public Map>> fetchDatabaseStatistics(@NonNull String pdpGroup, + @NonNull String pdpSubGroup, int recordCount, Instant startTime, Instant endTime) { Pageable recordSize = getRecordSize(recordCount); if (startTime != null && endTime != null) { @@ -159,8 +191,8 @@ public class PdpStatisticsService { * @param endTime end time of the records to be returned * @return pdpStatistics grouped by pdpGroup */ - public Map>> fetchDatabaseStatistics(String pdpGroup, int recordCount, - Instant startTime, Instant endTime) { + public Map>> fetchDatabaseStatistics(@NonNull String pdpGroup, + int recordCount, Instant startTime, Instant endTime) { Pageable recordSize = getRecordSize(recordCount); if (startTime != null && endTime != null) { diff --git a/main/src/main/java/org/onap/policy/pap/main/service/PolicyAuditService.java b/main/src/main/java/org/onap/policy/pap/main/service/PolicyAuditService.java index d2926fa1..951a3cbd 100644 --- a/main/src/main/java/org/onap/policy/pap/main/service/PolicyAuditService.java +++ b/main/src/main/java/org/onap/policy/pap/main/service/PolicyAuditService.java @@ -23,6 +23,7 @@ package org.onap.policy.pap.main.service; import java.time.Instant; import java.util.Date; import java.util.List; +import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import javax.ws.rs.core.Response; import lombok.NonNull; @@ -46,6 +47,8 @@ public class PolicyAuditService { private static final Integer DEFAULT_MAX_RECORDS = 100; private static final Integer DEFAULT_MIN_RECORDS = 10; + private AtomicLong generatedId = new AtomicLong(); + private final PolicyAuditRepository policyAuditRepository; /** @@ -61,12 +64,13 @@ public class PolicyAuditService { var count = 0; for (JpaPolicyAudit jpaAudit : jpaAudits) { result.addResult(jpaAudit.validate(String.valueOf(count++))); + // TODO: Fix this as part of POLICY-3897 + jpaAudit.getKey().setGeneratedId(generatedId.incrementAndGet()); } if (!result.isValid()) { throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, result.getResult()); } - policyAuditRepository.saveAll(jpaAudits); } @@ -103,7 +107,8 @@ public class PolicyAuditService { * @param endTime end time of the records to be returned * @return list of {@link PolicyAudit} records found */ - public List getAuditRecords(String pdpGroup, int recordCount, Instant startTime, Instant endTime) { + public List getAuditRecords(@NonNull String pdpGroup, int recordCount, Instant startTime, + Instant endTime) { Pageable recordSize = getRecordSize(recordCount); if (startTime != null && endTime != null) { return asPolicyAuditList(policyAuditRepository.findByPdpGroupAndTimeStampBetween(pdpGroup, @@ -130,8 +135,8 @@ public class PolicyAuditService { * @param endTime end time of the records to be returned * @return list of {@link PolicyAudit} records found */ - public List getAuditRecords(String pdpGroup, String policyName, String policyVersion, int recordCount, - Instant startTime, Instant endTime) { + public List getAuditRecords(@NonNull String pdpGroup, @NonNull String policyName, + @NonNull String policyVersion, int recordCount, Instant startTime, Instant endTime) { Pageable recordSize = getRecordSize(recordCount); if (startTime != null && endTime != null) { return asPolicyAuditList(policyAuditRepository.findByPdpGroupAndKeyNameAndKeyVersionAndTimeStampBetween( @@ -160,7 +165,7 @@ public class PolicyAuditService { * @param endTime end time of the records to be returned * @return list of {@link PolicyAudit} records found */ - public List getAuditRecords(String policyName, String policyVersion, int recordCount, + public List getAuditRecords(@NonNull String policyName, @NonNull String policyVersion, int recordCount, Instant startTime, Instant endTime) { Pageable recordSize = getRecordSize(recordCount); if (startTime != null && endTime != null) { diff --git a/main/src/main/java/org/onap/policy/pap/main/service/ToscaServiceTemplateService.java b/main/src/main/java/org/onap/policy/pap/main/service/ToscaServiceTemplateService.java index cebee1b5..e71045f6 100644 --- a/main/src/main/java/org/onap/policy/pap/main/service/ToscaServiceTemplateService.java +++ b/main/src/main/java/org/onap/policy/pap/main/service/ToscaServiceTemplateService.java @@ -34,6 +34,7 @@ import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.tosca.authorative.concepts.ToscaEntity; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType; +import org.onap.policy.models.tosca.authorative.concepts.ToscaTypedEntityFilter; import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate; import org.onap.policy.models.tosca.simple.provider.SimpleToscaProvider; import org.onap.policy.models.tosca.utils.ToscaUtils; @@ -81,6 +82,18 @@ public class ToscaServiceTemplateService { return policyList; } + /** + * Get filtered policies. + * + * @param filter the filter for the policies to get + * @return the policies found + * @throws PfModelException on errors getting policies + */ + public List getFilteredPolicyList(ToscaTypedEntityFilter filter) throws PfModelException { + String version = ToscaTypedEntityFilter.LATEST_VERSION.equals(filter.getVersion()) ? null : filter.getVersion(); + return filter.filter(getPolicyList(filter.getName(), version)); + } + /** * Get policy types. * @@ -172,4 +185,5 @@ public class ToscaServiceTemplateService { throw pfme; } } + } diff --git a/main/src/main/java/org/onap/policy/pap/main/startstop/PapActivator.java b/main/src/main/java/org/onap/policy/pap/main/startstop/PapActivator.java index 94943706..00207220 100644 --- a/main/src/main/java/org/onap/policy/pap/main/startstop/PapActivator.java +++ b/main/src/main/java/org/onap/policy/pap/main/startstop/PapActivator.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. * Modifications Copyright (C) 2019-2021 AT&T Intellectual Property. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,7 +40,6 @@ import org.onap.policy.models.pdp.concepts.PdpMessage; import org.onap.policy.models.pdp.concepts.PdpStatus; import org.onap.policy.models.pdp.enums.PdpMessageType; import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; import org.onap.policy.pap.main.PolicyPapRuntimeException; import org.onap.policy.pap.main.comm.PdpHeartbeatListener; import org.onap.policy.pap.main.comm.PdpModifyRequestMap; @@ -50,7 +49,6 @@ import org.onap.policy.pap.main.notification.PolicyNotifier; import org.onap.policy.pap.main.parameters.PapParameterGroup; import org.onap.policy.pap.main.parameters.PdpModifyRequestMapParams; import org.onap.policy.pap.main.rest.PapStatisticsManager; -import org.onap.policy.pap.main.rest.PolicyUndeployerImpl; import org.springframework.context.event.ContextClosedEvent; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.EventListener; @@ -88,17 +86,13 @@ public class PapActivator extends ServiceManagerContainer { private final RequestIdDispatcher responseReqIdDispatcher; private final RequestIdDispatcher heartbeatReqIdDispatcher; - /** - * Listener for anonymous {@link PdpStatus} messages either for registration or heartbeat. - */ - private final PdpHeartbeatListener pdpHeartbeatListener; - /** * Instantiate the activator for policy pap as a complete service. * * @param papParameterGroup the parameters for the pap service */ - public PapActivator(PapParameterGroup papParameterGroup) { + public PapActivator(PapParameterGroup papParameterGroup, PolicyNotifier policyNotifier, + PdpHeartbeatListener pdpHeartbeatListener, PdpModifyRequestMap pdpModifyRequestMap) { super("Policy PAP"); this.papParameterGroup = papParameterGroup; TopicEndpointManager.getManager().addTopics(papParameterGroup.getTopicParameterGroup()); @@ -108,8 +102,6 @@ public class PapActivator extends ServiceManagerContainer { this.heartbeatMsgDispatcher = new MessageTypeDispatcher(MSG_TYPE_NAMES); this.responseReqIdDispatcher = new RequestIdDispatcher<>(PdpStatus.class, REQ_ID_NAMES); this.heartbeatReqIdDispatcher = new RequestIdDispatcher<>(PdpStatus.class, REQ_ID_NAMES); - this.pdpHeartbeatListener = new PdpHeartbeatListener(papParameterGroup.getPdpParameters(), - papParameterGroup.isSavePdpStatisticsInDb()); } catch (final RuntimeException e) { throw new PolicyPapRuntimeException(e); @@ -123,24 +115,13 @@ public class PapActivator extends ServiceManagerContainer { final AtomicReference pdpUpdTimers = new AtomicReference<>(); final AtomicReference pdpStChgTimers = new AtomicReference<>(); final AtomicReference pdpExpirationTimer = new AtomicReference<>(); - final AtomicReference daoFactory = new AtomicReference<>(); final AtomicReference requestMap = new AtomicReference<>(); - final AtomicReference notifier = new AtomicReference<>(); // @formatter:off addAction("PAP parameters", () -> ParameterService.register(papParameterGroup), () -> ParameterService.deregister(papParameterGroup.getName())); - addAction("DAO Factory", - () -> daoFactory.set(new PolicyModelsProviderFactoryWrapper( - papParameterGroup.getDatabaseProviderParameters())), - () -> daoFactory.get().close()); - - addAction("DAO Factory registration", - () -> Registry.register(PapConstants.REG_PAP_DAO_FACTORY, daoFactory.get()), - () -> Registry.unregister(PapConstants.REG_PAP_DAO_FACTORY)); - addAction("Pdp Heartbeat Listener", () -> heartbeatReqIdDispatcher.register(pdpHeartbeatListener), () -> heartbeatReqIdDispatcher.unregister(pdpHeartbeatListener)); @@ -184,14 +165,10 @@ public class PapActivator extends ServiceManagerContainer { () -> { notifyPub.set(new Publisher<>(PapConstants.TOPIC_POLICY_NOTIFICATION)); startThread(notifyPub.get()); - notifier.set(new PolicyNotifier(notifyPub.get(), daoFactory.get())); + policyNotifier.setPublisher(notifyPub.get()); }, () -> notifyPub.get().stop()); - addAction("Policy Notifier", - () -> Registry.register(PapConstants.REG_POLICY_NOTIFIER, notifier.get()), - () -> Registry.unregister(PapConstants.REG_POLICY_NOTIFIER)); - addAction("PDP update timers", () -> { pdpUpdTimers.set(new TimerManager("update", pdpParams.getUpdateParameters().getMaxWaitMs())); @@ -212,23 +189,19 @@ public class PapActivator extends ServiceManagerContainer { addAction("PDP modification requests", () -> { - requestMap.set(new PdpModifyRequestMap( - PdpModifyRequestMapParams.builder() - .maxPdpAgeMs(MAX_MISSED_HEARTBEATS * pdpParams.getHeartBeatMs()) - .daoFactory(daoFactory.get()) - .modifyLock(pdpUpdateLock) - .params(pdpParams) - .policyNotifier(notifier.get()) - .pdpPublisher(pdpPub.get()) - .responseDispatcher(responseReqIdDispatcher) - .stateChangeTimers(pdpStChgTimers.get()) - .updateTimers(pdpUpdTimers.get()) - .savePdpStatistics(papParameterGroup.isSavePdpStatisticsInDb()) - .build())); + pdpModifyRequestMap.initialize( + PdpModifyRequestMapParams.builder() + .maxPdpAgeMs(MAX_MISSED_HEARTBEATS * pdpParams.getHeartBeatMs()) + .modifyLock(pdpUpdateLock) + .params(pdpParams) + .pdpPublisher(pdpPub.get()) + .responseDispatcher(responseReqIdDispatcher) + .stateChangeTimers(pdpStChgTimers.get()) + .updateTimers(pdpUpdTimers.get()) + .savePdpStatistics(papParameterGroup.isSavePdpStatisticsInDb()) + .build()); + requestMap.set(pdpModifyRequestMap); Registry.register(PapConstants.REG_PDP_MODIFY_MAP, requestMap.get()); - - // now that it's registered, we can attach a "policy undeploy" provider - requestMap.get().setPolicyUndeployer(new PolicyUndeployerImpl()); }, () -> Registry.unregister(PapConstants.REG_PDP_MODIFY_MAP)); diff --git a/main/src/main/java/org/onap/policy/pap/main/startstop/PapDatabaseInitializer.java b/main/src/main/java/org/onap/policy/pap/main/startstop/PapDatabaseInitializer.java index 617cdf36..b2a42d9c 100644 --- a/main/src/main/java/org/onap/policy/pap/main/startstop/PapDatabaseInitializer.java +++ b/main/src/main/java/org/onap/policy/pap/main/startstop/PapDatabaseInitializer.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,13 +28,10 @@ import org.onap.policy.common.parameters.ValidationResult; import org.onap.policy.common.utils.coder.CoderException; import org.onap.policy.common.utils.coder.StandardCoder; import org.onap.policy.common.utils.resources.ResourceUtils; -import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpGroups; -import org.onap.policy.models.provider.PolicyModelsProviderFactory; -import org.onap.policy.models.provider.PolicyModelsProviderParameters; import org.onap.policy.pap.main.PolicyPapException; -import org.onap.policy.pap.main.parameters.PapParameterGroup; +import org.onap.policy.pap.main.service.PdpGroupService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -54,10 +51,9 @@ public class PapDatabaseInitializer { private static final Logger LOGGER = LoggerFactory.getLogger(PapDatabaseInitializer.class); private final StandardCoder standardCoder; - private final PolicyModelsProviderFactory factory; @Autowired - private PapParameterGroup papParameterGroup; + private PdpGroupService pdpGroupService; @Value("${group-config-file:PapDb.json}") private String groupConfigFile; @@ -66,39 +62,34 @@ public class PapDatabaseInitializer { * Constructs the object. */ public PapDatabaseInitializer() { - factory = new PolicyModelsProviderFactory(); standardCoder = new StandardCoder(); } /** * Initializes database with group information. * - * @param policyModelsProviderParameters the database parameters * @param groupsJson the group file path * @throws PolicyPapException in case of errors. */ - private void initializePapDatabase( - final PolicyModelsProviderParameters policyModelsProviderParameters, - String groupsJson) throws PolicyPapException { + private void initializePapDatabase(String groupsJson) throws PolicyPapException { - try (var databaseProvider = - factory.createPolicyModelsProvider(policyModelsProviderParameters)) { + try { final var originalJson = ResourceUtils.getResourceAsString(groupsJson); final var pdpGroupsToCreate = standardCoder.decode(originalJson, PdpGroups.class); - final List pdpGroupsFromDb = databaseProvider.getPdpGroups( - pdpGroupsToCreate.getGroups().get(0).getName()); + final List pdpGroupsFromDb = + pdpGroupService.getPdpGroups(pdpGroupsToCreate.getGroups().get(0).getName()); if (pdpGroupsFromDb.isEmpty()) { ValidationResult result = pdpGroupsToCreate.validatePapRest(); if (!result.isValid()) { throw new PolicyPapException(result.getResult()); } - databaseProvider.createPdpGroups(pdpGroupsToCreate.getGroups()); + pdpGroupService.createPdpGroups(pdpGroupsToCreate.getGroups()); LOGGER.info("Created initial pdpGroup in DB - {} from {}", pdpGroupsToCreate, groupsJson); } else { - LOGGER.info("Initial pdpGroup already exists in DB, skipping create - {} from {}", - pdpGroupsFromDb, groupsJson); + LOGGER.info("Initial pdpGroup already exists in DB, skipping create - {} from {}", pdpGroupsFromDb, + groupsJson); } - } catch (final PfModelException | CoderException | RuntimeException exp) { + } catch (final CoderException | RuntimeException exp) { throw new PolicyPapException(exp); } } @@ -108,6 +99,6 @@ public class PapDatabaseInitializer { */ @PostConstruct public void loadData() throws PolicyPapException { - initializePapDatabase(papParameterGroup.getDatabaseProviderParameters(), groupConfigFile); + initializePapDatabase(groupConfigFile); } } diff --git a/main/src/main/resources/META-INF/persistence.xml b/main/src/main/resources/META-INF/persistence.xml deleted file mode 100644 index a9d61294..00000000 --- a/main/src/main/resources/META-INF/persistence.xml +++ /dev/null @@ -1,67 +0,0 @@ - - - - - - org.eclipse.persistence.jpa.PersistenceProvider - - org.onap.policy.models.base.PfConceptKey - org.onap.policy.models.dao.converters.CDataConditioner - org.onap.policy.models.dao.converters.Uuid2String - org.onap.policy.models.pdp.persistence.concepts.JpaPdp - org.onap.policy.models.pdp.persistence.concepts.JpaPdpGroup - org.onap.policy.models.pdp.persistence.concepts.JpaPdpPolicyStatus - org.onap.policy.models.pdp.persistence.concepts.JpaPdpStatistics - org.onap.policy.models.pdp.persistence.concepts.JpaPdpSubGroup - org.onap.policy.models.pap.persistence.concepts.JpaPolicyAudit - org.onap.policy.models.tosca.simple.concepts.JpaToscaCapabilityAssignment - org.onap.policy.models.tosca.simple.concepts.JpaToscaCapabilityAssignments - org.onap.policy.models.tosca.simple.concepts.JpaToscaCapabilityType - org.onap.policy.models.tosca.simple.concepts.JpaToscaCapabilityTypes - org.onap.policy.models.tosca.simple.concepts.JpaToscaDataType - org.onap.policy.models.tosca.simple.concepts.JpaToscaDataTypes - org.onap.policy.models.tosca.simple.concepts.JpaToscaNodeTemplate - org.onap.policy.models.tosca.simple.concepts.JpaToscaNodeTemplates - org.onap.policy.models.tosca.simple.concepts.JpaToscaNodeType - org.onap.policy.models.tosca.simple.concepts.JpaToscaNodeTypes - org.onap.policy.models.tosca.simple.concepts.JpaToscaParameter - org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicies - org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicy - org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicyType - org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicyTypes - org.onap.policy.models.tosca.simple.concepts.JpaToscaProperty - org.onap.policy.models.tosca.simple.concepts.JpaToscaRelationshipType - org.onap.policy.models.tosca.simple.concepts.JpaToscaRelationshipTypes - org.onap.policy.models.tosca.simple.concepts.JpaToscaRequirement - org.onap.policy.models.tosca.simple.concepts.JpaToscaRequirements - org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate - org.onap.policy.models.tosca.simple.concepts.JpaToscaTopologyTemplate - org.onap.policy.models.tosca.simple.concepts.JpaToscaTrigger - - - - - - - - diff --git a/main/src/main/resources/application.yaml b/main/src/main/resources/application.yaml index 3d6cf0e7..d6111aa1 100644 --- a/main/src/main/resources/application.yaml +++ b/main/src/main/resources/application.yaml @@ -14,7 +14,7 @@ spring: jpa: properties: hibernate: - dialect: org.hibernate.dialect.MySQL5InnoDBDialect + dialect: org.hibernate.dialect.MariaDB103Dialect hibernate: ddl-auto: none naming: @@ -34,14 +34,6 @@ pap: stateChangeParameters: maxRetryCount: 1 maxWaitMs: 30000 - databaseProviderParameters: - name: PolicyProviderParameterGroup - implementation: org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl - databaseDriver: org.mariadb.jdbc.Driver - databaseUrl: jdbc:mariadb://mariadb:3306/policyadmin - databaseUser: policy_user - databasePassword: policy_user - persistenceUnit: PolicyDb savePdpStatisticsInDb: true topicParameterGroup: topicSources: diff --git a/main/src/test/java/org/onap/policy/pap/main/comm/CommonRequestBase.java b/main/src/test/java/org/onap/policy/pap/main/comm/CommonRequestBase.java index 0dc6636b..dd206062 100644 --- a/main/src/test/java/org/onap/policy/pap/main/comm/CommonRequestBase.java +++ b/main/src/test/java/org/onap/policy/pap/main/comm/CommonRequestBase.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,10 +44,8 @@ import org.onap.policy.models.pdp.concepts.PdpStateChange; import org.onap.policy.models.pdp.concepts.PdpStatus; import org.onap.policy.models.pdp.concepts.PdpUpdate; import org.onap.policy.models.pdp.enums.PdpState; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; import org.onap.policy.pap.main.comm.msgdata.RequestListener; import org.onap.policy.pap.main.comm.msgdata.StateChangeReq; import org.onap.policy.pap.main.comm.msgdata.UpdateReq; @@ -84,8 +83,6 @@ public class CommonRequestBase { protected TimerManager.Timer timer; protected Queue> queue; protected RequestListener listener; - protected PolicyModelsProviderFactoryWrapper daoFactory; - protected PolicyModelsProvider dao; protected RequestParams reqParams; protected PdpModifyRequestMapParams mapParams; @@ -105,9 +102,6 @@ public class CommonRequestBase { timer = mock(TimerManager.Timer.class); queue = new LinkedList<>(); listener = mock(RequestListener.class); - daoFactory = mock(PolicyModelsProviderFactoryWrapper.class); - dao = mock(PolicyModelsProvider.class); - PdpParameters pdpParams = mock(PdpParameters.class); doAnswer(new Answer() { @@ -120,8 +114,6 @@ public class CommonRequestBase { when(timers.register(any(), any())).thenReturn(timer); - when(daoFactory.create()).thenReturn(dao); - PdpStateChangeParameters stateParams = mock(PdpStateChangeParameters.class); when(stateParams.getMaxRetryCount()).thenReturn(RETRIES); when(pdpParams.getStateChangeParameters()).thenReturn(stateParams); @@ -134,7 +126,7 @@ public class CommonRequestBase { .setResponseDispatcher(dispatcher).setTimers(timers); mapParams = PdpModifyRequestMapParams.builder().modifyLock(lock).pdpPublisher(publisher) - .policyNotifier(notifier).responseDispatcher(dispatcher).daoFactory(daoFactory) + .responseDispatcher(dispatcher) .updateTimers(timers).stateChangeTimers(timers).params(pdpParams) .maxPdpAgeMs(100).build(); } diff --git a/main/src/test/java/org/onap/policy/pap/main/comm/PdpHeartbeatListenerTest.java b/main/src/test/java/org/onap/policy/pap/main/comm/PdpHeartbeatListenerTest.java index 7ae4b370..34c20410 100644 --- a/main/src/test/java/org/onap/policy/pap/main/comm/PdpHeartbeatListenerTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/comm/PdpHeartbeatListenerTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019-2021 Nordix Foundation. * Modifications Copyright (C) 2020-2021 AT&T Intellectual Property. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,6 +31,7 @@ import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Map; import java.util.stream.Collectors; import org.junit.Test; import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; @@ -46,8 +47,10 @@ import org.onap.policy.models.pdp.enums.PdpState; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.onap.policy.pap.main.parameters.CommonTestData; +import org.onap.policy.pap.main.parameters.PapParameterGroup; import org.onap.policy.pap.main.parameters.PdpParameters; import org.onap.policy.pap.main.rest.e2e.End2EndBase; +import org.springframework.beans.factory.annotation.Autowired; /** * Class to perform unit test of {@link PdpHeartbeatListener}. @@ -65,12 +68,16 @@ public class PdpHeartbeatListenerTest extends End2EndBase { private static final String TOPIC = "my-topic"; private Instant timeStamp; + + @Autowired private PdpHeartbeatListener pdpHeartbeatListener; @Test public void testPdpHeartbeatListener() throws CoderException, PfModelException { addGroups("PdpGroups.json"); - pdpHeartbeatListener = new PdpHeartbeatListener(new PdpParameters(), true); + PapParameterGroup parameterGroup = new PapParameterGroup(); + parameterGroup.setPdpParameters(new PdpParameters()); + parameterGroup.setSavePdpStatisticsInDb(true); // Testing pdp registration success case final PdpStatus status1 = new PdpStatus(); @@ -219,14 +226,14 @@ public class PdpHeartbeatListenerTest extends End2EndBase { List policies = new ArrayList<>(); policies.add(polA); policies.add(polB); - final CommonTestData testData = new CommonTestData(); - PdpParameters params = testData.getPapParameterGroup(1).getPdpParameters(); - List polsUndep = policies.stream().map(ToscaPolicy::getIdentifier) - .collect(Collectors.toList()); - PdpStatusMessageHandler handler = new PdpStatusMessageHandler(params, true); - PdpUpdate update10 = handler.createPdpUpdateMessage( - status3.getPdpGroup(), new PdpSubGroup(), "pdp_2", - policies, polsUndep); + final PapParameterGroup testGroup = new CommonTestData().getPapParameterGroup(1); + testGroup.setSavePdpStatisticsInDb(true); + List polsUndep = + policies.stream().map(ToscaPolicy::getIdentifier).collect(Collectors.toList()); + PdpStatusMessageHandler handler = new PdpStatusMessageHandler(testGroup, pdpGroupService, + pdpStatisticsService); + PdpUpdate update10 = + handler.createPdpUpdateMessage(status3.getPdpGroup(), new PdpSubGroup(), "pdp_2", policies, polsUndep); assertSame(update10.getPoliciesToBeDeployed(), policies); assertSame(update10.getPoliciesToBeUndeployed(), polsUndep); assertThat(update10.getPoliciesToBeDeployed()).isInstanceOf(List.class); @@ -235,7 +242,9 @@ public class PdpHeartbeatListenerTest extends End2EndBase { @Test public void testPdpStatistics() throws CoderException, PfModelException, ParseException { addGroups("PdpGroups.json"); - pdpHeartbeatListener = new PdpHeartbeatListener(new PdpParameters(), true); + PapParameterGroup parameterGroup = new PapParameterGroup(); + parameterGroup.setPdpParameters(new PdpParameters()); + parameterGroup.setSavePdpStatisticsInDb(true); timeStamp = Instant.parse("2021-02-12T17:48:01.029211400Z"); // init default pdp group @@ -283,7 +292,7 @@ public class PdpHeartbeatListenerTest extends End2EndBase { pdpStatistics03.setTimeStamp(timeStamp); status3.setStatistics(pdpStatistics03); pdpHeartbeatListener.onTopicEvent(INFRA, TOPIC, status3); - verifyPdpStatistics(PDP_NAME, DEFAULT_GROUP, null, 1); + verifyPdpStatistics(PDP_NAME, DEFAULT_GROUP, APEX_TYPE, 1); // Testing pdp statistics failure having the pdpStatistics null in the heartbeat for already registered pdp final PdpStatus status4 = new PdpStatus(); @@ -298,7 +307,7 @@ public class PdpHeartbeatListenerTest extends End2EndBase { status4.setPolicies(idents4); status4.setStatistics(null); pdpHeartbeatListener.onTopicEvent(INFRA, TOPIC, status4); - verifyPdpStatistics(PDP_NAME, DEFAULT_GROUP, null, 1); + verifyPdpStatistics(PDP_NAME, DEFAULT_GROUP, APEX_TYPE, 1); // Testing pdp statistics failure passing different pdpGroup, PdpSubGroup & pdpInstanceId final PdpStatus status5 = new PdpStatus(); @@ -320,7 +329,7 @@ public class PdpHeartbeatListenerTest extends End2EndBase { status5.setStatistics(pdpStatistics05); pdpHeartbeatListener.onTopicEvent(INFRA, TOPIC, status5); - verifyPdpStatistics(null, DEFAULT_GROUP, null, 1); + verifyPdpStatistics(PDP_NAME, DEFAULT_GROUP, APEX_TYPE, 1); // Test pdp statistics failure passing negative values final PdpStatus status6 = new PdpStatus(); @@ -347,10 +356,12 @@ public class PdpHeartbeatListenerTest extends End2EndBase { status5.setStatistics(pdpStatistics06); pdpHeartbeatListener.onTopicEvent(INFRA, TOPIC, status5); - verifyPdpStatistics(null, DEFAULT_GROUP, null, 1); + verifyPdpStatistics(PDP_NAME, DEFAULT_GROUP, APEX_TYPE, 1); // Test pdp statistics save disabled case, sending valid pdp status but count should still remain 1 - pdpHeartbeatListener = new PdpHeartbeatListener(new PdpParameters(), false); + parameterGroup = new PapParameterGroup(); + parameterGroup.setPdpParameters(new PdpParameters()); + parameterGroup.setSavePdpStatisticsInDb(false); timeStamp = Instant.parse("2021-02-12T17:48:05.029211400Z"); final PdpStatus status7 = new PdpStatus(); status7.setName(PDP_NAME); @@ -370,7 +381,7 @@ public class PdpHeartbeatListenerTest extends End2EndBase { pdpStatistics07.setTimeStamp(timeStamp); status7.setStatistics(pdpStatistics07); pdpHeartbeatListener.onTopicEvent(INFRA, TOPIC, status7); - verifyPdpStatistics(PDP_NAME, DEFAULT_GROUP, null, 1); + verifyPdpStatistics(PDP_NAME, DEFAULT_GROUP, APEX_TYPE, 1); } @@ -389,7 +400,7 @@ public class PdpHeartbeatListenerTest extends End2EndBase { private void verifyPdpStatistics(final String pdpInstanceId, final String pdpGroupName, final String pdpSubGroupName, final int count) throws PfModelException { - final List fetchedPdpStatistics = + final Map>> fetchedPdpStatistics = fetchPdpStatistics(pdpInstanceId, pdpGroupName, pdpSubGroupName); assertEquals(count, fetchedPdpStatistics.size()); } diff --git a/main/src/test/java/org/onap/policy/pap/main/comm/PdpModifyRequestMapTest.java b/main/src/test/java/org/onap/policy/pap/main/comm/PdpModifyRequestMapTest.java index e626d28d..6ff989cd 100644 --- a/main/src/test/java/org/onap/policy/pap/main/comm/PdpModifyRequestMapTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/comm/PdpModifyRequestMapTest.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2020-2021 Nordix Foundation. + * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,6 +71,8 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.onap.policy.pap.main.comm.msgdata.Request; import org.onap.policy.pap.main.comm.msgdata.RequestListener; import org.onap.policy.pap.main.parameters.PdpModifyRequestMapParams; +import org.onap.policy.pap.main.service.PdpGroupService; +import org.onap.policy.pap.main.service.PolicyStatusService; import org.powermock.reflect.Whitebox; @RunWith(MockitoJUnitRunner.class) @@ -105,6 +108,12 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { @Mock private PdpStatusMessageHandler responseHandler; + @Mock + private PdpGroupService pdpGroupService; + + @Mock + private PolicyStatusService policyStatusService; + private MyMap map; private PdpUpdate update; private PdpStateChange change; @@ -135,14 +144,12 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { response.setPolicies(Collections.emptyList()); map = new MyMap(mapParams); - map.setPolicyUndeployer(undeployer); } @Test public void testPdpModifyRequestMap() { assertSame(mapParams, Whitebox.getInternalState(map, "params")); assertSame(lock, Whitebox.getInternalState(map, "modifyLock")); - assertSame(daoFactory, Whitebox.getInternalState(map, "daoFactory")); } @Test @@ -379,7 +386,7 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { Instant expired = Instant.now().minusSeconds(EXPIRED_SECONDS); group2.getPdpSubgroups().get(0).getPdpInstances().forEach(pdp -> pdp.setLastUpdate(expired)); - when(dao.getFilteredPdpGroups(any())).thenReturn(List.of(group1, group2)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(List.of(group1, group2)); // run it map.removeExpiredPdps(); @@ -407,25 +414,25 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { PdpGroup group1 = makeGroup(MY_GROUP); group1.setPdpSubgroups(List.of(makeSubGroup(MY_SUBGROUP, PDP1))); - when(dao.getFilteredPdpGroups(any())).thenReturn(List.of(group1)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(List.of(group1)); // run it map.removeExpiredPdps(); - verify(dao, never()).updatePdpGroups(any()); + verify(pdpGroupService, never()).updatePdpGroups(any()); verify(publisher, never()).enqueue(any()); } @Test public void testRemoveExpiredPdps_DaoEx() throws Exception { - when(dao.getFilteredPdpGroups(any())).thenThrow(makeException()); + when(pdpGroupService.getFilteredPdpGroups(any())).thenThrow(makeRuntimeException()); assertThatCode(map::removeExpiredPdps).doesNotThrowAnyException(); } @Test public void testRemoveExpiredPdps_DaoRtEx() throws Exception { - when(dao.getFilteredPdpGroups(any())).thenThrow(makeRuntimeException()); + when(pdpGroupService.getFilteredPdpGroups(any())).thenThrow(makeRuntimeException()); assertThatCode(map::removeExpiredPdps).doesNotThrowAnyException(); } @@ -440,8 +447,7 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { List pdps = group.getPdpSubgroups().get(0).getPdpInstances(); pdps.get(0).setLastUpdate(expired); pdps.get(2).setLastUpdate(expired); - - when(dao.getFilteredPdpGroups(any())).thenReturn(List.of(group)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(List.of(group)); // run it map.removeExpiredPdps(); @@ -469,7 +475,10 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { @Test public void testMakePdpRequests() { // this should invoke the real method without throwing an exception - new PdpModifyRequestMap(mapParams).addRequest(change); + PdpModifyRequestMap reqMap = + new PdpModifyRequestMap(pdpGroupService, policyStatusService, responseHandler, undeployer, notifier); + reqMap.initialize(mapParams); + reqMap.addRequest(change); QueueToken token = queue.poll(); assertNotNull(token); @@ -621,7 +630,7 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { assertEquals(1, map.nalloc); // no updates - verify(dao, never()).updatePdpGroups(any()); + verify(pdpGroupService, never()).updatePdpGroups(any()); } @Test @@ -753,7 +762,7 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { * @throws Exception if an error occurred */ private List getGroupUpdates() throws Exception { - verify(dao).updatePdpGroups(updateCaptor.capture()); + verify(pdpGroupService).updatePdpGroups(updateCaptor.capture()); return copyList(updateCaptor.getValue()); } @@ -777,7 +786,8 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { private int nalloc = 0; public MyMap(PdpModifyRequestMapParams params) { - super(params); + super(pdpGroupService, policyStatusService, responseHandler, undeployer, notifier); + super.initialize(params);; } @Override @@ -785,10 +795,5 @@ public class PdpModifyRequestMapTest extends CommonRequestBase { ++nalloc; return requests; } - - @Override - protected PdpStatusMessageHandler makePdpResponseHandler() { - return responseHandler; - } } } diff --git a/main/src/test/java/org/onap/policy/pap/main/notification/DeploymentStatusTest.java b/main/src/test/java/org/onap/policy/pap/main/notification/DeploymentStatusTest.java index 8d7a8c15..3b7f7e16 100644 --- a/main/src/test/java/org/onap/policy/pap/main/notification/DeploymentStatusTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/notification/DeploymentStatusTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,9 +46,9 @@ import org.onap.policy.models.pap.concepts.PolicyStatus; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus.PdpPolicyStatusBuilder; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus.State; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; import org.onap.policy.pap.main.notification.StatusAction.Action; +import org.onap.policy.pap.main.service.PolicyStatusService; @RunWith(MockitoJUnitRunner.class) public class DeploymentStatusTest { @@ -75,7 +76,7 @@ public class DeploymentStatusTest { private ArgumentCaptor> deleted; @Mock - private PolicyModelsProvider provider; + private PolicyStatusService policyStatusService; private DeploymentStatus tracker; @@ -84,7 +85,7 @@ public class DeploymentStatusTest { */ @Before public void setUp() { - tracker = new DeploymentStatus(provider); + tracker = new DeploymentStatus(policyStatusService); // @formatter:off builder = PdpPolicyStatus.builder() @@ -142,7 +143,7 @@ public class DeploymentStatusTest { PdpPolicyStatus status2 = builder.policy(POLICY_B).build(); PdpPolicyStatus status3 = builder.policy(POLICY_A).pdpId(PDP_B).build(); - when(provider.getGroupPolicyStatus(GROUP_A)).thenReturn(List.of(status1, status2, status3)); + when(policyStatusService.getGroupPolicyStatus(GROUP_A)).thenReturn(List.of(status1, status2, status3)); tracker.loadByGroup(GROUP_A); @@ -156,7 +157,7 @@ public class DeploymentStatusTest { // try again - should not reload tracker.loadByGroup(GROUP_A); - verify(provider).getGroupPolicyStatus(anyString()); + verify(policyStatusService).getGroupPolicyStatus(anyString()); } @Test @@ -198,7 +199,7 @@ public class DeploymentStatusTest { tracker.flush(); - verify(provider).cudPolicyStatus(created.capture(), updated.capture(), deleted.capture()); + verify(policyStatusService).cudPolicyStatus(created.capture(), updated.capture(), deleted.capture()); assertThat(sort(created.getValue())).isEqualTo(List.of(create1, create2)); assertThat(sort(updated.getValue())).isEqualTo(List.of(update1, update2)); diff --git a/main/src/test/java/org/onap/policy/pap/main/notification/PolicyNotifierTest.java b/main/src/test/java/org/onap/policy/pap/main/notification/PolicyNotifierTest.java index 9134985c..5fec269a 100644 --- a/main/src/test/java/org/onap/policy/pap/main/notification/PolicyNotifierTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/notification/PolicyNotifierTest.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,14 +42,14 @@ import org.mockito.Captor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pap.concepts.PolicyNotification; import org.onap.policy.models.pap.concepts.PolicyStatus; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; import org.onap.policy.pap.main.PolicyPapRuntimeException; import org.onap.policy.pap.main.comm.Publisher; import org.onap.policy.pap.main.comm.QueueToken; +import org.onap.policy.pap.main.service.PolicyStatusService; @RunWith(MockitoJUnitRunner.class) public class PolicyNotifierTest { @@ -61,10 +62,7 @@ public class PolicyNotifierTest { private Publisher publisher; @Mock - private PolicyModelsProviderFactoryWrapper daoFactory; - - @Mock - private PolicyModelsProvider dao; + private PolicyStatusService policyStatusService; @Mock private DeploymentStatus tracker; @@ -92,8 +90,7 @@ public class PolicyNotifierTest { @Before public void setUp() { try { - when(daoFactory.create()).thenReturn(dao); - when(dao.getGroupPolicyStatus(anyString())).thenReturn(Collections.emptyList()); + when(policyStatusService.getGroupPolicyStatus(anyString())).thenReturn(Collections.emptyList()); notifier = new MyNotifier(publisher); @@ -125,7 +122,8 @@ public class PolicyNotifierTest { @Test public void testProcessResponseString_Ex() throws PfModelException { - doThrow(new PfModelException(Status.BAD_REQUEST, "expected exception")).when(tracker).loadByGroup(anyString()); + doThrow(new PfModelRuntimeException(Status.BAD_REQUEST, "expected exception")).when(tracker) + .loadByGroup(anyString()); assertThatCode(() -> notifier.processResponse(PDP1, GROUP_A, Set.of(), Set.of())).doesNotThrowAnyException(); } @@ -155,20 +153,23 @@ public class PolicyNotifierTest { @Test public void testMakeDeploymentTracker() throws PfModelException { // make real object, which will invoke the real makeXxx() methods - new PolicyNotifier(publisher, daoFactory).processResponse(PDP1, GROUP_A, Set.of(), Set.of()); + PolicyNotifier policyNotifier = new PolicyNotifier(policyStatusService); + policyNotifier.setPublisher(publisher); + policyNotifier.processResponse(PDP1, GROUP_A, Set.of(), Set.of()); - verify(dao).getGroupPolicyStatus(GROUP_A); + verify(policyStatusService).getGroupPolicyStatus(GROUP_A); } private class MyNotifier extends PolicyNotifier { public MyNotifier(Publisher publisher) throws PfModelException { - super(publisher, daoFactory); + super(policyStatusService); + super.setPublisher(publisher); } @Override - protected DeploymentStatus makeDeploymentTracker(PolicyModelsProvider dao) { + protected DeploymentStatus makeDeploymentTracker() { return tracker; } } diff --git a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpModifyRequestMapParams.java b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpModifyRequestMapParams.java index b77c5544..c41915d2 100644 --- a/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpModifyRequestMapParams.java +++ b/main/src/test/java/org/onap/policy/pap/main/parameters/TestPdpModifyRequestMapParams.java @@ -3,6 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,10 +32,8 @@ import org.junit.Test; import org.onap.policy.common.endpoints.listeners.RequestIdDispatcher; import org.onap.policy.models.pdp.concepts.PdpMessage; import org.onap.policy.models.pdp.concepts.PdpStatus; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; import org.onap.policy.pap.main.comm.Publisher; import org.onap.policy.pap.main.comm.TimerManager; -import org.onap.policy.pap.main.notification.PolicyNotifier; import org.onap.policy.pap.main.parameters.PdpModifyRequestMapParams.PdpModifyRequestMapParamsBuilder; public class TestPdpModifyRequestMapParams { @@ -46,8 +45,6 @@ public class TestPdpModifyRequestMapParams { private PdpParameters pdpParams; private TimerManager updTimers; private TimerManager stateTimers; - private PolicyModelsProviderFactoryWrapper dao; - private PolicyNotifier notifier; /** * Sets up the objects and creates an empty {@link #builder}. @@ -61,12 +58,10 @@ public class TestPdpModifyRequestMapParams { pdpParams = mock(PdpParameters.class); updTimers = mock(TimerManager.class); stateTimers = mock(TimerManager.class); - dao = mock(PolicyModelsProviderFactoryWrapper.class); - notifier = mock(PolicyNotifier.class); builder = PdpModifyRequestMapParams.builder().modifyLock(lock).pdpPublisher(pub).responseDispatcher(disp) .params(pdpParams).stateChangeTimers(stateTimers).updateTimers(updTimers) - .daoFactory(dao).policyNotifier(notifier).maxPdpAgeMs(MAX_PDP_AGE_MS); + .maxPdpAgeMs(MAX_PDP_AGE_MS); } @Test @@ -79,8 +74,6 @@ public class TestPdpModifyRequestMapParams { assertSame(pdpParams, params.getParams()); assertSame(updTimers, params.getUpdateTimers()); assertSame(stateTimers, params.getStateChangeTimers()); - assertSame(dao, params.getDaoFactory()); - assertSame(notifier, params.getPolicyNotifier()); } @Test @@ -133,16 +126,4 @@ public class TestPdpModifyRequestMapParams { assertThatIllegalArgumentException().isThrownBy(() -> builder.updateTimers(null).build().validate()) .withMessageContaining("update"); } - - @Test - public void testValidate_MissingDaoFactory() { - assertThatIllegalArgumentException().isThrownBy(() -> builder.daoFactory(null).build().validate()) - .withMessageContaining("DAO"); - } - - @Test - public void testValidate_MissingNotifier() { - assertThatIllegalArgumentException().isThrownBy(() -> builder.policyNotifier(null).build().validate()) - .withMessageContaining("notifier"); - } } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java b/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java index 9673c295..e42cfd21 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -111,7 +111,7 @@ public abstract class CommonPapRestServer { @DynamicPropertySource static void registerPgProperties(DynamicPropertyRegistry registry) { - registry.add("pap.databaseProviderParameters.databaseUrl", () -> "jdbc:h2:mem:testdb" + CommonTestData.dbNum); + registry.add("spring.datasource.url", () -> "jdbc:h2:mem:testdb" + CommonTestData.dbNum); registry.add("server.ssl.enabled", () -> "true"); registry.add("server.ssl.key-store", () -> keystore.getKeystoreName()); registry.add("server.ssl.key-store-password", () -> SelfSignedKeyStore.KEYSTORE_PASSWORD); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/ProviderSuper.java b/main/src/test/java/org/onap/policy/pap/main/rest/ProviderSuper.java index 26e44d80..153a2bfa 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/ProviderSuper.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/ProviderSuper.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,13 +50,15 @@ import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpGroups; import org.onap.policy.models.pdp.concepts.PdpStateChange; import org.onap.policy.models.pdp.concepts.PdpUpdate; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType; import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; import org.onap.policy.pap.main.comm.PdpModifyRequestMap; import org.onap.policy.pap.main.notification.PolicyNotifier; +import org.onap.policy.pap.main.service.PdpGroupService; +import org.onap.policy.pap.main.service.PolicyAuditService; +import org.onap.policy.pap.main.service.PolicyStatusService; +import org.onap.policy.pap.main.service.ToscaServiceTemplateService; /** * Super class for TestPdpGroupDeployProviderXxx classes. @@ -65,11 +68,19 @@ public class ProviderSuper { public static final String DEFAULT_USER = "PAP_TEST"; @Mock - protected PolicyModelsProvider dao; + protected PdpGroupService pdpGroupService; @Mock - protected PolicyNotifier notifier; + protected PolicyStatusService policyStatusService; + + @Mock + protected PolicyAuditService policyAuditService; + @Mock + protected ToscaServiceTemplateService toscaService; + + @Mock + protected PolicyNotifier notifier; /** * Used to capture input to dao.updatePdpGroups() and dao.createPdpGroups(). @@ -79,7 +90,6 @@ public class ProviderSuper { protected Object lockit; protected PdpModifyRequestMap reqmap; - protected PolicyModelsProviderFactoryWrapper daofact; protected ToscaPolicy policy1; protected PapStatisticsManager statsmanager; @@ -96,26 +106,35 @@ public class ProviderSuper { reqmap = mock(PdpModifyRequestMap.class); lockit = new Object(); - daofact = mock(PolicyModelsProviderFactoryWrapper.class); policy1 = loadPolicy("policy.json"); statsmanager = mock(PapStatisticsManager.class); - when(daofact.create()).thenReturn(dao); - List groups = loadGroups("groups.json"); - when(dao.getFilteredPdpGroups(any())).thenReturn(groups); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(groups); - when(dao.createPdpGroups(any())).thenAnswer(answer -> answer.getArgument(0, List.class)); - when(dao.updatePdpGroups(any())).thenAnswer(answer -> answer.getArgument(0, List.class)); + when(pdpGroupService.createPdpGroups(any())).thenAnswer(answer -> answer.getArgument(0, List.class)); + when(pdpGroupService.updatePdpGroups(any())).thenAnswer(answer -> answer.getArgument(0, List.class)); Registry.register(PapConstants.REG_PDP_MODIFY_LOCK, lockit); Registry.register(PapConstants.REG_PDP_MODIFY_MAP, reqmap); - Registry.register(PapConstants.REG_PAP_DAO_FACTORY, daofact); - Registry.register(PapConstants.REG_POLICY_NOTIFIER, notifier); Registry.register(PapConstants.REG_STATISTICS_MANAGER, statsmanager); } + /** + * Initialize services to the provider for tests. + * + * @param prov the provider + */ + public void initialize(ProviderBase prov) { + prov.setPdpGroupService(pdpGroupService); + prov.setPolicyAuditService(policyAuditService); + prov.setPolicyStatusService(policyStatusService); + prov.setToscaService(toscaService); + prov.setPolicyNotifier(notifier); + prov.initialize(); + } + protected void assertGroup(List groups, String name) { PdpGroup group = groups.remove(0); @@ -138,7 +157,7 @@ public class ProviderSuper { * @throws Exception if an error occurred */ protected List getGroupCreates() throws Exception { - verify(dao).createPdpGroups(updateCaptor.capture()); + verify(pdpGroupService).createPdpGroups(updateCaptor.capture()); return copyList(updateCaptor.getValue()); } @@ -150,7 +169,7 @@ public class ProviderSuper { * @throws Exception if an error occurred */ protected List getGroupUpdates() throws Exception { - verify(dao).updatePdpGroups(updateCaptor.capture()); + verify(pdpGroupService).updatePdpGroups(updateCaptor.capture()); return copyList(updateCaptor.getValue()); } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateProvider.java index 9a0f5702..7666dc2a 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateProvider.java @@ -1,563 +1,561 @@ -/* - * ============LICENSE_START======================================================= - * ONAP PAP - * ================================================================================ - * Copyright (C) 2019-2021 Nordix Foundation. - * Modifications Copyright (C) 2021 AT&T Intellectual Property. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.pap.main.rest; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.TreeMap; -import javax.ws.rs.core.Response.Status; -import org.assertj.core.api.Assertions; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.common.utils.services.Registry; -import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.pdp.concepts.PdpGroup; -import org.onap.policy.models.pdp.concepts.PdpGroups; -import org.onap.policy.models.pdp.concepts.PdpStateChange; -import org.onap.policy.models.pdp.concepts.PdpSubGroup; -import org.onap.policy.models.pdp.concepts.PdpUpdate; -import org.onap.policy.models.pdp.enums.PdpState; -import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; -import org.onap.policy.pap.main.PapConstants; - -public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { - private static final String EXPECTED_EXCEPTION = "expected exception"; - - private static final String PDP2 = "pdpB"; - private static final String PDP4 = "pdpD"; - - private PdpGroupCreateOrUpdateProvider prov; - - @AfterClass - public static void tearDownAfterClass() { - Registry.newRegistry(); - } - - /** - * Configures mocks and objects. - * - * @throws Exception if an error occurs - */ - @Before - @Override - public void setUp() throws Exception { - - super.setUp(); - - when(dao.getPolicyTypeList("typeA", "100.2.3")).thenReturn(Arrays.asList(loadPolicyType("daoPolicyType.json"))); - - prov = new PdpGroupCreateOrUpdateProvider(); - prov.initialize(); - } - - @Test - public void testCreateOrUpdateGroups() throws Exception { - prov.createOrUpdateGroups(loadPdpGroups("emptyGroups.json")); - - // no groups, so no action should have been taken - assertNoGroupAction(); - } - - @Test - public void testCreateOrUpdateGroups_InvalidRequest() throws Exception { - assertThatThrownBy(() -> prov.createOrUpdateGroups(new PdpGroups())).isInstanceOf(PfModelException.class) - .hasMessageContaining("is null"); - - assertNoGroupAction(); - } - - @Test - public void testCreateOrUpdate_Invalid() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - groups.getGroups().get(0).setPdpGroupState(PdpState.TERMINATED); - - assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) - .hasMessageContaining("pdpGroupState"); - - assertNoGroupAction(); - } - - @Test - public void testAddGroup() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup group = groups.getGroups().get(0); - group.setPdpGroupState(PdpState.PASSIVE); - - prov.createOrUpdateGroups(groups); - - // should not have updated the state - assertEquals(PdpState.PASSIVE, group.getPdpGroupState()); - - assertSame(group, getGroupCreates().get(0)); - } - - @Test - public void testAddGroup_Invalid() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - groups.getGroups().get(0).setPdpGroupState(PdpState.TERMINATED); - - assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) - .hasMessageContaining("pdpGroupState"); - - assertNoGroupAction(); - } - - @Test - public void testAddGroup_InvalidSubGroup() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - - groups.getGroups().get(0).getPdpSubgroups().get(0).getSupportedPolicyTypes().get(0).setVersion("99.99.99"); - - assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) - .hasMessageContaining("unknown policy type"); - - assertNoGroupAction(); - } - - @Test - public void testValidateGroupOnly_NullState() { - PdpGroups groups = loadPdpGroups("createGroups.json"); - groups.getGroups().get(0).setPdpGroupState(null); - Assertions.assertThatCode(() -> prov.createOrUpdateGroups(groups)).doesNotThrowAnyException(); - } - - @Test - public void testValidateGroupOnly_Active() { - PdpGroups groups = loadPdpGroups("createGroups.json"); - groups.getGroups().get(0).setPdpGroupState(PdpState.ACTIVE); - Assertions.assertThatCode(() -> prov.createOrUpdateGroups(groups)).doesNotThrowAnyException(); - } - - @Test - public void testValidateGroupOnly_Passive() { - PdpGroups groups = loadPdpGroups("createGroups.json"); - groups.getGroups().get(0).setPdpGroupState(PdpState.PASSIVE); - Assertions.assertThatCode(() -> prov.createOrUpdateGroups(groups)).doesNotThrowAnyException(); - } - - @Test - public void testValidateGroupOnly_Invalid() { - PdpGroups groups = loadPdpGroups("createGroups.json"); - groups.getGroups().get(0).setPdpGroupState(PdpState.TERMINATED); - - assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) - .hasMessageContaining("pdpGroupState"); - } - - @Test - public void testUpdateGroup() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - - // DB group = new group - PdpGroup group = new PdpGroup(groups.getGroups().get(0)); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - prov.createOrUpdateGroups(groups); - - assertNoGroupAction(); - } - - @Test - public void testUpdateGroup_PropertiesChanged() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - - PdpGroup group = new PdpGroup(groups.getGroups().get(0)); - group.setProperties(new TreeMap<>()); - - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) - .hasMessageContaining("properties"); - - assertNoGroupAction(); - } - - @Test - public void testUpdateGroup_NewDescription() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup newgrp = groups.getGroups().get(0); - PdpGroup group = new PdpGroup(newgrp); - group.setDescription("old description"); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - prov.createOrUpdateGroups(groups); - - assertGroupUpdateOnly(group); - - assertEquals("my description", group.getDescription()); - assertEquals(newgrp.toString(), group.toString()); - } - - @Test - public void testUpdateGroup_NewState() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup newgrp = groups.getGroups().get(0); - PdpGroup group = new PdpGroup(newgrp); - group.setPdpGroupState(PdpState.TEST); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - prov.createOrUpdateGroups(groups); - - assertGroupUpdateOnly(group); - - assertEquals(PdpState.ACTIVE, group.getPdpGroupState()); - assertEquals(newgrp.toString(), group.toString()); - } - - @Test - public void testUpdateGroup_NewSubGroup() throws Exception { - PdpGroups groups = loadPdpGroups("createGroupsNewSub.json"); - PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - prov.createOrUpdateGroups(groups); - - PdpGroup newgrp = groups.getGroups().get(0); - assertEquals(newgrp.toString(), group.toString()); - assertGroupUpdateOnly(group); - } - - @Test - public void testUpdateGroup_UpdatedSubGroup() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup newgrp = groups.getGroups().get(0); - PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - // something different in this subgroup - group.getPdpSubgroups().get(0).setDesiredInstanceCount(10); - - prov.createOrUpdateGroups(groups); - - assertEquals(newgrp.toString(), group.toString()); - assertGroupUpdateOnly(group); - } - - @Test - public void testUpdateGroup_notifyPdpsDelSubGroups() throws Exception { - PdpGroup dbgroup = new PdpGroup(loadPdpGroups("createGroupsDelSub.json").getGroups().get(0)); - when(dao.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); - - PdpGroups groups = loadPdpGroups("createGroups.json"); - - prov.createOrUpdateGroups(groups); - - // verify that DB group was updated - List updates = getGroupUpdates(); - assertEquals(1, updates.size()); - dbgroup = updates.get(0); - - PdpGroup newgrp = groups.getGroups().get(0); - - Collections.sort(newgrp.getPdpSubgroups().get(0).getPolicies()); - Collections.sort(dbgroup.getPdpSubgroups().get(0).getPolicies()); - - assertEquals(newgrp.toString(), dbgroup.toString()); - - // no deployment notifications - checkEmptyNotification(); - - // this requires a PDP UPDATE message - List pdpUpdates = getUpdateRequests(2); - assertEquals(2, pdpUpdates.size()); - - PdpUpdate pdpUpdate = pdpUpdates.get(0); - assertEquals(PapConstants.PAP_NAME, pdpUpdate.getSource()); - assertEquals(PDP2, pdpUpdate.getName()); - assertNull(pdpUpdate.getPdpGroup()); - - pdpUpdate = pdpUpdates.get(1); - assertEquals(PapConstants.PAP_NAME, pdpUpdate.getSource()); - assertEquals(PDP4, pdpUpdate.getName()); - assertNull(pdpUpdate.getPdpGroup()); - - // it also requires a PDP STATE-CHANGE message - List changes = getStateChangeRequests(2); - assertEquals(2, changes.size()); - - PdpStateChange change = changes.get(0); - assertEquals(PapConstants.PAP_NAME, change.getSource()); - assertEquals(PDP2, change.getName()); - assertEquals(PdpState.PASSIVE, change.getState()); - - change = changes.get(1); - assertEquals(PapConstants.PAP_NAME, change.getSource()); - assertEquals(PDP4, change.getName()); - assertEquals(PdpState.PASSIVE, change.getState()); - } - - @Test - public void testUpdateField_Unchanged() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup newgrp = groups.getGroups().get(0); - PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - prov.createOrUpdateGroups(groups); - - assertNoGroupAction(); - } - - @Test - public void testUpdateField_WasNull() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup newgrp = groups.getGroups().get(0); - PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - group.setDescription(null); - - prov.createOrUpdateGroups(groups); - - assertEquals(newgrp.toString(), group.toString()); - assertGroupUpdateOnly(group); - } - - @Test - public void testUpdateField_NowNull() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup newgrp = groups.getGroups().get(0); - PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - newgrp.setDescription(null); - - prov.createOrUpdateGroups(groups); - - assertEquals(newgrp.toString(), group.toString()); - assertGroupUpdateOnly(group); - } - - @Test - public void testUpdateField_Changed() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup newgrp = groups.getGroups().get(0); - PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - newgrp.setDescription(group.getDescription() + "-changed"); - - prov.createOrUpdateGroups(groups); - - assertEquals(newgrp.toString(), group.toString()); - assertGroupUpdateOnly(group); - } - - @Test - public void testAddSubGroup() throws Exception { - PdpGroups groups = loadPdpGroups("createGroupsNewSub.json"); - PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - prov.createOrUpdateGroups(groups); - - PdpGroup newgrp = groups.getGroups().get(0); - - PdpSubGroup newsub = newgrp.getPdpSubgroups().get(1); - newsub.setCurrentInstanceCount(0); - newsub.setPdpInstances(new ArrayList<>(0)); - - assertEquals(newgrp.toString(), group.toString()); - assertGroupUpdateOnly(group); - } - - /** - * Tests addSubgroup() when the new subgroup has a wild-card policy type. - * - * @throws Exception if an error occurs - */ - @Test - public void testAddSubGroupWildCardPolicyType() throws Exception { - when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyListWildCard.json")); - when(dao.getPolicyTypeList("some.*", "2.3.4")).thenReturn(Collections.emptyList()); - - PdpGroups groups = loadPdpGroups("createGroupsWildCard.json"); - PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - prov.createOrUpdateGroups(groups); - - PdpGroup newgrp = groups.getGroups().get(0); - - PdpSubGroup newsub = newgrp.getPdpSubgroups().get(1); - newsub.setCurrentInstanceCount(0); - newsub.setPdpInstances(new ArrayList<>(0)); - - assertEquals(newgrp.toString(), group.toString()); - } - - @Test - public void testAddSubGroup_ValidationPolicyTypeNotFound() throws Exception { - PdpGroups groups = loadPdpGroups("createGroupsNewSub.json"); - PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - when(dao.getPolicyTypeList(any(), any())).thenReturn(Collections.emptyList()); - - assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).hasMessageContaining("unknown policy type"); - } - - @Test - public void testAddSubGroup_ValidationPolicyTypeDaoEx() throws Exception { - PdpGroups groups = loadPdpGroups("createGroupsNewSub.json"); - PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - PfModelException exc = new PfModelException(Status.CONFLICT, EXPECTED_EXCEPTION); - when(dao.getPolicyTypeList(any(), any())).thenThrow(exc); - - assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isSameAs(exc); - } - - @Test - public void testAddSubGroup_ValidateVersionPrefixMatch() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup newgrp = groups.getGroups().get(0); - PdpGroup dbgroup = new PdpGroup(newgrp); - when(dao.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); - - when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json")) - .thenReturn(loadPolicies("daoPolicyList.json")).thenReturn(loadPolicies("createGroupNewPolicy.json")); - - PdpGroups reqgroups = loadPdpGroups("createGroupsVersPrefix.json"); - - prov.createOrUpdateGroups(reqgroups); - - Collections.sort(newgrp.getPdpSubgroups().get(0).getPolicies()); - Collections.sort(dbgroup.getPdpSubgroups().get(0).getPolicies()); - - assertEquals(newgrp.toString(), dbgroup.toString()); - } - - @Test - public void testUpdateSubGroup_Invalid() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup newgrp = groups.getGroups().get(0); - PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - // change properties - newgrp.getPdpSubgroups().get(0).setProperties(new TreeMap<>()); - - assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) - .hasMessageContaining("properties"); - - assertNoGroupAction(); - } - - @Test - public void testUpdateSubGroup_SupportedPolicies() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup newgrp = groups.getGroups().get(0); - PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - newgrp.getPdpSubgroups().get(0).getSupportedPolicyTypes() - .add(new ToscaConceptIdentifier("typeX.*", "9.8.7")); - - // the group is updated with a new supported policy type in subgroup - assertEquals(2, newgrp.getPdpSubgroups().get(0).getSupportedPolicyTypes().size()); - prov.createOrUpdateGroups(groups); - // PdpGroup update doesn't allow supported policy type modifications - // during pdp group update, the ones in db is maintained - assertEquals(1, newgrp.getPdpSubgroups().get(0).getSupportedPolicyTypes().size()); - assertEquals(newgrp.toString(), group.toString()); - } - - @Test - public void testUpdateSubGroup_DesiredCount() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup newgrp = groups.getGroups().get(0); - PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - newgrp.getPdpSubgroups().get(0).setDesiredInstanceCount(20); - - prov.createOrUpdateGroups(groups); - - assertEquals(newgrp.toString(), group.toString()); - assertGroupUpdateOnly(group); - } - - @Test - public void testUpdateSubGroup_Unchanged() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup newgrp = groups.getGroups().get(0); - PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - prov.createOrUpdateGroups(groups); - - Collections.sort(newgrp.getPdpSubgroups().get(0).getPolicies()); - Collections.sort(group.getPdpSubgroups().get(0).getPolicies()); - - assertEquals(newgrp.toString(), group.toString()); - - // no notifications - checkEmptyNotification(); - - // no group updates - assertNoGroupAction(); - } - - @Test - public void testValidateSubGroup_PropertiesMismatch() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - PdpGroup newgrp = groups.getGroups().get(0); - PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); - - newgrp.setProperties(new TreeMap<>()); - - assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) - .hasMessageContaining("properties"); - - assertNoGroupAction(); - } - - private void assertNoGroupAction() throws Exception { - verify(dao, never()).createPdpGroups(any()); - verify(dao, never()).updatePdpGroups(any()); - verify(reqmap, never()).addRequest(any(), any()); - } - - private void assertGroupUpdateOnly(PdpGroup group) throws Exception { - verify(dao, never()).createPdpGroups(any()); - verify(reqmap, never()).addRequest(any(), any()); - - List updates = getGroupUpdates(); - assertEquals(Arrays.asList(group), updates); - } -} +/* + * ============LICENSE_START======================================================= + * ONAP PAP + * ================================================================================ + * Copyright (C) 2019-2021 Nordix Foundation. + * Modifications Copyright (C) 2021 AT&T Intellectual Property. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.main.rest; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.TreeMap; +import javax.ws.rs.core.Response.Status; +import org.assertj.core.api.Assertions; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.utils.services.Registry; +import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.pdp.concepts.PdpGroup; +import org.onap.policy.models.pdp.concepts.PdpGroups; +import org.onap.policy.models.pdp.concepts.PdpStateChange; +import org.onap.policy.models.pdp.concepts.PdpSubGroup; +import org.onap.policy.models.pdp.concepts.PdpUpdate; +import org.onap.policy.models.pdp.enums.PdpState; +import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; +import org.onap.policy.pap.main.PapConstants; + +public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { + private static final String EXPECTED_EXCEPTION = "expected exception"; + + private static final String PDP2 = "pdpB"; + private static final String PDP4 = "pdpD"; + + private PdpGroupCreateOrUpdateProvider prov; + + + + @AfterClass + public static void tearDownAfterClass() { + Registry.newRegistry(); + } + + /** + * Configures mocks and objects. + * + * @throws Exception if an error occurs + */ + @Before + @Override + public void setUp() throws Exception { super.setUp(); + prov = new PdpGroupCreateOrUpdateProvider(); + super.initialize(prov); + when(toscaService.getPolicyTypeList("typeA", "100.2.3")) + .thenReturn(Arrays.asList(loadPolicyType("daoPolicyType.json"))); } + + @Test + public void testCreateOrUpdateGroups() throws Exception { + prov.createOrUpdateGroups(loadPdpGroups("emptyGroups.json")); + + // no groups, so no action should have been taken + assertNoGroupAction(); + } + + @Test + public void testCreateOrUpdateGroups_InvalidRequest() throws Exception { + assertThatThrownBy(() -> prov.createOrUpdateGroups(new PdpGroups())).isInstanceOf(PfModelException.class) + .hasMessageContaining("is null"); + + assertNoGroupAction(); + } + + @Test + public void testCreateOrUpdate_Invalid() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + groups.getGroups().get(0).setPdpGroupState(PdpState.TERMINATED); + + assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) + .hasMessageContaining("pdpGroupState"); + + assertNoGroupAction(); + } + + @Test + public void testAddGroup() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup group = groups.getGroups().get(0); + group.setPdpGroupState(PdpState.PASSIVE); + + prov.createOrUpdateGroups(groups); + + // should not have updated the state + assertEquals(PdpState.PASSIVE, group.getPdpGroupState()); + + assertSame(group, getGroupCreates().get(0)); + } + + @Test + public void testAddGroup_Invalid() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + groups.getGroups().get(0).setPdpGroupState(PdpState.TERMINATED); + + assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) + .hasMessageContaining("pdpGroupState"); + + assertNoGroupAction(); + } + + @Test + public void testAddGroup_InvalidSubGroup() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + + groups.getGroups().get(0).getPdpSubgroups().get(0).getSupportedPolicyTypes().get(0).setVersion("99.99.99"); + + assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) + .hasMessageContaining("unknown policy type"); + + assertNoGroupAction(); + } + + @Test + public void testValidateGroupOnly_NullState() { + PdpGroups groups = loadPdpGroups("createGroups.json"); + groups.getGroups().get(0).setPdpGroupState(null); + Assertions.assertThatCode(() -> prov.createOrUpdateGroups(groups)).doesNotThrowAnyException(); + } + + @Test + public void testValidateGroupOnly_Active() { + PdpGroups groups = loadPdpGroups("createGroups.json"); + groups.getGroups().get(0).setPdpGroupState(PdpState.ACTIVE); + Assertions.assertThatCode(() -> prov.createOrUpdateGroups(groups)).doesNotThrowAnyException(); + } + + @Test + public void testValidateGroupOnly_Passive() { + PdpGroups groups = loadPdpGroups("createGroups.json"); + groups.getGroups().get(0).setPdpGroupState(PdpState.PASSIVE); + Assertions.assertThatCode(() -> prov.createOrUpdateGroups(groups)).doesNotThrowAnyException(); + } + + @Test + public void testValidateGroupOnly_Invalid() { + PdpGroups groups = loadPdpGroups("createGroups.json"); + groups.getGroups().get(0).setPdpGroupState(PdpState.TERMINATED); + + assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) + .hasMessageContaining("pdpGroupState"); + } + + @Test + public void testUpdateGroup() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + + // DB group = new group + PdpGroup group = new PdpGroup(groups.getGroups().get(0)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + prov.createOrUpdateGroups(groups); + + assertNoGroupAction(); + } + + @Test + public void testUpdateGroup_PropertiesChanged() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + + PdpGroup group = new PdpGroup(groups.getGroups().get(0)); + group.setProperties(new TreeMap<>()); + + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) + .hasMessageContaining("properties"); + + assertNoGroupAction(); + } + + @Test + public void testUpdateGroup_NewDescription() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup newgrp = groups.getGroups().get(0); + PdpGroup group = new PdpGroup(newgrp); + group.setDescription("old description"); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + prov.createOrUpdateGroups(groups); + + assertGroupUpdateOnly(group); + + assertEquals("my description", group.getDescription()); + assertEquals(newgrp.toString(), group.toString()); + } + + @Test + public void testUpdateGroup_NewState() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup newgrp = groups.getGroups().get(0); + PdpGroup group = new PdpGroup(newgrp); + group.setPdpGroupState(PdpState.TEST); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + prov.createOrUpdateGroups(groups); + + assertGroupUpdateOnly(group); + + assertEquals(PdpState.ACTIVE, group.getPdpGroupState()); + assertEquals(newgrp.toString(), group.toString()); + } + + @Test + public void testUpdateGroup_NewSubGroup() throws Exception { + PdpGroups groups = loadPdpGroups("createGroupsNewSub.json"); + PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + prov.createOrUpdateGroups(groups); + + PdpGroup newgrp = groups.getGroups().get(0); + assertEquals(newgrp.toString(), group.toString()); + assertGroupUpdateOnly(group); + } + + @Test + public void testUpdateGroup_UpdatedSubGroup() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup newgrp = groups.getGroups().get(0); + PdpGroup group = new PdpGroup(newgrp); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + // something different in this subgroup + group.getPdpSubgroups().get(0).setDesiredInstanceCount(10); + + prov.createOrUpdateGroups(groups); + + assertEquals(newgrp.toString(), group.toString()); + assertGroupUpdateOnly(group); + } + + @Test + public void testUpdateGroup_notifyPdpsDelSubGroups() throws Exception { + PdpGroup dbgroup = new PdpGroup(loadPdpGroups("createGroupsDelSub.json").getGroups().get(0)); + when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); + + PdpGroups groups = loadPdpGroups("createGroups.json"); + + prov.createOrUpdateGroups(groups); + + // verify that DB group was updated + List updates = getGroupUpdates(); + assertEquals(1, updates.size()); + dbgroup = updates.get(0); + + PdpGroup newgrp = groups.getGroups().get(0); + + Collections.sort(newgrp.getPdpSubgroups().get(0).getPolicies()); + Collections.sort(dbgroup.getPdpSubgroups().get(0).getPolicies()); + + assertEquals(newgrp.toString(), dbgroup.toString()); + + // no deployment notifications + checkEmptyNotification(); + + // this requires a PDP UPDATE message + List pdpUpdates = getUpdateRequests(2); + assertEquals(2, pdpUpdates.size()); + + PdpUpdate pdpUpdate = pdpUpdates.get(0); + assertEquals(PapConstants.PAP_NAME, pdpUpdate.getSource()); + assertEquals(PDP2, pdpUpdate.getName()); + assertNull(pdpUpdate.getPdpGroup()); + + pdpUpdate = pdpUpdates.get(1); + assertEquals(PapConstants.PAP_NAME, pdpUpdate.getSource()); + assertEquals(PDP4, pdpUpdate.getName()); + assertNull(pdpUpdate.getPdpGroup()); + + // it also requires a PDP STATE-CHANGE message + List changes = getStateChangeRequests(2); + assertEquals(2, changes.size()); + + PdpStateChange change = changes.get(0); + assertEquals(PapConstants.PAP_NAME, change.getSource()); + assertEquals(PDP2, change.getName()); + assertEquals(PdpState.PASSIVE, change.getState()); + + change = changes.get(1); + assertEquals(PapConstants.PAP_NAME, change.getSource()); + assertEquals(PDP4, change.getName()); + assertEquals(PdpState.PASSIVE, change.getState()); + } + + @Test + public void testUpdateField_Unchanged() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup newgrp = groups.getGroups().get(0); + PdpGroup group = new PdpGroup(newgrp); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + prov.createOrUpdateGroups(groups); + + assertNoGroupAction(); + } + + @Test + public void testUpdateField_WasNull() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup newgrp = groups.getGroups().get(0); + PdpGroup group = new PdpGroup(newgrp); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + group.setDescription(null); + + prov.createOrUpdateGroups(groups); + + assertEquals(newgrp.toString(), group.toString()); + assertGroupUpdateOnly(group); + } + + @Test + public void testUpdateField_NowNull() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup newgrp = groups.getGroups().get(0); + PdpGroup group = new PdpGroup(newgrp); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + newgrp.setDescription(null); + + prov.createOrUpdateGroups(groups); + + assertEquals(newgrp.toString(), group.toString()); + assertGroupUpdateOnly(group); + } + + @Test + public void testUpdateField_Changed() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup newgrp = groups.getGroups().get(0); + PdpGroup group = new PdpGroup(newgrp); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + newgrp.setDescription(group.getDescription() + "-changed"); + + prov.createOrUpdateGroups(groups); + + assertEquals(newgrp.toString(), group.toString()); + assertGroupUpdateOnly(group); + } + + @Test + public void testAddSubGroup() throws Exception { + PdpGroups groups = loadPdpGroups("createGroupsNewSub.json"); + PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + prov.createOrUpdateGroups(groups); + + PdpGroup newgrp = groups.getGroups().get(0); + + PdpSubGroup newsub = newgrp.getPdpSubgroups().get(1); + newsub.setCurrentInstanceCount(0); + newsub.setPdpInstances(new ArrayList<>(0)); + + assertEquals(newgrp.toString(), group.toString()); + assertGroupUpdateOnly(group); + } + + /** + * Tests addSubgroup() when the new subgroup has a wild-card policy type. + * + * @throws Exception if an error occurs + */ + @Test + public void testAddSubGroupWildCardPolicyType() throws Exception { + when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyListWildCard.json")); + when(toscaService.getPolicyTypeList("some.*", "2.3.4")).thenReturn(Collections.emptyList()); + + PdpGroups groups = loadPdpGroups("createGroupsWildCard.json"); + PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + prov.createOrUpdateGroups(groups); + + PdpGroup newgrp = groups.getGroups().get(0); + + PdpSubGroup newsub = newgrp.getPdpSubgroups().get(1); + newsub.setCurrentInstanceCount(0); + newsub.setPdpInstances(new ArrayList<>(0)); + + assertEquals(newgrp.toString(), group.toString()); + } + + @Test + public void testAddSubGroup_ValidationPolicyTypeNotFound() throws Exception { + PdpGroups groups = loadPdpGroups("createGroupsNewSub.json"); + PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + when(toscaService.getPolicyTypeList(any(), any())).thenReturn(Collections.emptyList()); + + assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).hasMessageContaining("unknown policy type"); + } + + @Test + public void testAddSubGroup_ValidationPolicyTypeDaoEx() throws Exception { + PdpGroups groups = loadPdpGroups("createGroupsNewSub.json"); + PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + PfModelException exc = new PfModelException(Status.CONFLICT, EXPECTED_EXCEPTION); + when(toscaService.getPolicyTypeList(any(), any())).thenThrow(exc); + + assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isSameAs(exc); + } + + @Test + public void testAddSubGroup_ValidateVersionPrefixMatch() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup newgrp = groups.getGroups().get(0); + PdpGroup dbgroup = new PdpGroup(newgrp); + when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); + + when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json")) + .thenReturn(loadPolicies("daoPolicyList.json")).thenReturn(loadPolicies("createGroupNewPolicy.json")); + + PdpGroups reqgroups = loadPdpGroups("createGroupsVersPrefix.json"); + + prov.createOrUpdateGroups(reqgroups); + + Collections.sort(newgrp.getPdpSubgroups().get(0).getPolicies()); + Collections.sort(dbgroup.getPdpSubgroups().get(0).getPolicies()); + + assertEquals(newgrp.toString(), dbgroup.toString()); + } + + @Test + public void testUpdateSubGroup_Invalid() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup newgrp = groups.getGroups().get(0); + PdpGroup group = new PdpGroup(newgrp); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + // change properties + newgrp.getPdpSubgroups().get(0).setProperties(new TreeMap<>()); + + assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) + .hasMessageContaining("properties"); + + assertNoGroupAction(); + } + + @Test + public void testUpdateSubGroup_SupportedPolicies() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup newgrp = groups.getGroups().get(0); + PdpGroup group = new PdpGroup(newgrp); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + newgrp.getPdpSubgroups().get(0).getSupportedPolicyTypes() + .add(new ToscaConceptIdentifier("typeX.*", "9.8.7")); + + // the group is updated with a new supported policy type in subgroup + assertEquals(2, newgrp.getPdpSubgroups().get(0).getSupportedPolicyTypes().size()); + prov.createOrUpdateGroups(groups); + // PdpGroup update doesn't allow supported policy type modifications + // during pdp group update, the ones in db is maintained + assertEquals(1, newgrp.getPdpSubgroups().get(0).getSupportedPolicyTypes().size()); + assertEquals(newgrp.toString(), group.toString()); + } + + @Test + public void testUpdateSubGroup_DesiredCount() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup newgrp = groups.getGroups().get(0); + PdpGroup group = new PdpGroup(newgrp); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + newgrp.getPdpSubgroups().get(0).setDesiredInstanceCount(20); + + prov.createOrUpdateGroups(groups); + + assertEquals(newgrp.toString(), group.toString()); + assertGroupUpdateOnly(group); + } + + @Test + public void testUpdateSubGroup_Unchanged() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup newgrp = groups.getGroups().get(0); + PdpGroup group = new PdpGroup(newgrp); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + prov.createOrUpdateGroups(groups); + + Collections.sort(newgrp.getPdpSubgroups().get(0).getPolicies()); + Collections.sort(group.getPdpSubgroups().get(0).getPolicies()); + + assertEquals(newgrp.toString(), group.toString()); + + // no notifications + checkEmptyNotification(); + + // no group updates + assertNoGroupAction(); + } + + @Test + public void testValidateSubGroup_PropertiesMismatch() throws Exception { + PdpGroups groups = loadPdpGroups("createGroups.json"); + PdpGroup newgrp = groups.getGroups().get(0); + PdpGroup group = new PdpGroup(newgrp); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + + newgrp.setProperties(new TreeMap<>()); + + assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) + .hasMessageContaining("properties"); + + assertNoGroupAction(); + } + + private void assertNoGroupAction() throws Exception { + verify(pdpGroupService, never()).createPdpGroups(any()); + verify(pdpGroupService, never()).updatePdpGroups(any()); + verify(reqmap, never()).addRequest(any(), any()); + } + + private void assertGroupUpdateOnly(PdpGroup group) throws Exception { + verify(pdpGroupService, never()).createPdpGroups(any()); + verify(reqmap, never()).addRequest(any(), any()); + + List updates = getGroupUpdates(); + assertEquals(Arrays.asList(group), updates); + } +} diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java index 3e9eda8a..449d48f2 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java @@ -4,7 +4,7 @@ * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2020-2021 Nordix Foundation. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,6 +47,7 @@ import org.mockito.Captor; import org.mockito.Mock; import org.onap.policy.common.utils.services.Registry; import org.onap.policy.models.base.PfModelException; +import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpSubGroup; import org.onap.policy.models.pdp.concepts.PdpUpdate; @@ -84,14 +85,14 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { @Before @Override public void setUp() throws Exception { - super.setUp(); + prov = new MyProvider(); + super.initialize(prov); ident = policy1.getIdentifier(); optIdent = new ToscaConceptIdentifierOptVersion(ident.getName(), null); fullIdent = new ToscaConceptIdentifierOptVersion(ident.getName(), ident.getVersion()); - prov = new MyProvider(); updater = prov.makeUpdater(session, policy1, fullIdent); } @@ -144,12 +145,12 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { } @Test - public void testDeleteGroup_DaoEx() throws Exception { + public void testDeleteGroup_Ex() throws Exception { PdpGroup group = loadGroup("deleteGroup.json"); when(session.getGroup(GROUP1_NAME)).thenReturn(group); - PfModelException ex = new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION); + PfModelRuntimeException ex = new PfModelRuntimeException(Status.BAD_REQUEST, EXPECTED_EXCEPTION); doThrow(ex).when(session).deleteGroupFromDb(group); assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isSameAs(ex); @@ -162,15 +163,15 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { */ @Test public void testUndeploy_Full() throws Exception { - when(dao.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1)); + when(toscaService.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1)); PdpGroup group = loadGroup("undeploy.json"); - when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group)); - when(dao.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group)); + when(toscaService.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1)); PdpGroupDeleteProvider deleteProvider = new PdpGroupDeleteProvider(); - deleteProvider.initialize(); + super.initialize(deleteProvider); deleteProvider.undeploy(fullIdent, DEFAULT_USER); // should have updated the old group diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java index 28e515f3..29c06f76 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java @@ -4,7 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -89,12 +89,12 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { public void setUp() throws Exception { super.setUp(); - - when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList2.json")); - when(dao.getPolicyTypeList("typeA", "100.2.3")).thenReturn(Arrays.asList(loadPolicyType("daoPolicyType.json"))); - prov = new PdpGroupDeployProvider(); - prov.initialize(); + super.initialize(prov); + + when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList2.json")); + when(toscaService.getPolicyTypeList("typeA", "100.2.3")) + .thenReturn(Arrays.asList(loadPolicyType("daoPolicyType.json"))); } /** @@ -105,14 +105,14 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { PdpGroups groups = loadPdpGroups("deployGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); PdpGroup dbgroup = new PdpGroup(newgrp); - when(dao.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); + when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); // add new policies List policies = newgrp.getPdpSubgroups().get(0).getPolicies(); policies.add(new ToscaConceptIdentifier(POLICY2_NAME, POLICY2_VERSION)); policies.add(new ToscaConceptIdentifier(POLICY3_NAME, POLICY3_VERSION)); - when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json")) + when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json")) .thenReturn(loadPolicies("createGroupNewPolicy2.json")).thenReturn(loadPolicies("daoPolicyList.json")); // add = POST @@ -139,12 +139,12 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { policies.add(new ToscaConceptIdentifier(POLICY3_NAME, POLICY3_VERSION)); PdpGroup dbgroup = new PdpGroup(newgrp); - when(dao.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); + when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); // policy that should be left final ToscaConceptIdentifier policyId1 = policies.remove(0); - when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json")) + when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json")) .thenReturn(loadPolicies("createGroupNewPolicy2.json")).thenReturn(loadPolicies("daoPolicyList.json")); DeploymentGroups depgroups = toDeploymentGroups(groups); @@ -173,7 +173,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { // put policy3 into db subgroup subgrp.getPolicies().add(new ToscaConceptIdentifier(POLICY3_NAME, POLICY3_VERSION)); PdpGroup dbgroup = new PdpGroup(newgrp); - when(dao.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); + when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); // now make the subgrp reflect our final expectation subgrp.getPolicies().remove(1); @@ -197,7 +197,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { DeploymentGroups depgroups = new DeploymentGroups(); depgroups.setGroups(Arrays.asList(depgroup)); - when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json")) + when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json")) .thenReturn(loadPolicies("daoPolicyList.json")).thenReturn(loadPolicies("createGroupNewPolicy2.json")); prov.updateGroupPolicies(depgroups, DEFAULT_USER); @@ -211,7 +211,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { PdpGroups groups = loadPdpGroups("deployGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); // something different in this subgroup group.getPdpSubgroups().get(0).getPolicies().add(new ToscaConceptIdentifier(POLICY2_NAME, POLICY2_VERSION)); @@ -245,7 +245,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { String groupName = groups.getGroups().get(0).getName(); // group not found - when(dao.getPdpGroups(groupName)).thenReturn(Collections.emptyList()); + when(pdpGroupService.getPdpGroups(groupName)).thenReturn(Collections.emptyList()); assertThatThrownBy(() -> prov.updateGroupPolicies(toDeploymentGroups(groups), DEFAULT_USER)) .isInstanceOf(PfModelException.class).hasMessageContaining(groupName) @@ -260,7 +260,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { // DB group = new group PdpGroup group = new PdpGroup(groups.getGroups().get(0)); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); prov.updateGroupPolicies(toDeploymentGroups(groups), DEFAULT_USER); @@ -271,7 +271,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { public void testUpdateGroup_NewSubGroup() throws Exception { PdpGroups groups = loadPdpGroups("createGroupsNewSub.json"); PdpGroup group = loadPdpGroups("deployGroups.json").getGroups().get(0); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); assertThatThrownBy(() -> prov.updateGroupPolicies(toDeploymentGroups(groups), DEFAULT_USER)) .isInstanceOf(PfModelException.class).hasMessageContaining("pdpTypeB") @@ -285,7 +285,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { PdpGroups groups = loadPdpGroups("deployGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); // something different in this subgroup group.getPdpSubgroups().get(0).getPolicies().add(new ToscaConceptIdentifier(POLICY2_NAME, POLICY2_VERSION)); @@ -304,10 +304,10 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { // group has no policies yet group.getPdpSubgroups().get(0).getPolicies().clear(); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); // unknown policy - when(dao.getFilteredPolicyList(any())).thenReturn(Collections.emptyList()); + when(toscaService.getFilteredPolicyList(any())).thenReturn(Collections.emptyList()); assertThatThrownBy(() -> prov.updateGroupPolicies(toDeploymentGroups(groups), DEFAULT_USER)) .isInstanceOf(PfModelException.class) @@ -329,7 +329,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { newgrp.getPdpSubgroups().add(subgrp2); PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); // add two new policies ToscaConceptIdentifier policyId2 = new ToscaConceptIdentifier(POLICY2_NAME, POLICY2_VERSION); @@ -338,7 +338,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { ToscaConceptIdentifier policyId3 = new ToscaConceptIdentifier(POLICY3_NAME, POLICY3_VERSION); subgrp.getPolicies().add(policyId3); - when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json")) + when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json")) .thenReturn(loadPolicies("createGroupNewPolicy2.json")).thenReturn(loadPolicies("daoPolicyList.json")); prov.updateGroupPolicies(toDeploymentGroups(groups), DEFAULT_USER); @@ -361,7 +361,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { PdpGroup newgrp = groups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); // use version prefix PdpSubGroup subgrp = newgrp.getPdpSubgroups().get(0); @@ -388,7 +388,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { PdpGroup newgrp = groups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); // use incorrect version prefix newgrp.getPdpSubgroups().get(0).getPolicies().get(0).setVersion("9"); @@ -404,7 +404,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { PdpGroups dbgroups = loadPdpGroups("deployGroups.json"); PdpGroup newgrp = dbgroups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); - when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); prov.updateGroupPolicies(toDeploymentGroups(dbgroups), DEFAULT_USER); @@ -425,13 +425,13 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { PdpGroups dbgroups = loadPdpGroups("deployGroups.json"); PdpGroup newgrp = dbgroups.getGroups().get(0); PdpGroup dbgroup = new PdpGroup(newgrp); - when(dao.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); + when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); // arrange for DB policy version to be different PdpSubGroup dbsubgrp = dbgroup.getPdpSubgroups().get(0); dbsubgrp.getPolicies().get(0).setVersion("9.9.9"); - when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json")); + when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json")); assertThatThrownBy(() -> prov.updateGroupPolicies(toDeploymentGroups(dbgroups), DEFAULT_USER)) .isInstanceOf(PfModelException.class).hasMessageContaining("different version already deployed"); @@ -444,7 +444,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { PdpGroups dbgroups = loadPdpGroups("deployGroups.json"); PdpGroup newgrp = dbgroups.getGroups().get(0); PdpGroup dbgroup = new PdpGroup(newgrp); - when(dao.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); + when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); final DeploymentGroups groups = toDeploymentGroups(dbgroups); @@ -456,7 +456,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { // DB has a different supported type dbsubgrp.getSupportedPolicyTypes().get(0).setName("some-other-type"); - when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json")); + when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json")); assertThatThrownBy(() -> prov.updateGroupPolicies(groups, DEFAULT_USER)).isInstanceOf(PfModelException.class) .hasMessageContaining(newgrp.getPdpSubgroups().get(0).getPolicies().get(0).getName()) @@ -515,9 +515,9 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { */ @Test public void testDeployPoliciesWildCard() throws Exception { - when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("deployPoliciesWildCard.json")); - when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyListWildCard.json")); - when(dao.getPolicyTypeList(any(), any())).thenReturn(Collections.emptyList()); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(loadGroups("deployPoliciesWildCard.json")); + when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyListWildCard.json")); + when(toscaService.getPolicyTypeList(any(), any())).thenReturn(Collections.emptyList()); policy1.setName("policy.some"); policy1.setVersion(POLICY1_VERSION); @@ -544,17 +544,9 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test - public void testDeploySimplePolicies_DaoEx() throws Exception { - PfModelException exc = new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION); - when(dao.getFilteredPdpGroups(any())).thenThrow(exc); - - assertThatThrownBy(() -> prov.deployPolicies(loadRequest(), DEFAULT_USER)).isSameAs(exc); - } - - @Test - public void testDeploySimplePolicies_DaoPfRtEx() throws Exception { + public void testDeploySimplePolicies_PfRtEx() throws Exception { PfModelRuntimeException exc = new PfModelRuntimeException(Status.BAD_REQUEST, EXPECTED_EXCEPTION); - when(dao.getFilteredPdpGroups(any())).thenThrow(exc); + when(pdpGroupService.getFilteredPdpGroups(any())).thenThrow(exc); assertThatThrownBy(() -> prov.deployPolicies(loadRequest(), DEFAULT_USER)).isSameAs(exc); } @@ -562,7 +554,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { @Test public void testDeploySimplePolicies_RuntimeEx() throws Exception { RuntimeException exc = new RuntimeException(EXPECTED_EXCEPTION); - when(dao.getFilteredPolicyList(any())).thenThrow(exc); + when(toscaService.getFilteredPolicyList(any())).thenThrow(exc); assertThatThrownBy(() -> prov.deployPolicies(loadRequest(), DEFAULT_USER)).isInstanceOf(PfModelException.class) .hasCause(exc); @@ -570,7 +562,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { @Test public void testDeploySimplePolicies_NoGroups() throws Exception { - when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("emptyGroups.json")); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(loadGroups("emptyGroups.json")); assertThatThrownBy(() -> prov.deployPolicies(loadRequest(), DEFAULT_USER)).isInstanceOf(PfModelException.class) .hasMessage("policy not supported by any PDP group: policyA 1.2.3"); @@ -587,9 +579,9 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { PapStatisticsManager mgr = new PapStatisticsManager(); Registry.register(PapConstants.REG_STATISTICS_MANAGER, mgr); - when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("deployPoliciesWildCard.json")); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(loadGroups("deployPoliciesWildCard.json")); prov.deployPolicies(loadRequest("multiple_requests.json"), DEFAULT_USER); - assertEquals(mgr.getTotalPolicyDeployCount(), 3); + assertEquals(3, mgr.getTotalPolicyDeployCount()); Registry.unregister(PapConstants.REG_STATISTICS_MANAGER); Registry.register(PapConstants.REG_STATISTICS_MANAGER, statsmanager); @@ -609,7 +601,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { * Last subgroup matches. */ - when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroupDao.json")); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroupDao.json")); prov.deployPolicies(loadRequest(), DEFAULT_USER); @@ -627,14 +619,14 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { public void testMakeUpdater_PolicyVersionMismatch() throws Exception { // subgroup has a different version of the Policy - when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroupDao_DiffVers.json")); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroupDao_DiffVers.json")); PdpDeployPolicies req = loadRequest(); assertThatThrownBy(() -> prov.deployPolicies(req, DEFAULT_USER)).isInstanceOf(PfModelRuntimeException.class) .hasMessageContaining("pdpTypeC").hasMessageContaining("different version already deployed"); - verify(dao, never()).createPdpGroups(any()); - verify(dao, never()).updatePdpGroups(any()); + verify(pdpGroupService, never()).createPdpGroups(any()); + verify(pdpGroupService, never()).updatePdpGroups(any()); verify(reqmap, never()).addRequest(any(PdpUpdate.class)); } @@ -642,14 +634,14 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { public void testMakeUpdater_NoPdps() throws Exception { // subgroup has no PDPs - when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroup_NoPdpsDao.json")); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroup_NoPdpsDao.json")); PdpDeployPolicies req = loadRequest(); assertThatThrownBy(() -> prov.deployPolicies(req, DEFAULT_USER)).isInstanceOf(PfModelRuntimeException.class) .hasMessage("group " + GROUP1_NAME + " subgroup " + PDP1_TYPE + " has no active PDPs"); - verify(dao, never()).createPdpGroups(any()); - verify(dao, never()).updatePdpGroups(any()); + verify(pdpGroupService, never()).createPdpGroups(any()); + verify(pdpGroupService, never()).updatePdpGroups(any()); verify(reqmap, never()).addRequest(any(PdpUpdate.class)); } @@ -664,13 +656,13 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } private void assertNoGroupAction() throws Exception { - verify(dao, never()).createPdpGroups(any()); - verify(dao, never()).updatePdpGroups(any()); + verify(pdpGroupService, never()).createPdpGroups(any()); + verify(pdpGroupService, never()).updatePdpGroups(any()); verify(reqmap, never()).addRequest(any(), any()); } private void assertGroupUpdate(PdpGroup group, PdpSubGroup subgrp) throws Exception { - verify(dao, never()).createPdpGroups(any()); + verify(pdpGroupService, never()).createPdpGroups(any()); assertEquals(0, getStateChangeRequests(1).size()); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckProvider.java index b236c56b..0040beae 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckProvider.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. - * Modifications Copyright (C) 2020-2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2020-2022 Bell Canada. All rights reserved. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -23,8 +23,6 @@ package org.onap.policy.pap.main.rest; import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.File; @@ -45,9 +43,7 @@ import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpGroups; import org.onap.policy.models.pdp.concepts.PdpSubGroup; import org.onap.policy.models.pdp.concepts.Pdps; -import org.onap.policy.models.provider.PolicyModelsProvider; -import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; +import org.onap.policy.pap.main.service.PdpGroupService; import org.springframework.http.HttpStatus; /** @@ -59,8 +55,7 @@ import org.springframework.http.HttpStatus; public class TestPdpGroupHealthCheckProvider { @Mock - private PolicyModelsProvider dao; - private PolicyModelsProviderFactoryWrapper daofact; + private PdpGroupService pdpGroupService; private List groups; private Coder coder = new StandardCoder(); @@ -71,19 +66,14 @@ public class TestPdpGroupHealthCheckProvider { public void setUp() throws Exception { Registry.newRegistry(); - daofact = mock(PolicyModelsProviderFactoryWrapper.class); - when(daofact.create()).thenReturn(dao); - groups = loadFile("pdpGroup.json").getGroups(); - when(dao.getPdpGroups(any())).thenReturn(groups); - - Registry.register(PapConstants.REG_PAP_DAO_FACTORY, daofact); + when(pdpGroupService.getPdpGroups()).thenReturn(groups); } @Test public void testFetchPdpGroupHealthStatus() throws Exception { - final PdpGroupHealthCheckProvider provider = new PdpGroupHealthCheckProvider(); + final PdpGroupHealthCheckProvider provider = new PdpGroupHealthCheckProvider(pdpGroupService); final Pair pair = provider.fetchPdpGroupHealthStatus(); assertEquals(HttpStatus.OK, pair.getLeft()); verifyPdps(pair.getRight().getPdpList(), groups); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditManager.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditManager.java index b33c0ef6..4f844fbc 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditManager.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditManager.java @@ -1,6 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -52,7 +53,7 @@ public class TestPolicyAuditManager extends ProviderSuper { @Before public void setUp() throws Exception { super.setUp(); - auditManager = new PolicyAuditManager(dao); + auditManager = new PolicyAuditManager(policyAuditService); } @AfterClass @@ -88,7 +89,7 @@ public class TestPolicyAuditManager extends ProviderSuper { assertThat(auditManager.getAuditRecords()).hasSize(1); - doThrow(PfModelRuntimeException.class).when(dao).createAuditRecords(any()); + doThrow(PfModelRuntimeException.class).when(policyAuditService).createAuditRecords(any()); auditManager.saveRecordsToDb(); assertThat(auditManager.getAuditRecords()).isNotEmpty(); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditProvider.java deleted file mode 100644 index 51bea02a..00000000 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditProvider.java +++ /dev/null @@ -1,105 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2021 Bell Canada. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.pap.main.rest; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; - -import java.time.Instant; -import java.util.ArrayList; -import java.util.List; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.common.utils.services.Registry; -import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.pap.concepts.PolicyAudit; -import org.onap.policy.models.pap.concepts.PolicyAudit.AuditAction; -import org.onap.policy.models.pap.persistence.provider.PolicyAuditProvider.AuditFilter; -import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; - -public class TestPolicyAuditProvider extends ProviderSuper { - private static final String TEST_GROUP = "testGroup"; - private static final String TEST_PDP_TYPE = "testPdpType"; - private static final ToscaConceptIdentifier POLICY_A = new ToscaConceptIdentifier("PolicyA", "1.0.0"); - private static final ToscaConceptIdentifier POLICY_B = new ToscaConceptIdentifier("PolicyB", "2.0.0"); - - private PolicyAuditProvider provider; - - @AfterClass - public static void tearDownAfterClass() { - Registry.newRegistry(); - } - - @Override - @Before - public void setUp() throws Exception { - - super.setUp(); - provider = new PolicyAuditProvider(); - provider.initialize(); - } - - @Test - public void testGetAuditRecords() throws PfModelException { - - AuditFilter auditFilter = AuditFilter.builder().recordNum(5).fromDate(null).toDate(null).build(); - - buildAuditRecords(auditFilter); - - List result = new ArrayList<>(provider.getAuditRecords(auditFilter)); - validateAuditRecords(result, 2); - } - - private void buildAuditRecords(AuditFilter auditFilter) { - PolicyAudit audit1 = PolicyAudit.builder().auditId(123L).pdpGroup(TEST_GROUP).pdpType(TEST_PDP_TYPE) - .policy(POLICY_A).action(AuditAction.DEPLOYMENT).timestamp(Instant.now()).user(DEFAULT_USER) - .build(); - - PolicyAudit audit2 = PolicyAudit.builder().auditId(456L).pdpGroup(TEST_GROUP).pdpType(TEST_PDP_TYPE) - .policy(POLICY_B).action(AuditAction.UNDEPLOYMENT).timestamp(Instant.now()).user(DEFAULT_USER) - .build(); - - if (auditFilter.getName() == null) { - when(dao.getAuditRecords(auditFilter)).thenReturn(List.of(audit1, audit2)); - } else { - when(dao.getAuditRecords(auditFilter)).thenReturn(List.of(audit1)); - } - - } - - private void validateAuditRecords(List result, int count) { - assertThat(result).hasSize(count); - for (PolicyAudit audit : result) { - if (audit.getAuditId() == 123L) { - assertThat(audit.getPdpGroup()).isEqualTo(TEST_GROUP); - assertThat(audit.getPdpType()).isEqualTo(TEST_PDP_TYPE); - assertThat(audit.getPolicy()).isEqualTo(POLICY_A); - assertThat(audit.getAction()).isEqualTo(AuditAction.DEPLOYMENT); - assertThat(audit.getUser()).isEqualTo(DEFAULT_USER); - } else if (audit.getAuditId() == 456L) { - assertThat(audit.getPdpGroup()).isEqualTo(TEST_GROUP); - assertThat(audit.getPdpType()).isEqualTo(TEST_PDP_TYPE); - assertThat(audit.getPolicy()).isEqualTo(POLICY_B); - assertThat(audit.getAction()).isEqualTo(AuditAction.UNDEPLOYMENT); - assertThat(audit.getUser()).isEqualTo(DEFAULT_USER); - } - } - } -} diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckProvider.java index 13deef40..04d4cf91 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyComponentsHealthCheckProvider.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2020 Nordix Foundation. * Modifications Copyright (C) 2020-2021 AT&T Corp. - * Modifications Copyright (C) 2020-2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2020-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,6 @@ package org.onap.policy.pap.main.rest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import java.io.File; @@ -55,11 +54,10 @@ import org.onap.policy.models.pdp.concepts.Pdp; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpGroups; import org.onap.policy.models.pdp.enums.PdpHealthStatus; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; import org.onap.policy.pap.main.parameters.CommonTestData; import org.onap.policy.pap.main.parameters.PapParameterGroup; +import org.onap.policy.pap.main.service.PdpGroupService; import org.onap.policy.pap.main.startstop.PapActivator; import org.springframework.http.HttpStatus; import org.springframework.test.util.ReflectionTestUtils; @@ -73,10 +71,7 @@ public class TestPolicyComponentsHealthCheckProvider { private static final String HEALTHY = "healthy"; @Mock - private PolicyModelsProvider dao; - - @Mock - private PolicyModelsProviderFactoryWrapper daofact; + private PdpGroupService pdpGroupService; @Mock private HttpClientFactory clientFactory; @@ -116,11 +111,9 @@ public class TestPolicyComponentsHealthCheckProvider { @Before public void setUp() throws Exception { groups = loadPdpGroupsFromFile().getGroups(); - when(dao.getPdpGroups(any())).thenReturn(groups); + when(pdpGroupService.getPdpGroups()).thenReturn(groups); - when(daofact.create()).thenReturn(dao); Registry.newRegistry(); - Registry.register(PapConstants.REG_PAP_DAO_FACTORY, daofact); when(papActivator.isAlive()).thenReturn(true); Registry.register(PapConstants.REG_PAP_ACTIVATOR, papActivator); @@ -153,7 +146,7 @@ public class TestPolicyComponentsHealthCheckProvider { clients.add(client2); clients.add(client3); PapParameterGroup papParameterGroup = ParameterService.get(PAP_GROUP_PARAMS_NAME); - provider = new PolicyComponentsHealthCheckProvider(); + provider = new PolicyComponentsHealthCheckProvider(papParameterGroup, pdpGroupService); ReflectionTestUtils.setField(provider, "papParameterGroup", papParameterGroup); provider.initializeClientHealthCheckExecutorService(); ReflectionTestUtils.setField(provider, "clients", clients); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusProvider.java index 8f09b7e3..1f2c08ed 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusProvider.java @@ -3,7 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -59,7 +59,6 @@ public class TestPolicyStatusProvider extends ProviderSuper { private PolicyStatusProvider prov; - @AfterClass public static void tearDownAfterClass() { Registry.newRegistry(); @@ -76,8 +75,7 @@ public class TestPolicyStatusProvider extends ProviderSuper { super.setUp(); - prov = new PolicyStatusProvider(); - prov.initialize(); + prov = new PolicyStatusProvider(policyStatusService); } @Test @@ -242,7 +240,7 @@ public class TestPolicyStatusProvider extends ProviderSuper { builder.deploy(true); // @formatter:off - when(dao.getAllPolicyStatus()).thenReturn(List.of( + when(policyStatusService.getAllPolicyStatus()).thenReturn(List.of( builder.policy(POLICY_A).pdpId(PDP_A).build(), builder.policy(POLICY_A).pdpId(PDP_B).build(), notDeployed, @@ -264,7 +262,7 @@ public class TestPolicyStatusProvider extends ProviderSuper { ToscaConceptIdentifierOptVersion optIdent = new ToscaConceptIdentifierOptVersion(POLICY_A); // @formatter:off - when(dao.getAllPolicyStatus(optIdent)).thenReturn(List.of( + when(policyStatusService.getAllPolicyStatus(optIdent)).thenReturn(List.of( builder.policy(POLICY_A).pdpId(PDP_A).build(), notDeployed, builder.policy(POLICY_A).pdpId(PDP_C).build() diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java index 5046181c..434863b5 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java @@ -4,7 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,7 +71,6 @@ public class TestProviderBase extends ProviderSuper { private MyProvider prov; - @AfterClass public static void tearDownAfterClass() { Registry.newRegistry(); @@ -85,20 +84,16 @@ public class TestProviderBase extends ProviderSuper { @Override @Before public void setUp() throws Exception { - super.setUp(); - - when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json")); - prov = new MyProvider(); - prov.initialize(); + super.initialize(prov); + when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json")); } @Test public void testProviderBase() { assertSame(lockit, Whitebox.getInternalState(prov, "updateLock")); assertSame(reqmap, Whitebox.getInternalState(prov, "requestMap")); - assertSame(daofact, Whitebox.getInternalState(prov, "daoFactory")); } @Test @@ -112,18 +107,10 @@ public class TestProviderBase extends ProviderSuper { checkEmptyNotification(); } - @Test - public void testProcess_CreateEx() throws Exception { - PfModelException ex = new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION); - when(daofact.create()).thenThrow(ex); - - assertThatThrownBy(() -> prov.process(loadEmptyRequest(), this::handle)).isSameAs(ex); - } - @Test public void testProcess_PfRtEx() throws Exception { PfModelRuntimeException ex = new PfModelRuntimeException(Status.BAD_REQUEST, EXPECTED_EXCEPTION); - when(daofact.create()).thenThrow(ex); + when(pdpGroupService.updatePdpGroups(any())).thenThrow(ex); assertThatThrownBy(() -> prov.process(loadEmptyRequest(), this::handle)).isSameAs(ex); } @@ -131,7 +118,7 @@ public class TestProviderBase extends ProviderSuper { @Test public void testProcess_RuntimeEx() throws Exception { RuntimeException ex = new RuntimeException(EXPECTED_EXCEPTION); - when(daofact.create()).thenThrow(ex); + when(pdpGroupService.updatePdpGroups(any())).thenThrow(ex); assertThatThrownBy(() -> prov.process(loadEmptyRequest(), this::handle)).isInstanceOf(PfModelException.class) .hasMessage("request failed").hasCause(ex); @@ -139,19 +126,20 @@ public class TestProviderBase extends ProviderSuper { @Test public void testProcessPolicy_NoGroups() throws Exception { - when(dao.getFilteredPdpGroups(any())).thenReturn(Collections.emptyList()); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Collections.emptyList()); - SessionData session = new SessionData(dao, DEFAULT_USER); + SessionData session = + new SessionData(DEFAULT_USER, toscaService, pdpGroupService, policyStatusService, policyAuditService); ToscaConceptIdentifierOptVersion ident = new ToscaConceptIdentifierOptVersion(POLICY1_NAME, POLICY1_VERSION); assertThatThrownBy(() -> prov.processPolicy(session, ident)).isInstanceOf(PfModelException.class) - .hasMessage("policy not supported by any PDP group: policyA 1.2.3"); + .hasMessage("policy not supported by any PDP group: policyA 1.2.3"); } @Test public void testGetPolicy() throws Exception { PfModelException exc = new PfModelException(Status.CONFLICT, EXPECTED_EXCEPTION); - when(dao.getFilteredPolicyList(any())).thenThrow(exc); + when(toscaService.getFilteredPolicyList(any())).thenThrow(exc); ToscaConceptIdentifierOptVersion req = loadRequest(); assertThatThrownBy(() -> prov.process(req, this::handle)).isInstanceOf(PfModelRuntimeException.class) @@ -160,7 +148,7 @@ public class TestProviderBase extends ProviderSuper { @Test public void testGetPolicy_NotFound() throws Exception { - when(dao.getFilteredPolicyList(any())).thenReturn(Collections.emptyList()); + when(toscaService.getFilteredPolicyList(any())).thenReturn(Collections.emptyList()); ToscaConceptIdentifierOptVersion req = loadRequest(); assertThatThrownBy(() -> prov.process(req, this::handle)).isInstanceOf(PfModelRuntimeException.class) @@ -171,7 +159,7 @@ public class TestProviderBase extends ProviderSuper { @Test public void testGetGroup() throws Exception { - when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("getGroupDao.json")) + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(loadGroups("getGroupDao.json")) .thenReturn(loadGroups("groups.json")); prov.process(loadRequest(), this::handle); @@ -193,7 +181,7 @@ public class TestProviderBase extends ProviderSuper { * Last subgroup matches. */ - when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroupDao.json")); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroupDao.json")); prov.clear(); prov.add(false, true, false, true); @@ -225,7 +213,7 @@ public class TestProviderBase extends ProviderSuper { * Should generate updates to pdp1, pdp2, and pdp3. */ - when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json")) + when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json")) .thenReturn(loadPolicies("upgradeGroupPolicy2.json")) .thenReturn(loadPolicies("upgradeGroupPolicy3.json")) .thenReturn(loadPolicies("upgradeGroupPolicy4.json")); @@ -238,7 +226,7 @@ public class TestProviderBase extends ProviderSuper { * request */ // @formatter:off - when(dao.getFilteredPdpGroups(any())) + when(pdpGroupService.getFilteredPdpGroups(any())) .thenReturn(groups1).thenReturn(groups1) .thenReturn(groups2).thenReturn(groups2) .thenReturn(groups1).thenReturn(groups1) @@ -272,8 +260,8 @@ public class TestProviderBase extends ProviderSuper { prov.process(loadRequest(), this::handle); - verify(dao, never()).createPdpGroups(any()); - verify(dao, never()).updatePdpGroups(any()); + verify(pdpGroupService, never()).createPdpGroups(any()); + verify(pdpGroupService, never()).updatePdpGroups(any()); verify(reqmap, never()).addRequest(any(PdpUpdate.class)); } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestSessionData.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestSessionData.java index 952a861d..ec79c03a 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestSessionData.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestSessionData.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,13 +56,13 @@ import org.onap.policy.models.pap.concepts.PolicyNotification; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpStateChange; import org.onap.policy.models.pdp.concepts.PdpUpdate; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierOptVersion; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType; import org.onap.policy.models.tosca.authorative.concepts.ToscaTypedEntityFilter; import org.onap.policy.pap.main.notification.DeploymentStatus; +import org.onap.policy.pap.main.service.PolicyStatusService; public class TestSessionData extends ProviderSuper { private static final String GROUP_NAME = "groupA"; @@ -99,13 +100,13 @@ public class TestSessionData extends ProviderSuper { group1 = loadGroup("group1.json"); group2 = loadGroup("group2.json"); - session = new SessionData(dao, DEFAULT_USER); + session = new SessionData(DEFAULT_USER, toscaService, pdpGroupService, policyStatusService, policyAuditService); } @Test public void testGetPolicyType() throws Exception { ToscaPolicyType policy1 = makePolicyType(POLICY_TYPE, POLICY_TYPE_VERSION); - when(dao.getPolicyTypeList(POLICY_TYPE, POLICY_TYPE_VERSION)).thenReturn(Arrays.asList(policy1)); + when(toscaService.getPolicyTypeList(POLICY_TYPE, POLICY_TYPE_VERSION)).thenReturn(Arrays.asList(policy1)); assertSame(policy1, session.getPolicyType(type)); @@ -115,7 +116,7 @@ public class TestSessionData extends ProviderSuper { @Test public void testGetPolicyType_NotFound() throws Exception { - when(dao.getPolicyTypeList(any(), any())).thenReturn(Collections.emptyList()); + when(toscaService.getPolicyTypeList(any(), any())).thenReturn(Collections.emptyList()); assertNull(session.getPolicyType(type)); } @@ -123,7 +124,7 @@ public class TestSessionData extends ProviderSuper { @Test public void testGetPolicyType_DaoEx() throws Exception { PfModelException ex = new PfModelException(Status.INTERNAL_SERVER_ERROR, EXPECTED_EXCEPTION); - when(dao.getPolicyTypeList(POLICY_TYPE, POLICY_TYPE_VERSION)).thenThrow(ex); + when(toscaService.getPolicyTypeList(POLICY_TYPE, POLICY_TYPE_VERSION)).thenThrow(ex); assertThatThrownBy(() -> session.getPolicyType(type)).isSameAs(ex); } @@ -131,7 +132,7 @@ public class TestSessionData extends ProviderSuper { @Test public void testGetPolicy_NullVersion() throws Exception { ToscaPolicy policy1 = makePolicy(POLICY_NAME, POLICY_VERSION); - when(dao.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1)); + when(toscaService.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1)); ident.setVersion(null); assertSame(policy1, session.getPolicy(ident)); @@ -143,13 +144,13 @@ public class TestSessionData extends ProviderSuper { // retrieve a second time using full version - should use cache assertSame(policy1, session.getPolicy(new ToscaConceptIdentifierOptVersion(policy1.getIdentifier()))); - verify(dao).getFilteredPolicyList(any()); + verify(toscaService).getFilteredPolicyList(any()); } @Test public void testGetPolicy_MajorVersion() throws Exception { ToscaPolicy policy1 = makePolicy(POLICY_NAME, POLICY_VERSION); - when(dao.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1)); + when(toscaService.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1)); ident.setVersion("1"); assertSame(policy1, session.getPolicy(ident)); @@ -161,13 +162,13 @@ public class TestSessionData extends ProviderSuper { // retrieve a second time using full version - should use cache assertSame(policy1, session.getPolicy(new ToscaConceptIdentifierOptVersion(policy1.getIdentifier()))); - verify(dao).getFilteredPolicyList(any()); + verify(toscaService).getFilteredPolicyList(any()); } @Test public void testGetPolicy_MajorMinorVersion() throws Exception { ToscaPolicy policy1 = makePolicy(POLICY_NAME, POLICY_VERSION); - when(dao.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1)); + when(toscaService.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1)); ident.setVersion(POLICY_VERSION); assertSame(policy1, session.getPolicy(ident)); @@ -179,12 +180,12 @@ public class TestSessionData extends ProviderSuper { // retrieve a second time using full version - should use cache assertSame(policy1, session.getPolicy(new ToscaConceptIdentifierOptVersion(policy1.getIdentifier()))); - verify(dao).getFilteredPolicyList(any()); + verify(toscaService).getFilteredPolicyList(any()); } @Test public void testGetPolicy_NotFound() throws Exception { - when(dao.getFilteredPolicyList(any())).thenReturn(Collections.emptyList()); + when(toscaService.getFilteredPolicyList(any())).thenReturn(Collections.emptyList()); assertNull(session.getPolicy(ident)); } @@ -192,7 +193,7 @@ public class TestSessionData extends ProviderSuper { @Test public void testGetPolicy_DaoEx() throws Exception { PfModelException ex = new PfModelException(Status.INTERNAL_SERVER_ERROR, EXPECTED_EXCEPTION); - when(dao.getFilteredPolicyList(any())).thenThrow(ex); + when(toscaService.getFilteredPolicyList(any())).thenThrow(ex); assertThatThrownBy(() -> session.getPolicy(ident)).isSameAs(ex); } @@ -364,13 +365,13 @@ public class TestSessionData extends ProviderSuper { assertTrue(session.isUnchanged()); // force the groups into the cache - when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1, group2)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1, group2)); session.getActivePdpGroupsByPolicyType(type); /* * try group 1 */ - when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1)); PdpGroup newgrp = new PdpGroup(group1); session.update(newgrp); assertFalse(session.isUnchanged()); @@ -383,7 +384,7 @@ public class TestSessionData extends ProviderSuper { /* * try group 2 */ - when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group2)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group2)); newgrp = new PdpGroup(group2); session.update(newgrp); assertFalse(session.isUnchanged()); @@ -396,7 +397,7 @@ public class TestSessionData extends ProviderSuper { @Test public void testUpdate_NotInCache() throws Exception { - when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1)); assertThatIllegalStateException().isThrownBy(() -> session.update(new PdpGroup(group1))) .withMessage("group not cached: groupA"); @@ -404,49 +405,41 @@ public class TestSessionData extends ProviderSuper { @Test public void testGetGroup() throws Exception { - when(dao.getPdpGroups(GROUP_NAME)).thenReturn(Arrays.asList(group1)); + when(pdpGroupService.getPdpGroups(GROUP_NAME)).thenReturn(Arrays.asList(group1)); assertSame(group1, session.getGroup(GROUP_NAME)); - verify(dao).getPdpGroups(any()); + verify(pdpGroupService).getPdpGroups(any(String.class)); // repeat assertSame(group1, session.getGroup(GROUP_NAME)); // should not access dao again - verify(dao, times(1)).getPdpGroups(any()); + verify(pdpGroupService, times(1)).getPdpGroups(any(String.class)); } @Test public void testGetGroup_NotFound() throws Exception { - when(dao.getPdpGroups(GROUP_NAME)).thenReturn(Collections.emptyList()); + when(pdpGroupService.getPdpGroups(GROUP_NAME)).thenReturn(Collections.emptyList()); assertNull(session.getGroup(GROUP_NAME)); - verify(dao).getPdpGroups(any()); + verify(pdpGroupService).getPdpGroups(any(String.class)); // repeat assertNull(session.getGroup(GROUP_NAME)); // SHOULD access dao again - verify(dao, times(2)).getPdpGroups(GROUP_NAME); + verify(pdpGroupService, times(2)).getPdpGroups(GROUP_NAME); // find it this time - when(dao.getPdpGroups(GROUP_NAME)).thenReturn(Arrays.asList(group1)); + when(pdpGroupService.getPdpGroups(GROUP_NAME)).thenReturn(Arrays.asList(group1)); assertSame(group1, session.getGroup(GROUP_NAME)); - verify(dao, times(3)).getPdpGroups(GROUP_NAME); - } - - @Test - public void testGetGroup_DaoEx() throws Exception { - PfModelException ex = new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION); - when(dao.getPdpGroups(GROUP_NAME)).thenThrow(ex); - - assertThatThrownBy(() -> session.getGroup(GROUP_NAME)).isSameAs(ex); + verify(pdpGroupService, times(3)).getPdpGroups(GROUP_NAME); } @Test public void testGetActivePdpGroupsByPolicyType() throws Exception { List groups = Arrays.asList(group1, group2); - when(dao.getFilteredPdpGroups(any())).thenReturn(groups); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(groups); // repeat assertEquals(groups, session.getActivePdpGroupsByPolicyType(type)); @@ -454,32 +447,32 @@ public class TestSessionData extends ProviderSuper { assertEquals(groups, session.getActivePdpGroupsByPolicyType(type)); // only invoked once - should have used the cache for the rest - verify(dao, times(1)).getFilteredPdpGroups(any()); + verify(pdpGroupService, times(1)).getFilteredPdpGroups(any()); } @Test public void testAddGroup() throws Exception { List groups = Arrays.asList(group1, group2); - when(dao.getFilteredPdpGroups(any())).thenReturn(groups); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(groups); // query by each type assertEquals(groups, session.getActivePdpGroupsByPolicyType(type)); assertEquals(groups, session.getActivePdpGroupsByPolicyType(type2)); // invoked once for each type - verify(dao, times(2)).getFilteredPdpGroups(any()); + verify(pdpGroupService, times(2)).getFilteredPdpGroups(any()); // repeat - should be no more invocations assertEquals(groups, session.getActivePdpGroupsByPolicyType(type)); assertEquals(groups, session.getActivePdpGroupsByPolicyType(type2)); - verify(dao, times(2)).getFilteredPdpGroups(any()); + verify(pdpGroupService, times(2)).getFilteredPdpGroups(any()); } @Test public void testUpdateDb() throws Exception { // force the groups into the cache PdpGroup group3 = loadGroup("group3.json"); - when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1, group2, group3)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1, group2, group3)); session.getActivePdpGroupsByPolicyType(type); // create groups 4 & 5 @@ -490,7 +483,7 @@ public class TestSessionData extends ProviderSuper { session.create(group5); // update group 1 - when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1)); PdpGroup newgrp1 = new PdpGroup(group1); session.update(newgrp1); @@ -499,12 +492,12 @@ public class TestSessionData extends ProviderSuper { session.update(newgrp1); // update group 3 - when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group3)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group3)); PdpGroup newgrp3 = new PdpGroup(group3); session.update(newgrp3); // update group 5 - when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group5)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group5)); PdpGroup newgrp5 = new PdpGroup(group5); session.update(newgrp5); @@ -529,22 +522,22 @@ public class TestSessionData extends ProviderSuper { @Test public void testUpdateDb_Empty() throws Exception { // force data into the cache - when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1, group2)); + when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group1, group2)); session.getActivePdpGroupsByPolicyType(type); PolicyNotification notif = new PolicyNotification(); session.updateDb(notif); assertThat(notif.getAdded()).isEmpty(); - verify(dao, never()).createPdpGroups(any()); - verify(dao, never()).updatePdpGroups(any()); + verify(pdpGroupService, never()).createPdpGroups(any()); + verify(pdpGroupService, never()).updatePdpGroups(any()); } @Test public void testDeleteGroupFromDb() throws Exception { session.deleteGroupFromDb(group1); - verify(dao).deletePdpGroup(group1.getName()); + verify(pdpGroupService).deletePdpGroup(group1.getName()); } @Test @@ -561,18 +554,19 @@ public class TestSessionData extends ProviderSuper { DeploymentStatus status = mock(DeploymentStatus.class); - session = new SessionData(dao, DEFAULT_USER) { - @Override - protected DeploymentStatus makeDeploymentStatus(PolicyModelsProvider dao) { - return status; - } - }; + session = + new SessionData(DEFAULT_USER, toscaService, pdpGroupService, policyStatusService, policyAuditService) { + @Override + protected DeploymentStatus makeDeploymentStatus(PolicyStatusService policyStatusService) { + return status; + } + }; ToscaPolicy policy = makePolicy(POLICY_NAME, POLICY_VERSION); policy.setType(POLICY_TYPE); policy.setTypeVersion(POLICY_TYPE_VERSION); - when(dao.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy)); + when(toscaService.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy)); ToscaConceptIdentifier policyId = new ToscaConceptIdentifier(POLICY_NAME, POLICY_VERSION); List pdps = Arrays.asList(PDP1, PDP2); @@ -617,7 +611,7 @@ public class TestSessionData extends ProviderSuper { @SuppressWarnings("unchecked") ArgumentCaptor> captor = ArgumentCaptor.forClass(ToscaTypedEntityFilter.class); - verify(dao).getFilteredPolicyList(captor.capture()); + verify(toscaService).getFilteredPolicyList(captor.capture()); return captor.getValue(); } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndBase.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndBase.java index e51aa776..9c9f36ad 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndBase.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndBase.java @@ -4,7 +4,7 @@ * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2019-2020 Nordix Foundation. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,28 +27,32 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.List; +import java.util.Map; +import java.util.Optional; import org.junit.After; -import org.junit.AfterClass; -import org.junit.BeforeClass; import org.onap.policy.common.parameters.ValidationResult; 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.common.utils.resources.ResourceUtils; +import org.onap.policy.models.base.PfConceptKey; import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.pdp.concepts.PdpGroup; import org.onap.policy.models.pdp.concepts.PdpGroups; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus; import org.onap.policy.models.pdp.concepts.PdpStatistics; -import org.onap.policy.models.pdp.persistence.provider.PdpFilterParameters; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; +import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate; import org.onap.policy.pap.main.PolicyPapRuntimeException; -import org.onap.policy.pap.main.parameters.PapParameterGroup; +import org.onap.policy.pap.main.repository.ToscaServiceTemplateRepository; import org.onap.policy.pap.main.rest.CommonPapRestServer; +import org.onap.policy.pap.main.service.PdpGroupService; +import org.onap.policy.pap.main.service.PdpStatisticsService; +import org.onap.policy.pap.main.service.PolicyStatusService; +import org.onap.policy.pap.main.service.ToscaServiceTemplateService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.yaml.snakeyaml.Yaml; public abstract class End2EndBase extends CommonPapRestServer { @@ -57,54 +61,25 @@ public abstract class End2EndBase extends CommonPapRestServer { private static final Coder coder = new StandardCoder(); private static final Yaml yaml = new Yaml(); - /** - * DB connection. This is kept open until {@link #stop()} is invoked so that the in-memory DB is not destroyed. - */ - private static PolicyModelsProvider dbConn; - - /** - * DAO provider factory. - */ - private static PolicyModelsProviderFactoryWrapper daoFactory; - /** * Context - should be initialized by setUp() method. */ protected End2EndContext context = null; + @Autowired + public PdpGroupService pdpGroupService; - /** - * Starts Main and connects to the DB. - * - * @throws Exception if an error occurs - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - CommonPapRestServer.setUpBeforeClass(); - - final PapParameterGroup params = new StandardCoder().decode(new File(CONFIG_FILE), PapParameterGroup.class); - daoFactory = new PolicyModelsProviderFactoryWrapper(params.getDatabaseProviderParameters()); - dbConn = daoFactory.create(); - } + @Autowired + public PdpStatisticsService pdpStatisticsService; - /** - * Tears down. - */ - @AfterClass - public static void tearDownAfterClass() { - try { - dbConn.close(); - } catch (final PfModelException e) { - logger.warn("failed to close the DB", e); - } + @Autowired + private ToscaServiceTemplateRepository serviceTemplateRepository; - try { - daoFactory.close(); - } catch (final Exception e) { - logger.warn("failed to close DAO factory", e); - } + @Autowired + public PolicyStatusService policyStatusService; - } + @Autowired + public ToscaServiceTemplateService toscaService; /** * Tears down. @@ -130,9 +105,10 @@ public abstract class End2EndBase extends CommonPapRestServer { * @param yamlFile name of the YAML file specifying the data to be loaded * @throws PfModelException if a DAO error occurs */ - public static void addToscaPolicyTypes(final String yamlFile) throws PfModelException { + public void addToscaPolicyTypes(final String yamlFile) throws PfModelException { final ToscaServiceTemplate serviceTemplate = loadYamlFile(yamlFile, ToscaServiceTemplate.class); - dbConn.createPolicyTypes(serviceTemplate); + JpaToscaServiceTemplate jpaToscaServiceTemplate = mergeWithExistingTemplate(serviceTemplate); + serviceTemplateRepository.save(jpaToscaServiceTemplate); } /** @@ -141,9 +117,30 @@ public abstract class End2EndBase extends CommonPapRestServer { * @param yamlFile name of the YAML file specifying the data to be loaded * @throws PfModelException if a DAO error occurs */ - public static void addToscaPolicies(final String yamlFile) throws PfModelException { + public void addToscaPolicies(final String yamlFile) throws PfModelException { final ToscaServiceTemplate serviceTemplate = loadYamlFile(yamlFile, ToscaServiceTemplate.class); - dbConn.createPolicies(serviceTemplate); + JpaToscaServiceTemplate jpaToscaServiceTemplate = mergeWithExistingTemplate(serviceTemplate); + serviceTemplateRepository.save(jpaToscaServiceTemplate); + } + + private JpaToscaServiceTemplate mergeWithExistingTemplate(ToscaServiceTemplate serviceTemplate) { + JpaToscaServiceTemplate jpaToscaServiceTemplate = new JpaToscaServiceTemplate(serviceTemplate); + Optional dbServiceTemplateOpt = serviceTemplateRepository + .findById(new PfConceptKey(JpaToscaServiceTemplate.DEFAULT_NAME, JpaToscaServiceTemplate.DEFAULT_VERSION)); + if (!dbServiceTemplateOpt.isEmpty()) { + JpaToscaServiceTemplate dbServiceTemplate = dbServiceTemplateOpt.get(); + if (dbServiceTemplate.getPolicyTypes() != null) { + jpaToscaServiceTemplate.setPolicyTypes(dbServiceTemplate.getPolicyTypes()); + } + if (dbServiceTemplate.getDataTypes() != null) { + jpaToscaServiceTemplate.setDataTypes(dbServiceTemplate.getDataTypes()); + } + if (dbServiceTemplate.getTopologyTemplate() != null) { + jpaToscaServiceTemplate.setTopologyTemplate(dbServiceTemplate.getTopologyTemplate()); + } + } + + return jpaToscaServiceTemplate; } /** @@ -152,7 +149,7 @@ public abstract class End2EndBase extends CommonPapRestServer { * @param jsonFile name of the JSON file specifying the data to be loaded * @throws PfModelException if a DAO error occurs */ - public static void addGroups(final String jsonFile) throws PfModelException { + public void addGroups(final String jsonFile) throws PfModelException { final PdpGroups groups = loadJsonFile(jsonFile, PdpGroups.class); final ValidationResult result = groups.validatePapRest(); @@ -160,7 +157,7 @@ public abstract class End2EndBase extends CommonPapRestServer { throw new PolicyPapRuntimeException("cannot init DB groups from " + jsonFile + ":\n" + result.getResult()); } - dbConn.createPdpGroups(groups.getGroups()); + pdpGroupService.createPdpGroups(groups.getGroups()); } /** @@ -169,8 +166,8 @@ public abstract class End2EndBase extends CommonPapRestServer { * @param name name of the pdpGroup * @throws PfModelException if a DAO error occurs */ - public static List fetchGroups(final String name) throws PfModelException { - return dbConn.getPdpGroups(name); + public List fetchGroups(final String name) throws PfModelException { + return pdpGroupService.getPdpGroups(name); } /** @@ -181,10 +178,9 @@ public abstract class End2EndBase extends CommonPapRestServer { * @param subGroupName name of the pdpSubGroup * @throws PfModelException if a DAO error occurs */ - public static List fetchPdpStatistics(final String instanceId, final String groupName, - final String subGroupName) throws PfModelException { - return dbConn.getFilteredPdpStatistics( - PdpFilterParameters.builder().name(instanceId).group(groupName).subGroup(subGroupName).build()); + public Map>> fetchPdpStatistics(final String instanceId, + final String groupName, final String subGroupName) throws PfModelException { + return pdpStatisticsService.fetchDatabaseStatistics(groupName, subGroupName, instanceId, 100, null, null); } /** @@ -193,9 +189,9 @@ public abstract class End2EndBase extends CommonPapRestServer { * @param jsonFile name of the JSON file specifying the data to be loaded * @throws PfModelException if a DAO error occurs */ - public static void addPdpPolicyStatus(final String jsonFile) throws PfModelException { + public void addPdpPolicyStatus(final String jsonFile) throws PfModelException { final PolicyStatusRecords data = loadJsonFile(jsonFile, PolicyStatusRecords.class); - dbConn.cudPolicyStatus(data.records, null, null); + policyStatusService.cudPolicyStatus(data.records, null, null); } /** diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupCreateOrUpdateTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupCreateOrUpdateTest.java index dacee672..3f763863 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupCreateOrUpdateTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupCreateOrUpdateTest.java @@ -3,6 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,7 +32,6 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.junit.After; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.models.pap.concepts.PdpGroupUpdateResponse; import org.onap.policy.models.pdp.concepts.PdpGroup; @@ -48,24 +48,13 @@ public class PdpGroupCreateOrUpdateTest extends End2EndBase { private static final String CREATE_SUBGROUP = "pdpTypeA"; private static final String GROUP_ENDPOINT = "pdps"; - /** - * Starts Main and adds policies to the DB. - * - * @throws Exception if an error occurs - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - End2EndBase.setUpBeforeClass(); - - addToscaPolicyTypes("monitoring.policy-type.yaml"); - } - /** * Sets up. */ @Override @Before public void setUp() throws Exception { + addToscaPolicyTypes("monitoring.policy-type.yaml"); super.setUp(); context = new End2EndContext(); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeleteTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeleteTest.java index 9b80bb7e..e3ad0044 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeleteTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeleteTest.java @@ -4,7 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,7 +33,6 @@ import java.util.concurrent.TimeUnit; import javax.ws.rs.client.Invocation; import javax.ws.rs.core.Response; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.common.endpoints.event.comm.bus.NoopTopicFactories; import org.onap.policy.common.endpoints.event.comm.bus.NoopTopicSink; @@ -51,25 +50,14 @@ public class PdpGroupDeleteTest extends End2EndBase { private static final String DELETE_GROUP_ENDPOINT = "pdps/groups"; private static final String DELETE_POLICIES_ENDPOINT = "pdps/policies"; - /** - * Starts Main and adds policies to the DB. - * - * @throws Exception if an error occurs - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - End2EndBase.setUpBeforeClass(); - - addToscaPolicyTypes("monitoring.policy-type.yaml"); - addToscaPolicies("monitoring.policy.yaml"); - } - /** * Sets up. */ @Override @Before public void setUp() throws Exception { + addToscaPolicyTypes("monitoring.policy-type.yaml"); + addToscaPolicies("monitoring.policy.yaml"); super.setUp(); context = new End2EndContext(); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeployTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeployTest.java index 08974ed8..cdb1fa9d 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeployTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeployTest.java @@ -4,7 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,6 @@ import javax.ws.rs.client.Invocation; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.common.endpoints.event.comm.bus.NoopTopicFactories; import org.onap.policy.common.endpoints.event.comm.bus.NoopTopicSink; @@ -58,25 +57,14 @@ public class PdpGroupDeployTest extends End2EndBase { private static final String DEPLOY_POLICIES_ENDPOINT = "pdps/policies"; private static final String DEPLOY_SUBGROUP = "pdpTypeA"; - /** - * Starts Main and adds policies to the DB. - * - * @throws Exception if an error occurs - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - End2EndBase.setUpBeforeClass(); - - addToscaPolicyTypes("monitoring.policy-type.yaml"); - addToscaPolicies("monitoring.policy.yaml"); - } - /** * Sets up. */ @Override @Before public void setUp() throws Exception { + addToscaPolicyTypes("monitoring.policy-type.yaml"); + addToscaPolicies("monitoring.policy.yaml"); super.setUp(); context = new End2EndContext(); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupQueryTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupQueryTest.java index a0a40ce5..d6472ce1 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupQueryTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupQueryTest.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,7 +33,7 @@ import java.util.function.Predicate; import java.util.stream.Collectors; import javax.ws.rs.client.Invocation; import javax.ws.rs.core.Response; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; import org.onap.policy.models.pdp.concepts.Pdp; import org.onap.policy.models.pdp.concepts.PdpGroup; @@ -46,18 +47,19 @@ public class PdpGroupQueryTest extends End2EndBase { private static final String GROUP_ENDPOINT = "pdps"; /** - * Starts Main and adds policies to the DB. + * Sets up. * - * @throws Exception if an error occurs + * @throws Exception the exception */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - End2EndBase.setUpBeforeClass(); + @Override + @Before + public void setUp() throws Exception { addToscaPolicyTypes("monitoring.policy-type.yaml"); addToscaPolicies("monitoring.policy.yaml"); addGroups("queryGroup.json"); + super.setUp(); } @Test diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupStateChangeTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupStateChangeTest.java index df7fcc01..2fa7cfb4 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupStateChangeTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupStateChangeTest.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +31,6 @@ import javax.ws.rs.client.Entity; import javax.ws.rs.client.Invocation; import javax.ws.rs.core.Response; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.models.pap.concepts.PdpGroupStateChangeResponse; import org.onap.policy.models.pdp.concepts.PdpStatus; @@ -46,25 +46,14 @@ public class PdpGroupStateChangeTest extends End2EndBase { private static final String DEACT_GROUP = "stateChangeGroupDeactivate"; private static final String GROUP_ENDPOINT = "pdps/groups"; - /** - * Starts Main and adds policies to the DB. - * - * @throws Exception if an error occurs - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - End2EndBase.setUpBeforeClass(); - - addToscaPolicyTypes("monitoring.policy-type.yaml"); - addToscaPolicies("monitoring.policy.yaml"); - } - /** * Sets up. */ @Override @Before public void setUp() throws Exception { + addToscaPolicyTypes("monitoring.policy-type.yaml"); + addToscaPolicies("monitoring.policy.yaml"); super.setUp(); context = new End2EndContext(); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyAuditTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyAuditTest.java index d98a4ba3..b0a135d2 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyAuditTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyAuditTest.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2021 Bell Canada. All rights reserved. + * Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,18 +26,17 @@ import java.util.List; import javax.ws.rs.client.Invocation; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.Response; +import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.onap.policy.common.utils.services.Registry; -import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pap.concepts.PolicyAudit; import org.onap.policy.models.pap.concepts.PolicyAudit.AuditAction; -import org.onap.policy.models.provider.PolicyModelsProvider; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; -import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper; +import org.onap.policy.pap.main.repository.PolicyAuditRepository; import org.onap.policy.pap.main.rest.PolicyAuditControllerV1; +import org.onap.policy.pap.main.service.PolicyAuditService; +import org.springframework.beans.factory.annotation.Autowired; public class PolicyAuditTest extends End2EndBase { private static final String TEST_GROUP = "testGroup"; @@ -54,6 +53,12 @@ public class PolicyAuditTest extends End2EndBase { private static int BAD_REQUEST_STATUS_CODE = 400; private static final String BAD_REQUEST_MSG = "NumberFormatException For"; + @Autowired + private PolicyAuditService policyAuditService; + + @Autowired + private PolicyAuditRepository policyAuditRepository; + @Override @Before public void setUp() throws Exception { @@ -61,23 +66,31 @@ public class PolicyAuditTest extends End2EndBase { setupEnv(); } + /** + * Teardown after tests. + */ + @Override + @After + public void tearDown() { + policyAuditRepository.deleteAll(); + super.tearDown(); + } + private void setupEnv() { List recordList = new ArrayList<>(); Instant auditRecordTime = Instant.ofEpochSecond(1627392315L); - PolicyModelsProviderFactoryWrapper modelProviderWrapper = - Registry.get(PapConstants.REG_PAP_DAO_FACTORY, PolicyModelsProviderFactoryWrapper.class); - try (PolicyModelsProvider databaseProvider = modelProviderWrapper.create()) { - PolicyAudit audit1 = PolicyAudit.builder().auditId(123L).pdpGroup(TEST_GROUP).pdpType(TEST_PDP_TYPE) + try { + PolicyAudit audit1 = PolicyAudit.builder().pdpGroup(TEST_GROUP).pdpType(TEST_PDP_TYPE) .policy(POLICY_A).action(AuditAction.DEPLOYMENT) .timestamp(auditRecordTime).user(DEFAULT_USER).build(); - PolicyAudit audit2 = PolicyAudit.builder().auditId(456L).pdpGroup(TEST_GROUP).pdpType(TEST_PDP_TYPE) + PolicyAudit audit2 = PolicyAudit.builder().pdpGroup(TEST_GROUP).pdpType(TEST_PDP_TYPE) .policy(POLICY_B).action(AuditAction.UNDEPLOYMENT) .timestamp(auditRecordTime).user(DEFAULT_USER).build(); recordList.add(audit1); recordList.add(audit2); - databaseProvider.createAuditRecords(recordList); - } catch (final PfModelException exp) { + policyAuditService.createAuditRecords(recordList); + } catch (Exception exp) { throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, exp.getMessage()); } } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyStatusTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyStatusTest.java index b44d4af7..121318f5 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyStatusTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PolicyStatusTest.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,7 @@ import java.util.List; import javax.ws.rs.client.Invocation; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.Response; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; import org.onap.policy.models.pap.concepts.PolicyStatus; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus; @@ -41,15 +41,11 @@ public class PolicyStatusTest extends End2EndBase { private static final String POLICY_STATUS_ENDPOINT = "policies/deployed"; private static final String POLICY_DEPLOYMENT_STATUS_ENDPOINT = "policies/status"; - /** - * Starts Main and adds policies to the DB. - * - * @throws Exception if an error occurs - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception { - End2EndBase.setUpBeforeClass(); + @Override + @Before + public void setUp() throws Exception { addPdpPolicyStatus("policyStatus.json"); + super.setUp(); } @Test diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/StatisticsTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/StatisticsTest.java index 1331e458..876ea0fb 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/StatisticsTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/StatisticsTest.java @@ -4,7 +4,7 @@ * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2020-2021 Nordix Foundation. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,17 +32,12 @@ import java.util.Map; import javax.ws.rs.client.Invocation; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.Response; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.common.utils.services.Registry; -import org.onap.policy.models.base.PfModelException; -import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pdp.concepts.PdpStatistics; -import org.onap.policy.models.provider.PolicyModelsProvider; -import org.onap.policy.models.provider.PolicyModelsProviderFactory; import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.parameters.CommonTestData; -import org.onap.policy.pap.main.parameters.PapParameterGroup; import org.onap.policy.pap.main.rest.PapStatisticsManager; import org.onap.policy.pap.main.rest.StatisticsReport; @@ -52,6 +47,7 @@ public class StatisticsTest extends End2EndBase { private static final String START_TIME_NAME = "startTime"; private static final long TIMESTAMP_SEC = 1562494272; + private static PdpStatistics pdpStatisticsRecord; /** * Adds a record to the DB. @@ -60,25 +56,24 @@ public class StatisticsTest extends End2EndBase { public static void setUpBeforeClass() throws Exception { End2EndBase.setUpBeforeClass(); - PolicyModelsProviderFactory modelProviderWrapper = new PolicyModelsProviderFactory(); - PapParameterGroup parameterGroup = new CommonTestData().getPapParameterGroup(6969); - try (PolicyModelsProvider databaseProvider = - modelProviderWrapper.createPolicyModelsProvider(parameterGroup.getDatabaseProviderParameters())) { - PdpStatistics pdpStatisticsRecord = new PdpStatistics(); - pdpStatisticsRecord.setPdpGroupName("defaultGroup"); - pdpStatisticsRecord.setPdpSubGroupName("apex"); - pdpStatisticsRecord.setPdpInstanceId("pdp1"); - pdpStatisticsRecord.setTimeStamp(Instant.ofEpochSecond(TIMESTAMP_SEC)); - pdpStatisticsRecord.setPolicyDeployCount(1); - pdpStatisticsRecord.setPolicyDeployFailCount(0); - pdpStatisticsRecord.setPolicyDeploySuccessCount(1); - pdpStatisticsRecord.setPolicyExecutedCount(1); - pdpStatisticsRecord.setPolicyExecutedFailCount(0); - pdpStatisticsRecord.setPolicyExecutedSuccessCount(1); - databaseProvider.createPdpStatistics(List.of(pdpStatisticsRecord)); - } catch (final PfModelException exp) { - throw new PfModelRuntimeException(Response.Status.BAD_REQUEST, exp.getMessage()); - } + pdpStatisticsRecord = new PdpStatistics(); + pdpStatisticsRecord.setPdpGroupName("defaultGroup"); + pdpStatisticsRecord.setPdpSubGroupName("apex"); + pdpStatisticsRecord.setPdpInstanceId("pdp1"); + pdpStatisticsRecord.setTimeStamp(Instant.ofEpochSecond(TIMESTAMP_SEC)); + pdpStatisticsRecord.setPolicyDeployCount(1); + pdpStatisticsRecord.setPolicyDeployFailCount(0); + pdpStatisticsRecord.setPolicyDeploySuccessCount(1); + pdpStatisticsRecord.setPolicyExecutedCount(1); + pdpStatisticsRecord.setPolicyExecutedFailCount(0); + pdpStatisticsRecord.setPolicyExecutedSuccessCount(1); + } + + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + pdpStatisticsService.createPdpStatistics(List.of(pdpStatisticsRecord)); } @Test diff --git a/main/src/test/java/org/onap/policy/pap/main/service/PdpGroupServiceTest.java b/main/src/test/java/org/onap/policy/pap/main/service/PdpGroupServiceTest.java index e7090fcf..549eb96b 100644 --- a/main/src/test/java/org/onap/policy/pap/main/service/PdpGroupServiceTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/service/PdpGroupServiceTest.java @@ -71,7 +71,7 @@ public class PdpGroupServiceTest extends CommonPapRestServer { public void setUp() throws Exception { super.setUp(); PdpGroups defaultGroup = coder.decode(ResourceUtils.getResourceAsString("e2e/PdpGroups.json"), PdpGroups.class); - pdpGroupService.savePdpGroups(defaultGroup.getGroups()); + pdpGroupService.createPdpGroups(defaultGroup.getGroups()); groupsToCreate = coder.decode(ResourceUtils.getResourceAsString("e2e/createGroups.json"), PdpGroups.class); } @@ -82,23 +82,23 @@ public class PdpGroupServiceTest extends CommonPapRestServer { assertThat(pdpGroups).hasSize(1); assertThat(pdpGroups.get(0).getName()).isEqualTo(DEFAULT_GROUP); - pdpGroupService.savePdpGroups(groupsToCreate.getGroups()); + pdpGroupService.createPdpGroups(groupsToCreate.getGroups()); assertThat(pdpGroupService.getPdpGroups()).hasSize(2); - pdpGroups = pdpGroupService.getPdpGroupByName(CREATE_GROUPS); + pdpGroups = pdpGroupService.getPdpGroups(CREATE_GROUPS); assertThat(pdpGroups).hasSize(1); assertThat(pdpGroups.get(0).getName()).isEqualTo(CREATE_GROUPS); - assertThat(pdpGroupService.getPdpGroupByState(PdpState.PASSIVE)).isEqualTo(pdpGroups); + assertThat(pdpGroupService.getPdpGroups(PdpState.PASSIVE)).isEqualTo(pdpGroups); - List activePdpGroups = pdpGroupService.getPdpGroupByState(PdpState.ACTIVE); + List activePdpGroups = pdpGroupService.getPdpGroups(PdpState.ACTIVE); assertThat(activePdpGroups).hasSize(1); assertThat(activePdpGroups.get(0).getPdpSubgroups()).hasSize(3); - assertThat(pdpGroupService.getPdpGroupByNameAndState(CREATE_GROUPS, PdpState.PASSIVE)).hasSize(1); - assertThat(pdpGroupService.getPdpGroupByNameAndState("invalid-group", PdpState.PASSIVE)).hasSize(0); - assertThat(pdpGroupService.getPdpGroupByNameAndState(DEFAULT_GROUP, PdpState.ACTIVE)).hasSize(1); + assertThat(pdpGroupService.getPdpGroups(CREATE_GROUPS, PdpState.PASSIVE)).hasSize(1); + assertThat(pdpGroupService.getPdpGroups("invalid-group", PdpState.PASSIVE)).hasSize(0); + assertThat(pdpGroupService.getPdpGroups(DEFAULT_GROUP, PdpState.ACTIVE)).hasSize(1); PdpGroupFilter filter = PdpGroupFilter.builder() .policyTypeList( @@ -116,20 +116,21 @@ public class PdpGroupServiceTest extends CommonPapRestServer { @Test public void testPdpGroupsCrudFailure() { - assertThatThrownBy(() -> pdpGroupService.getPdpGroupByState(null)) + PdpState pdpState = null; + assertThatThrownBy(() -> pdpGroupService.getPdpGroups(pdpState)) .hasMessage(String.format(FIELD_IS_NULL, "pdpState")); - pdpGroupService.savePdpGroups(groupsToCreate.getGroups()); + pdpGroupService.createPdpGroups(groupsToCreate.getGroups()); assertThatThrownBy(() -> pdpGroupService.deletePdpGroup("invalid-group")) .hasMessage("delete of PDP group \"invalid-group\" failed, PDP group does not exist"); assertThat(pdpGroupService.getPdpGroups()).hasSize(2); - assertThatThrownBy(() -> pdpGroupService.savePdpGroups(null)) + assertThatThrownBy(() -> pdpGroupService.createPdpGroups(null)) .hasMessage(String.format(FIELD_IS_NULL, "pdpGroups")); PdpGroup invalidPdpGroup = new PdpGroup(groupsToCreate.getGroups().get(0)); invalidPdpGroup.setName("invalidPdpGroup"); invalidPdpGroup.setPdpGroupState(null); - assertThatThrownBy(() -> pdpGroupService.savePdpGroups(List.of(invalidPdpGroup))) + assertThatThrownBy(() -> pdpGroupService.createPdpGroups(List.of(invalidPdpGroup))) .hasMessageContaining("Failed saving PdpGroup.") .hasMessageContaining("item \"pdpGroupState\" value \"null\" INVALID, is null"); pdpGroupService.deletePdpGroup(CREATE_GROUPS); @@ -154,16 +155,16 @@ public class PdpGroupServiceTest extends CommonPapRestServer { pdpGroupService.updatePdp(NAME, TYPE, new Pdp()); }).hasMessage(LOCALNAME_IS_NULL); - pdpGroupService.savePdpGroups(groupsToCreate.getGroups()); + pdpGroupService.createPdpGroups(groupsToCreate.getGroups()); assertThat(pdpGroupService.getPdpGroups()).hasSize(2); - PdpGroup pdpGroup = pdpGroupService.getPdpGroupByName(CREATE_GROUPS).get(0); + PdpGroup pdpGroup = pdpGroupService.getPdpGroups(CREATE_GROUPS).get(0); Pdp pdp = pdpGroup.getPdpSubgroups().get(0).getPdpInstances().get(0); assertThat(pdp.getHealthy()).isEqualTo(PdpHealthStatus.HEALTHY); // now update and test pdp.setHealthy(PdpHealthStatus.NOT_HEALTHY); pdpGroupService.updatePdp(CREATE_GROUPS, "pdpTypeA", pdp); - PdpGroup updatGroup = pdpGroupService.getPdpGroupByName(CREATE_GROUPS).get(0); + PdpGroup updatGroup = pdpGroupService.getPdpGroups(CREATE_GROUPS).get(0); assertThat(updatGroup.getPdpSubgroups().get(0).getPdpInstances().get(0).getHealthy()) .isEqualTo(PdpHealthStatus.NOT_HEALTHY); pdpGroupService.deletePdpGroup(CREATE_GROUPS); @@ -183,16 +184,16 @@ public class PdpGroupServiceTest extends CommonPapRestServer { pdpGroupService.updatePdpSubGroup(NAME, new PdpSubGroup()); }).hasMessage(LOCALNAME_IS_NULL); - pdpGroupService.savePdpGroups(groupsToCreate.getGroups()); + pdpGroupService.createPdpGroups(groupsToCreate.getGroups()); assertThat(pdpGroupService.getPdpGroups()).hasSize(2); - PdpGroup pdpGroup = pdpGroupService.getPdpGroupByName(CREATE_GROUPS).get(0); + PdpGroup pdpGroup = pdpGroupService.getPdpGroups(CREATE_GROUPS).get(0); PdpSubGroup pdpSubGroup = pdpGroup.getPdpSubgroups().get(0); assertThat(pdpSubGroup.getDesiredInstanceCount()).isEqualTo(2); // now update and test pdpSubGroup.setDesiredInstanceCount(1); pdpGroupService.updatePdpSubGroup(CREATE_GROUPS, pdpSubGroup); - PdpGroup updatGroup = pdpGroupService.getPdpGroupByName(CREATE_GROUPS).get(0); + PdpGroup updatGroup = pdpGroupService.getPdpGroups(CREATE_GROUPS).get(0); assertThat(updatGroup.getPdpSubgroups().get(0).getDesiredInstanceCount()).isEqualTo(1); pdpGroupService.deletePdpGroup(CREATE_GROUPS); } diff --git a/main/src/test/java/org/onap/policy/pap/main/service/PdpStatisticsServiceTest.java b/main/src/test/java/org/onap/policy/pap/main/service/PdpStatisticsServiceTest.java index 86fd9b04..fc604cee 100644 --- a/main/src/test/java/org/onap/policy/pap/main/service/PdpStatisticsServiceTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/service/PdpStatisticsServiceTest.java @@ -27,10 +27,12 @@ import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Map; +import org.junit.After; import org.junit.Before; import org.junit.Test; import org.onap.policy.models.base.Validated; import org.onap.policy.models.pdp.concepts.PdpStatistics; +import org.onap.policy.pap.main.repository.PdpStatisticsRepository; import org.onap.policy.pap.main.rest.CommonPapRestServer; import org.springframework.beans.factory.annotation.Autowired; @@ -49,6 +51,9 @@ public class PdpStatisticsServiceTest extends CommonPapRestServer { @Autowired private PdpStatisticsService pdpStatisticsService; + @Autowired + private PdpStatisticsRepository pdpStatisticsRepository; + private PdpStatistics pdpStatistics1; private PdpStatistics pdpStatistics2; private PdpStatistics pdpStatistics3; @@ -63,10 +68,19 @@ public class PdpStatisticsServiceTest extends CommonPapRestServer { @Before public void setUp() throws Exception { super.setUp(); - pdpStatistics1 = generatePdpStatistics(NAME1, TIMESTAMP1, 1L, GROUP, SUBGROUP); - pdpStatistics2 = generatePdpStatistics("name2", TIMESTAMP1, 2L, GROUP, SUBGROUP); - pdpStatistics3 = generatePdpStatistics(NAME1, TIMESTAMP2, 3L, GROUP, SUBGROUP); - pdpStatistics4 = generatePdpStatistics(NAME3, TIMESTAMP2, 4L, GROUP0, SUBGROUP); + pdpStatistics1 = generatePdpStatistics(NAME1, TIMESTAMP1, GROUP, SUBGROUP); + pdpStatistics2 = generatePdpStatistics("name2", TIMESTAMP1, GROUP, SUBGROUP); + pdpStatistics3 = generatePdpStatistics(NAME1, TIMESTAMP2, GROUP, SUBGROUP); + pdpStatistics4 = generatePdpStatistics(NAME3, TIMESTAMP2, GROUP0, SUBGROUP); + } + + /** + * Teardown after tests. + */ + @Override + @After + public void tearDown() { + pdpStatisticsRepository.deleteAll(); } @Test @@ -167,12 +181,11 @@ public class PdpStatisticsServiceTest extends CommonPapRestServer { assertThat(created.get(GROUP0).get(SUBGROUP)).isEqualTo(List.of(pdpStatistics4)); } - private PdpStatistics generatePdpStatistics(String pdpInstanceId, Instant date, Long id, String group, + private PdpStatistics generatePdpStatistics(String pdpInstanceId, Instant date, String group, String subgroup) { PdpStatistics pdpStatistics11 = new PdpStatistics(); pdpStatistics11.setPdpInstanceId(pdpInstanceId); pdpStatistics11.setTimeStamp(date); - pdpStatistics11.setGeneratedId(id); pdpStatistics11.setPdpGroupName(group); pdpStatistics11.setPdpSubGroupName(subgroup); pdpStatistics11.setPolicyDeployCount(2); diff --git a/main/src/test/java/org/onap/policy/pap/main/service/PolicyAuditServiceTest.java b/main/src/test/java/org/onap/policy/pap/main/service/PolicyAuditServiceTest.java index 980cdd1a..68044ad7 100644 --- a/main/src/test/java/org/onap/policy/pap/main/service/PolicyAuditServiceTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/service/PolicyAuditServiceTest.java @@ -27,11 +27,13 @@ import static org.junit.Assert.assertThrows; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; +import org.junit.After; import org.junit.Test; import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pap.concepts.PolicyAudit; import org.onap.policy.models.pap.concepts.PolicyAudit.AuditAction; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; +import org.onap.policy.pap.main.repository.PolicyAuditRepository; import org.onap.policy.pap.main.rest.CommonPapRestServer; import org.springframework.beans.factory.annotation.Autowired; @@ -47,6 +49,18 @@ public class PolicyAuditServiceTest extends CommonPapRestServer { @Autowired private PolicyAuditService policyAuditService; + @Autowired + private PolicyAuditRepository policyAuditRepository; + + /** + * Teardown after tests. + */ + @Override + @After + public void tearDown() { + policyAuditRepository.deleteAll(); + } + @Test public void testCreateAuditRecordsSuccess() { policyAuditService.createAuditRecords(generatePolicyAudits(Instant.now(), GROUP_A, MY_POLICY)); @@ -109,10 +123,10 @@ public class PolicyAuditServiceTest extends CommonPapRestServer { } private List generatePolicyAudits(Instant date, String group, ToscaConceptIdentifier policy) { - PolicyAudit deploy = PolicyAudit.builder().pdpGroup(group).pdpType("pdpType").policy(policy).auditId(1L) + PolicyAudit deploy = PolicyAudit.builder().pdpGroup(group).pdpType("pdpType").policy(policy) .action(AuditAction.DEPLOYMENT).timestamp(date.truncatedTo(ChronoUnit.SECONDS)).build(); - PolicyAudit undeploy = PolicyAudit.builder().pdpGroup(group).pdpType("pdpType").policy(policy).auditId(2L) + PolicyAudit undeploy = PolicyAudit.builder().pdpGroup(group).pdpType("pdpType").policy(policy) .action(AuditAction.UNDEPLOYMENT).timestamp(date.plusSeconds(1).truncatedTo(ChronoUnit.SECONDS)).build(); return List.of(deploy, undeploy); diff --git a/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java b/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java index 1a1415a5..2204392a 100644 --- a/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java +++ b/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapActivator.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * Copyright (C) 2019 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. - * Modifications Copyright (C) 2021 Bell Canada. All rights reserved. + * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,6 +41,7 @@ import org.onap.policy.common.utils.network.NetworkUtil; import org.onap.policy.common.utils.services.Registry; import org.onap.policy.pap.main.PapConstants; import org.onap.policy.pap.main.PolicyPapException; +import org.onap.policy.pap.main.comm.PdpHeartbeatListener; import org.onap.policy.pap.main.comm.PdpModifyRequestMap; import org.onap.policy.pap.main.notification.PolicyNotifier; import org.onap.policy.pap.main.parameters.CommonTestData; @@ -91,7 +92,9 @@ public class TestPapActivator { final PapParameterGroup parGroup = new CommonTestData().getPapParameterGroup(6969); - activator = new PapActivator(parGroup); + activator = new PapActivator(parGroup, new PolicyNotifier(null), new PdpHeartbeatListener(), + new PdpModifyRequestMap(null, null, null, null, null)); + } /** @@ -118,7 +121,6 @@ public class TestPapActivator { assertNotNull(Registry.get(PapConstants.REG_PDP_MODIFY_LOCK, Object.class)); assertNotNull(Registry.get(PapConstants.REG_STATISTICS_MANAGER, PapStatisticsManager.class)); assertNotNull(Registry.get(PapConstants.REG_PDP_MODIFY_MAP, PdpModifyRequestMap.class)); - assertNotNull(Registry.get(PapConstants.REG_POLICY_NOTIFIER, PolicyNotifier.class)); // repeat - should throw an exception assertThatIllegalStateException().isThrownBy(() -> activator.start()); @@ -136,7 +138,6 @@ public class TestPapActivator { assertNull(Registry.getOrDefault(PapConstants.REG_PDP_MODIFY_LOCK, Object.class, null)); assertNull(Registry.getOrDefault(PapConstants.REG_STATISTICS_MANAGER, PapStatisticsManager.class, null)); assertNull(Registry.getOrDefault(PapConstants.REG_PDP_MODIFY_MAP, PdpModifyRequestMap.class, null)); - assertNull(Registry.getOrDefault(PapConstants.REG_POLICY_NOTIFIER, PolicyNotifier.class, null)); // repeat - should throw an exception assertThatIllegalStateException().isThrownBy(() -> activator.stop()); diff --git a/main/src/test/resources/META-INF/persistence.xml b/main/src/test/resources/META-INF/persistence.xml deleted file mode 100644 index 2e44a069..00000000 --- a/main/src/test/resources/META-INF/persistence.xml +++ /dev/null @@ -1,68 +0,0 @@ - - - - - - org.eclipse.persistence.jpa.PersistenceProvider - - org.onap.policy.models.base.PfConceptKey - org.onap.policy.models.dao.converters.CDataConditioner - org.onap.policy.models.dao.converters.Uuid2String - org.onap.policy.models.pdp.persistence.concepts.JpaPdp - org.onap.policy.models.pdp.persistence.concepts.JpaPdpGroup - org.onap.policy.models.pdp.persistence.concepts.JpaPdpPolicyStatus - org.onap.policy.models.pdp.persistence.concepts.JpaPdpStatistics - org.onap.policy.models.pdp.persistence.concepts.JpaPdpSubGroup - org.onap.policy.models.pap.persistence.concepts.JpaPolicyAudit - org.onap.policy.models.tosca.simple.concepts.JpaToscaCapabilityAssignment - org.onap.policy.models.tosca.simple.concepts.JpaToscaCapabilityAssignments - org.onap.policy.models.tosca.simple.concepts.JpaToscaCapabilityType - org.onap.policy.models.tosca.simple.concepts.JpaToscaCapabilityTypes - org.onap.policy.models.tosca.simple.concepts.JpaToscaDataType - org.onap.policy.models.tosca.simple.concepts.JpaToscaDataTypes - org.onap.policy.models.tosca.simple.concepts.JpaToscaNodeTemplate - org.onap.policy.models.tosca.simple.concepts.JpaToscaNodeTemplates - org.onap.policy.models.tosca.simple.concepts.JpaToscaNodeType - org.onap.policy.models.tosca.simple.concepts.JpaToscaNodeTypes - org.onap.policy.models.tosca.simple.concepts.JpaToscaParameter - org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicies - org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicy - org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicyType - org.onap.policy.models.tosca.simple.concepts.JpaToscaPolicyTypes - org.onap.policy.models.tosca.simple.concepts.JpaToscaProperty - org.onap.policy.models.tosca.simple.concepts.JpaToscaRelationshipType - org.onap.policy.models.tosca.simple.concepts.JpaToscaRelationshipTypes - org.onap.policy.models.tosca.simple.concepts.JpaToscaRequirement - org.onap.policy.models.tosca.simple.concepts.JpaToscaRequirements - org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate - org.onap.policy.models.tosca.simple.concepts.JpaToscaTopologyTemplate - org.onap.policy.models.tosca.simple.concepts.JpaToscaTrigger - - - - - - - - - diff --git a/main/src/test/resources/config/application.yaml b/main/src/test/resources/config/application.yaml index 06d153bb..b9579db1 100644 --- a/main/src/test/resources/config/application.yaml +++ b/main/src/test/resources/config/application.yaml @@ -33,14 +33,6 @@ pap: maxWaitMs: 3000 heartBeatMs: 6000 maxMessageAgeMs: 20000 - databaseProviderParameters: - name: PolicyModelsProviderParameters - implementation: org.onap.policy.models.provider.impl.DatabasePolicyModelsProviderImpl - databaseDriver: org.h2.Driver - databaseUrl: jdbc:h2:mem:testdb0 - databaseUser: policy - databasePassword: UDAxaWNZ - persistenceUnit: ToscaConceptTest savePdpStatisticsInDb: true topicParameterGroup: topicSources: -- cgit 1.2.3-korg