diff options
Diffstat (limited to 'main/src/main/java/org')
31 files changed, 481 insertions, 764 deletions
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<PdpStatus> { - 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; @@ -66,15 +67,19 @@ 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<ToscaPolicy> getToscaPolicies(final PdpSubGroup subGroup, - final PolicyModelsProvider databaseProvider) - throws PfModelException { + public List<ToscaPolicy> getToscaPolicies(final PdpSubGroup subGroup) throws PfModelException { final List<ToscaPolicy> 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<ToscaPolicy> policies) - throws PfModelException { - var deploymentStatus = new DeploymentStatus(databaseProvider); + PdpState pdpState, List<ToscaPolicy> 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. * * <p/> - * 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<PdpGroup> groups = dao.getFilteredPdpGroups(filter); + List<PdpGroup> groups = pdpGroupService.getFilteredPdpGroups(filter); List<PdpGroup> 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); } } @@ -353,14 +367,6 @@ public class PdpModifyRequestMap { } /** - * 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. */ private class SingletonListener implements RequestListener { @@ -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<PdpGroup> pdpGroups = databaseProvider.getFilteredPdpGroups(filter); + final List<PdpGroup> 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<PdpSubGroup> 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> 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<PdpGroup> pdpGroups = databaseProvider.getFilteredPdpGroups(filter); + final List<PdpGroup> pdpGroups = pdpGroupService.getFilteredPdpGroups(filter); if (!pdpGroups.isEmpty()) { var pdpGroup = pdpGroups.get(0); Optional<PdpSubGroup> pdpSubgroup = findPdpSubGroup(message, pdpGroup); if (pdpSubgroup.isPresent()) { Optional<Pdp> 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<ToscaConceptIdentifier, ToscaPolicy> 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<ToscaPolicy> 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<PolicyNotification> publisher; - - private final PolicyModelsProviderFactoryWrapper daoFactory; + @Setter + private Publisher<PolicyNotification> publisher; /** * Processes a response from a PDP. @@ -59,8 +62,8 @@ public class PolicyNotifier { public synchronized void processResponse(String pdp, String pdpGroup, Set<ToscaConceptIdentifier> expectedPolicies, Set<ToscaConceptIdentifier> 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<HttpStatus, Pdps> 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<PdpGroup> groups = databaseProvider.getPdpGroups(null); - final List<Pdp> pdpList = new ArrayList<>(); - for (final PdpGroup group : groups) { - for (final PdpSubGroup subGroup : group.getPdpSubgroups()) { - pdpList.addAll(subGroup.getPdpInstances()); - } + final List<PdpGroup> groups = pdpGroupService.getPdpGroups(); + final List<Pdp> 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<HttpStatus, PdpGroups> 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<HttpStatus, PdpGroups> 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<PdpGroup> 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<PdpGroup> 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<PdpGroup> 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<PdpGroup> 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<PdpGroup> pdpGroups, - final PdpState pdpState) throws PfModelException { + private void updatePdpGroupAndPdp(final List<PdpGroup> 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<ToscaPolicy> policies = getToscaPolicies(subGroup, databaseProvider); + List<ToscaPolicy> 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<Object> makeOkOrNotFoundResponse(UUID requestId, Collection<PolicyAudit> 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<PolicyAudit> 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<PolicyAudit> 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<HttpClient> 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<PdpGroup> groups = fetchPdpGroups(); + List<PdpGroup> groups = pdpGroupService.getPdpGroups(); Map<String, List<Pdp>> 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<PdpGroup> fetchPdpGroups() throws PfModelException { - List<PdpGroup> 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<PolicyStatus> getStatus() throws PfModelException { - try (PolicyModelsProvider dao = daoFactory.create()) { - return accumulate(dao.getAllPolicyStatus()); - } + public Collection<PolicyStatus> 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<PolicyStatus> getStatus(ToscaConceptIdentifierOptVersion policy) throws PfModelException { - try (PolicyModelsProvider dao = daoFactory.create()) { - return accumulate(dao.getAllPolicyStatus(policy)); - } + public Collection<PolicyStatus> 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<PolicyStatus> getByRegex(String patternString) throws PfModelException { + public Collection<PolicyStatus> getByRegex(String patternString) { // try to make pattern out of regex final var pattern = Pattern.compile(patternString); // get all the statuses - final List<PdpPolicyStatus> policyStatuses; - try (PolicyModelsProvider dao = daoFactory.create()) { - policyStatuses = dao.getAllPolicyStatus(); - } + final List<PdpPolicyStatus> policyStatuses = policyStatusService.getAllPolicyStatus(); // filter out statuses with the wrong name final Collection<PdpPolicyStatus> 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<PdpPolicyStatus> getPolicyStatus() throws PfModelException { - try (PolicyModelsProvider dao = daoFactory.create()) { - return dao.getAllPolicyStatus(); - } + public Collection<PdpPolicyStatus> 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<PdpPolicyStatus> getPolicyStatus(String pdpGroupName) throws PfModelException { - try (PolicyModelsProvider dao = daoFactory.create()) { - return dao.getGroupPolicyStatus(pdpGroupName); - } + public Collection<PdpPolicyStatus> 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<PdpPolicyStatus> 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<PdpPolicyStatus> 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<PdpPolicyStatus> getPolicyStatusByRegex(String pdpGroupName, String patternString) - throws PfModelException { + public Collection<PdpPolicyStatus> getPolicyStatusByRegex(String pdpGroupName, String patternString) { final var pattern = Pattern.compile(patternString); // get all the statuses final Collection<PdpPolicyStatus> 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<ToscaConceptIdentifier> 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; @@ -63,11 +67,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<ToscaPolicyType> lst = dao.getPolicyTypeList(desiredType.getName(), desiredType.getVersion()); + List<ToscaPolicyType> 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<ToscaPolicy> filterBuilder = - ToscaTypedEntityFilter.<ToscaPolicy>builder().name(desiredPolicy.getName()); + ToscaTypedEntityFilter.<ToscaPolicy>builder().name(desiredPolicy.getName()); setPolicyFilterVersion(filterBuilder, desiredPolicy.getVersion()); - List<ToscaPolicy> lst = dao.getFilteredPolicyList(filterBuilder.build()); + List<ToscaPolicy> 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<PdpGroup> lst = dao.getPdpGroups(name); + List<PdpGroup> 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<PdpGroup> groups = dao.getFilteredPdpGroups(filter); + List<PdpGroup> 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<GroupData> 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<String, Map<String, List<PdpStatistics>>> 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<String, Map<String, List<PdpStatistics>>> generatePdpStatistics(List<PdpStatistics> pdpStatisticsList) { - Map<String, Map<String, List<PdpStatistics>>> 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<PdpGroup> getPdpGroupByName(@NonNull String pdpGroup) { + public List<PdpGroup> 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<PdpGroup> getPdpGroupByState(@NonNull PdpState pdpState) { + public List<PdpGroup> 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<PdpGroup> getPdpGroupByNameAndState(@NonNull String pdpGroup, @NonNull PdpState state) { + public List<PdpGroup> 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<PdpGroup> pdpGroups) { + public List<PdpGroup> createPdpGroups(@NonNull final List<PdpGroup> pdpGroups) { + return savePdpGroups(pdpGroups); + } + + /** + * Updates PDP groups. + * + * @param pdpGroups the PDP groups to create + * @return the PDP groups created + */ + public List<PdpGroup> updatePdpGroups(@NonNull final List<PdpGroup> pdpGroups) { + return savePdpGroups(pdpGroups); + } - // Return the created PDP groups + private List<PdpGroup> savePdpGroups(final List<PdpGroup> pdpGroups) { List<PdpGroup> 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,9 +58,33 @@ 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. * * @param pdpStatisticsList a specification of the PDP statistics to create @@ -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<String, Map<String, List<PdpStatistics>>> fetchDatabaseStatistics(String pdpGroup, String pdpSubGroup, - String pdp, int recordCount, Instant startTime, Instant endTime) { + public Map<String, Map<String, List<PdpStatistics>>> 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<String, Map<String, List<PdpStatistics>>> fetchDatabaseStatistics(String pdpGroup, String pdpSubGroup, - int recordCount, Instant startTime, Instant endTime) { + public Map<String, Map<String, List<PdpStatistics>>> 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<String, Map<String, List<PdpStatistics>>> fetchDatabaseStatistics(String pdpGroup, int recordCount, - Instant startTime, Instant endTime) { + public Map<String, Map<String, List<PdpStatistics>>> 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<PolicyAudit> getAuditRecords(String pdpGroup, int recordCount, Instant startTime, Instant endTime) { + public List<PolicyAudit> 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<PolicyAudit> getAuditRecords(String pdpGroup, String policyName, String policyVersion, int recordCount, - Instant startTime, Instant endTime) { + public List<PolicyAudit> 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<PolicyAudit> getAuditRecords(String policyName, String policyVersion, int recordCount, + public List<PolicyAudit> 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; @@ -82,6 +83,18 @@ public class ToscaServiceTemplateService { } /** + * Get filtered policies. + * + * @param filter the filter for the policies to get + * @return the policies found + * @throws PfModelException on errors getting policies + */ + public List<ToscaPolicy> getFilteredPolicyList(ToscaTypedEntityFilter<ToscaPolicy> filter) throws PfModelException { + String version = ToscaTypedEntityFilter.LATEST_VERSION.equals(filter.getVersion()) ? null : filter.getVersion(); + return filter.filter(getPolicyList(filter.getName(), version)); + } + + /** * Get policy types. * * @param name the name of the policy type to get, set to null to get all 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; @@ -89,16 +87,12 @@ public class PapActivator extends ServiceManagerContainer { private final RequestIdDispatcher<PdpStatus> 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<TimerManager> pdpUpdTimers = new AtomicReference<>(); final AtomicReference<TimerManager> pdpStChgTimers = new AtomicReference<>(); final AtomicReference<ScheduledExecutorService> pdpExpirationTimer = new AtomicReference<>(); - final AtomicReference<PolicyModelsProviderFactoryWrapper> daoFactory = new AtomicReference<>(); final AtomicReference<PdpModifyRequestMap> requestMap = new AtomicReference<>(); - final AtomicReference<PolicyNotifier> 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<PdpGroup> pdpGroupsFromDb = databaseProvider.getPdpGroups( - pdpGroupsToCreate.getGroups().get(0).getName()); + final List<PdpGroup> 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); } } |