From 51589bc07dcf6a17f0e165ef3195b0a238c7ca69 Mon Sep 17 00:00:00 2001 From: "adheli.tavares" Date: Fri, 21 Jun 2024 19:57:25 +0100 Subject: Code coverage and sonar fixes for PAP Issue-ID: POLICY-5058 Change-Id: I85efd6b0b2ac498959bbaf23ebe1b2ba6e1c320e Signed-off-by: adheli.tavares --- .../policy/pap/main/PolicyPapRuntimeException.java | 6 +- .../policy/pap/main/comm/PdpHeartbeatListener.java | 10 +- .../policy/pap/main/comm/PdpMessageGenerator.java | 25 ++-- .../policy/pap/main/comm/PdpModifyRequestMap.java | 34 +++-- .../pap/main/comm/PdpStatusMessageHandler.java | 55 ++++---- .../policy/pap/main/config/WebSecurityConfig.java | 4 +- .../main/exception/ServiceExceptionHandler.java | 13 +- .../main/rest/PdpGroupStateChangeControllerV1.java | 9 +- .../pap/main/rest/PdpGroupStateChangeProvider.java | 43 +++--- .../pap/main/rest/PolicyStatusControllerV1.java | 148 ++++++--------------- .../policy/pap/main/rest/PolicyStatusProvider.java | 10 +- .../pap/main/service/PolicyAuditService.java | 7 +- .../pap/main/service/PolicyStatusService.java | 17 +-- .../main/service/ToscaServiceTemplateService.java | 18 +-- .../pap/main/startstop/PapDatabaseInitializer.java | 9 +- .../pap/main/comm/PdpModifyRequestMapTest.java | 24 +--- .../policy/pap/main/comm/TimerManagerTest.java | 43 ++---- .../pap/main/comm/msgdata/UpdateReqTest.java | 16 +-- .../pap/main/notification/PolicyNotifierTest.java | 24 ++-- .../policy/pap/main/rest/CommonPapRestServer.java | 16 ++- .../onap/policy/pap/main/rest/ProviderSuper.java | 16 +-- .../rest/TestPdpGroupCreateOrUpdateProvider.java | 86 ++++++------ .../pap/main/rest/TestPdpGroupDeleteProvider.java | 12 +- .../pap/main/rest/TestPdpGroupDeployProvider.java | 49 +++---- .../main/rest/TestPdpGroupHealthCheckProvider.java | 4 +- .../rest/TestPdpGroupStateChangeControllerV1.java | 20 ++- .../pap/main/rest/TestPolicyAuditManager.java | 8 +- .../pap/main/rest/TestPolicyStatusProvider.java | 5 +- .../pap/main/rest/TestPolicyUndeployerImpl.java | 13 +- .../policy/pap/main/rest/TestProviderBase.java | 27 ++-- .../onap/policy/pap/main/rest/TestSessionData.java | 31 +++-- .../onap/policy/pap/main/rest/e2e/End2EndBase.java | 8 +- .../pap/main/rest/e2e/PdpGroupDeployTest.java | 4 +- .../pap/main/service/PolicyAuditServiceTest.java | 54 +++++++- .../pap/main/service/PolicyStatusServiceTest.java | 35 +++-- .../main/startstop/TestPapDatabaseInitializer.java | 80 +++++++++++ main/src/test/resources/application-test-db.yaml | 14 ++ .../createGroupDuplicateSubGroups.json | 53 ++++++++ 38 files changed, 554 insertions(+), 496 deletions(-) create mode 100644 main/src/test/java/org/onap/policy/pap/main/startstop/TestPapDatabaseInitializer.java create mode 100644 main/src/test/resources/application-test-db.yaml create mode 100644 main/src/test/resources/simpleDeploy/createGroupDuplicateSubGroups.json (limited to 'main') diff --git a/main/src/main/java/org/onap/policy/pap/main/PolicyPapRuntimeException.java b/main/src/main/java/org/onap/policy/pap/main/PolicyPapRuntimeException.java index 95b941f6..b4b1cf98 100644 --- a/main/src/main/java/org/onap/policy/pap/main/PolicyPapRuntimeException.java +++ b/main/src/main/java/org/onap/policy/pap/main/PolicyPapRuntimeException.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. + * Copyright (C) 2019, 2024 Nordix Foundation. * Modifications Copyright (C) 2019 AT&T Intellectual Property. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -21,12 +21,16 @@ package org.onap.policy.pap.main; +import java.io.Serial; + /** * This runtime exception will be called if a runtime error occurs when using policy pap. * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ public class PolicyPapRuntimeException extends RuntimeException { + + @Serial private static final long serialVersionUID = -8507246953751956974L; /** 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 4e4709e9..abf28d79 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 @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. + * Copyright (C) 2019, 2024 Nordix Foundation. * Modifications Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ @@ -22,7 +22,6 @@ 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; @@ -35,14 +34,17 @@ import org.springframework.stereotype.Component; * * @author Ram Krishna Verma (ram.krishna.verma@est.tech) */ -@AllArgsConstructor @NoArgsConstructor @Component public class PdpHeartbeatListener implements TypedMessageListener { - @Autowired private PdpStatusMessageHandler pdpStatusMessageHandler; + @Autowired + public PdpHeartbeatListener(PdpStatusMessageHandler pdpStatusMessageHandler) { + this.pdpStatusMessageHandler = pdpStatusMessageHandler; + } + @Override public void onTopicEvent(final CommInfrastructure infra, final String topic, final PdpStatus 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 7bf6b803..af92e44f 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 @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021-2022 Nordix Foundation. + * Modifications Copyright (C) 2021-2022, 2024 Nordix Foundation. * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -27,7 +27,6 @@ import java.util.List; import lombok.Getter; import org.onap.policy.common.parameters.ParameterService; import org.onap.policy.common.utils.services.Registry; -import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.pap.concepts.PolicyNotification; import org.onap.policy.models.pdp.concepts.PdpStateChange; import org.onap.policy.models.pdp.concepts.PdpSubGroup; @@ -88,7 +87,7 @@ public class PdpMessageGenerator { * Constructs the object. * * @param includeHeartBeat if the heart beat interval is to be included in any - * PDP-UPDATE messages + * PDP-UPDATE messages */ public PdpMessageGenerator(boolean includeHeartBeat) { this.includeHeartBeat = includeHeartBeat; @@ -112,9 +111,8 @@ public class PdpMessageGenerator { } protected PdpUpdate createPdpUpdateMessage(final String pdpGroupName, final PdpSubGroup subGroup, - final String pdpInstanceId, - final List policiesToBeDeployed, - final List policiesToBeUndeployed) { + final String pdpInstanceId, final List policiesToBeDeployed, + final List policiesToBeUndeployed) { final var update = new PdpUpdate(); @@ -135,9 +133,8 @@ public class PdpMessageGenerator { * * @param subGroup PdpSubGroup to retrieve policies from * @return a list of ToscaPolicy - * @throws PfModelException the exception **/ - public List getToscaPolicies(final PdpSubGroup subGroup) throws PfModelException { + public List getToscaPolicies(final PdpSubGroup subGroup) { final List policies = new LinkedList<>(); for (final ToscaConceptIdentifier policyIdentifier : subGroup.getPolicies()) { @@ -149,7 +146,7 @@ public class PdpMessageGenerator { } protected PdpStateChange createPdpStateChangeMessage(final String pdpGroupName, final PdpSubGroup subGroup, - final String pdpInstanceId, final PdpState pdpState) { + final String pdpInstanceId, final PdpState pdpState) { final var stateChange = new PdpStateChange(); stateChange.setSource(PapConstants.PAP_NAME); @@ -166,14 +163,14 @@ public class PdpMessageGenerator { * If group state=ACTIVE AND updateMsg has policiesToDeploy, then make sure deployment status is updated * If group state=PASSIVE, then delete any deployment information for a PDP. * - * @param pdpGroupName the group name - * @param pdpType the pdp type + * @param pdpGroupName the group name + * @param pdpType the pdp type * @param pdpInstanceId the pdp instance - * @param pdpState the new state as per the PDP_STATE_CHANGE change message - * @param policies list of policies as per the PDP_UPDATE message + * @param pdpState the new state as per the PDP_STATE_CHANGE change message + * @param policies list of policies as per the PDP_UPDATE message */ protected void updateDeploymentStatus(final String pdpGroupName, final String pdpType, final String pdpInstanceId, - PdpState pdpState, List policies) { + PdpState pdpState, List policies) { var deploymentStatus = new DeploymentStatus(policyStatusService); deploymentStatus.loadByGroup(pdpGroupName); if (pdpState.equals(PdpState.PASSIVE)) { 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 e23026be..1b8018bf 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 @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2021, 2024 Nordix Foundation. * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -89,7 +89,6 @@ public class PdpModifyRequestMap { /** * Used to undeploy policies from the system, when they cannot be deployed to a PDP. - * *

* Note: The request map needs an undeployer during creation, and the undeployer * needs the request map when it's initialize method is called. @@ -105,15 +104,15 @@ public class PdpModifyRequestMap { /** * Constructs the object. * - * @param pdpGroupService the pdpGroupService - * @param policyStatusService the policyStatusService + * @param pdpGroupService the pdpGroupService + * @param policyStatusService the policyStatusService * @param pdpStatusMessageHandler the pdpStatusMessageHandler - * @param policyUndeployer the policyUndeployer - * @param policyNotifier the policyNotifier + * @param policyUndeployer the policyUndeployer + * @param policyNotifier the policyNotifier */ public PdpModifyRequestMap(PdpGroupService pdpGroupService, PolicyStatusService policyStatusService, - PdpStatusMessageHandler pdpStatusMessageHandler, PolicyUndeployer policyUndeployer, - PolicyNotifier policyNotifier) { + PdpStatusMessageHandler pdpStatusMessageHandler, PolicyUndeployer policyUndeployer, + PolicyNotifier policyNotifier) { this.pdpGroupService = pdpGroupService; this.policyStatusService = policyStatusService; this.pdpStatusMessageHandler = pdpStatusMessageHandler; @@ -159,7 +158,7 @@ public class PdpModifyRequestMap { /** * Adds a pair of requests to the map. * - * @param update the UPDATE request or {@code null} + * @param update the UPDATE request or {@code null} * @param stateChange the STATE-CHANGE request or {@code null} */ public void addRequest(PdpUpdate update, PdpStateChange stateChange) { @@ -189,11 +188,10 @@ public class PdpModifyRequestMap { * Adds an UPDATE request to the map. * * @param update the UPDATE request or {@code null} - * @return the new request (this should only be used by junit tests) */ - public Request addRequest(PdpUpdate update) { + public void addRequest(PdpUpdate update) { if (update == null) { - return null; + return; } if (isBroadcast(update)) { @@ -213,7 +211,6 @@ public class PdpModifyRequestMap { var request = new UpdateReq(reqparams, name, update); addSingleton(request); - return request; } /** @@ -251,8 +248,7 @@ public class PdpModifyRequestMap { * Determines if a message is a broadcast message. * * @param message the message to examine - * @return {@code true} if the message is a broadcast message, {@code false} if - * destined for a single PDP + * @return {@code true} if the message is a broadcast message, {@code false} if destined for a single PDP */ private boolean isBroadcast(PdpMessage message) { return (message.getName() == null); @@ -319,7 +315,7 @@ public class PdpModifyRequestMap { * Removes expired PDPs from a group. * * @param minAge minimum age for active PDPs - * @param group group from which expired PDPs should be removed + * @param group group from which expired PDPs should be removed * @return the expired PDPs */ private Set removeFromGroup(Instant minAge, PdpGroup group) { @@ -335,9 +331,9 @@ public class PdpModifyRequestMap { * Removes expired PDPs from a subgroup. * * @param minAge minimum age for active PDPs - * @param group group from which to attempt to remove the PDP + * @param group group from which to attempt to remove the PDP * @param subgrp subgroup from which to attempt to remove the PDP - * @param pdps where to place the expired PDPs + * @param pdps where to place the expired PDPs */ private void removeFromSubgroup(Instant minAge, PdpGroup group, PdpSubGroup subgrp, Set pdps) { @@ -397,7 +393,7 @@ public class PdpModifyRequestMap { try { logger.warn("undeploy policies from {}:{} that failed to deploy: {}", oldmsg.getPdpGroup(), - oldmsg.getPdpSubgroup(), undeployPolicies); + oldmsg.getPdpSubgroup(), undeployPolicies); policyUndeployer.undeploy(oldmsg.getPdpGroup(), oldmsg.getPdpSubgroup(), undeployPolicies); } catch (PfModelException | RuntimeException e) { logger.error("cannot undeploy policies {}", undeployPolicies, e); 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 1426d1cb..068c10ae 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 @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019-2021,2023 Nordix Foundation. + * Copyright (C) 2019-2021, 2023-2024 Nordix Foundation. * Modifications Copyright (C) 2019-2021 AT&T Intellectual Property. * Modifications Copyright (C) 2021-2023 Bell Canada. All rights reserved. * ================================================================================ @@ -26,6 +26,7 @@ import java.sql.SQLIntegrityConstraintViolationException; import java.time.Instant; import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -33,7 +34,6 @@ import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.apache.commons.lang3.builder.EqualsBuilder; -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.PdpGroupFilter; @@ -83,7 +83,7 @@ public class PdpStatusMessageHandler extends PdpMessageGenerator { /** * Constructs the object. * - * @param parameterGroup the parameterGroup + * @param parameterGroup the parameterGroup * @param pdpGroupService the pdpGroupService */ public PdpStatusMessageHandler(PapParameterGroup parameterGroup, PdpGroupService pdpGroupService) { @@ -126,7 +126,7 @@ public class PdpStatusMessageHandler extends PdpMessageGenerator { * instead of an error level. */ LOGGER.info("Failed updating PDP information for {} - may have been added by another PAP", - message.getName()); + message.getName()); LOGGER.trace("Failed updating PDP information for {}", message.getName(), exp); } else { LOGGER.error("Failed connecting to database provider", exp); @@ -138,7 +138,7 @@ public class PdpStatusMessageHandler extends PdpMessageGenerator { /** * Determines if the exception indicates a duplicate key. * - * @param thrown exception to check + * @param thrown exception to check * @param exceptionClazz the class to check against * @return {@code true} if the exception occurred due to a duplicate key */ @@ -158,7 +158,7 @@ public class PdpStatusMessageHandler extends PdpMessageGenerator { return false; } - private void handlePdpRegistration(final PdpStatus message) throws PfModelException, PolicyPapException { + private void handlePdpRegistration(final PdpStatus message) throws PolicyPapException { if (!findAndUpdatePdpGroup(message)) { final var errorMessage = "Failed to register PDP. No matching PdpGroup/SubGroup Found - "; LOGGER.debug("{}{}", errorMessage, message); @@ -166,11 +166,10 @@ public class PdpStatusMessageHandler extends PdpMessageGenerator { } } - private boolean findAndUpdatePdpGroup(final PdpStatus message) - throws PfModelException { + private boolean findAndUpdatePdpGroup(final PdpStatus message) { var pdpGroupFound = false; final PdpGroupFilter filter = - PdpGroupFilter.builder().name(message.getPdpGroup()).groupState(PdpState.ACTIVE).build(); + PdpGroupFilter.builder().name(message.getPdpGroup()).groupState(PdpState.ACTIVE).build(); final List pdpGroups = pdpGroupService.getFilteredPdpGroups(filter); if (!pdpGroups.isEmpty()) { @@ -179,7 +178,7 @@ public class PdpStatusMessageHandler extends PdpMessageGenerator { return pdpGroupFound; } - private boolean registerPdp(final PdpStatus message, final PdpGroup finalizedPdpGroup) throws PfModelException { + private boolean registerPdp(final PdpStatus message, final PdpGroup finalizedPdpGroup) { Optional subGroup; var pdpGroupFound = false; subGroup = findPdpSubGroup(message, finalizedPdpGroup); @@ -187,7 +186,7 @@ public class PdpStatusMessageHandler extends PdpMessageGenerator { if (subGroup.isPresent()) { policies = getToscaPolicies(subGroup.get()); policiesToBeDeployed = policies.stream().collect(Collectors - .toMap(ToscaPolicy::getIdentifier, policy -> policy)); + .toMap(ToscaPolicy::getIdentifier, policy -> policy)); policiesToBeUndeployed = null; LOGGER.debug("Found pdpGroup - {}, going for registration of PDP - {}", finalizedPdpGroup, message); @@ -220,10 +219,10 @@ public class PdpStatusMessageHandler extends PdpMessageGenerator { LOGGER.debug("Updated PdpSubGroup in DB - {} belonging to PdpGroup - {}", pdpSubGroup, pdpGroup.getName()); } - private void handlePdpHeartbeat(final PdpStatus message) throws PfModelException { + private void handlePdpHeartbeat(final PdpStatus message) { final PdpGroupFilter filter = - PdpGroupFilter.builder().name(message.getPdpGroup()).groupState(PdpState.ACTIVE).build(); + PdpGroupFilter.builder().name(message.getPdpGroup()).groupState(PdpState.ACTIVE).build(); final List pdpGroups = pdpGroupService.getFilteredPdpGroups(filter); if (!pdpGroups.isEmpty()) { var pdpGroup = pdpGroups.get(0); @@ -263,20 +262,20 @@ public class PdpStatusMessageHandler extends PdpMessageGenerator { } private void processPdpDetails(final PdpStatus message, final PdpSubGroup pdpSubGroup, final Pdp pdpInstance, - final PdpGroup pdpGroup) throws PfModelException { + final PdpGroup pdpGroup) { // all policies policies = getToscaPolicies(pdpSubGroup); Map policyMap = - policies.stream().collect(Collectors.toMap(ToscaPolicy::getIdentifier, policy -> policy)); + policies.stream().collect(Collectors.toMap(ToscaPolicy::getIdentifier, policy -> policy)); // policies that the PDP already has (-) all - policiesToBeUndeployed = message.getPolicies().stream().filter(policyId -> !policyMap.containsKey(policyId)) - .collect(Collectors.toList()); + policiesToBeUndeployed = message.getPolicies().stream() + .filter(policyId -> !policyMap.containsKey(policyId)).toList(); // all (-) policies that the PDP already has policiesToBeDeployed = policyMap; - policiesToBeDeployed.keySet().removeAll(message.getPolicies()); + message.getPolicies().forEach(policiesToBeDeployed.keySet()::remove); if (PdpState.TERMINATED.equals(message.getState())) { processPdpTermination(pdpSubGroup, pdpInstance, pdpGroup); @@ -298,25 +297,25 @@ public class PdpStatusMessageHandler extends PdpMessageGenerator { pdpGroupService.updatePdpSubGroup(pdpGroup.getName(), pdpSubGroup); LOGGER.debug("Deleted PdpInstance - {} belonging to PdpSubGroup - {} and PdpGroup - {}", pdpInstance, - pdpSubGroup, pdpGroup); + pdpSubGroup, pdpGroup); } private boolean validatePdpDetails(final PdpStatus message, final PdpGroup pdpGroup, final PdpSubGroup subGroup, - final Pdp pdpInstanceDetails) { + final Pdp pdpInstanceDetails) { /* * "EqualsBuilder" is a bit of a misnomer, as it uses containsAll() to check policies. Nevertheless, it does the * job and provides a convenient way to build a bunch of comparisons. */ return new EqualsBuilder().append(message.getPdpGroup(), pdpGroup.getName()) - .append(message.getPdpSubgroup(), subGroup.getPdpType()) - .append(message.getPdpType(), subGroup.getPdpType()) - .append(message.getState(), pdpInstanceDetails.getPdpState()) - .append(message.getPolicies().containsAll(subGroup.getPolicies()), true) - .append(subGroup.getPolicies().containsAll(message.getPolicies()), true).build(); + .append(message.getPdpSubgroup(), subGroup.getPdpType()) + .append(message.getPdpType(), subGroup.getPdpType()) + .append(message.getState(), pdpInstanceDetails.getPdpState()) + .append(new HashSet<>(message.getPolicies()).containsAll(subGroup.getPolicies()), true) + .append(new HashSet<>(subGroup.getPolicies()).containsAll(message.getPolicies()), true).build(); } private void updatePdpHealthStatus(final PdpStatus message, final PdpSubGroup pdpSubgroup, final Pdp pdpInstance, - final PdpGroup pdpGroup) { + final PdpGroup pdpGroup) { pdpInstance.setHealthy(message.getHealthy()); pdpInstance.setMessage(message.getDescription()); pdpInstance.setLastUpdate(Instant.now()); @@ -326,11 +325,11 @@ public class PdpStatusMessageHandler extends PdpMessageGenerator { } private void sendPdpMessage(final String pdpGroupName, final PdpSubGroup subGroup, final String pdpInstanceId, - final PdpState pdpState) { + final PdpState pdpState) { final List polsToBeDeployed = new LinkedList<>(policiesToBeDeployed.values()); final var pdpUpdatemessage = createPdpUpdateMessage(pdpGroupName, subGroup, pdpInstanceId, - polsToBeDeployed, policiesToBeUndeployed); + polsToBeDeployed, policiesToBeUndeployed); final var pdpStateChangeMessage = createPdpStateChangeMessage(pdpGroupName, subGroup, pdpInstanceId, pdpState); updateDeploymentStatus(pdpGroupName, subGroup.getPdpType(), pdpInstanceId, pdpStateChangeMessage.getState(), diff --git a/main/src/main/java/org/onap/policy/pap/main/config/WebSecurityConfig.java b/main/src/main/java/org/onap/policy/pap/main/config/WebSecurityConfig.java index 181ea434..32b7ff86 100644 --- a/main/src/main/java/org/onap/policy/pap/main/config/WebSecurityConfig.java +++ b/main/src/main/java/org/onap/policy/pap/main/config/WebSecurityConfig.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2021 Bell Canada. All rights reserved. - * Modifications Copyright (C) 2023 Nordix Foundation. + * Modifications Copyright (C) 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ public class WebSecurityConfig { http .httpBasic(Customizer.withDefaults()) .authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated()) - .csrf(AbstractHttpConfigurer::disable); + .csrf(AbstractHttpConfigurer::disable); // NOSONAR return http.build(); } } diff --git a/main/src/main/java/org/onap/policy/pap/main/exception/ServiceExceptionHandler.java b/main/src/main/java/org/onap/policy/pap/main/exception/ServiceExceptionHandler.java index 58876fc8..685d52f6 100644 --- a/main/src/main/java/org/onap/policy/pap/main/exception/ServiceExceptionHandler.java +++ b/main/src/main/java/org/onap/policy/pap/main/exception/ServiceExceptionHandler.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2022 Bell Canada. All rights reserved. - * Modifications Copyright (C) 2023 Nordix Foundation. + * Modifications Copyright (C) 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,6 @@ package org.onap.policy.pap.main.exception; import jakarta.ws.rs.core.Response; -import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.onap.policy.models.base.PfModelRuntimeException; @@ -37,13 +36,12 @@ public class ServiceExceptionHandler { * Handle any exceptions that are not already handled. * For e.g., runtime exceptions that could happen during SQL query execution related to data integrity etc. * - * @param joinPoint the point of execution * @param exception the exception */ @AfterThrowing(pointcut = "execution(* org.onap.policy.pap.main.service.*.*(..))", throwing = "exception") - public void handleServiceException(JoinPoint joinPoint, RuntimeException exception) { - if (exception instanceof PfModelRuntimeException) { - throw (PfModelRuntimeException) exception; + public void handleServiceException(RuntimeException exception) { + if (exception instanceof PfModelRuntimeException pfModelException) { + throw pfModelException; } else { throw new PfModelRuntimeException(Response.Status.INTERNAL_SERVER_ERROR, exception.getMessage(), exception); } @@ -55,11 +53,10 @@ public class ServiceExceptionHandler { * Autowiring these service classes can cause TransactionException. * For e.g., JDBC connection failure occurs and failed to open transaction at service level * - * @param joinPoint the point of execution * @param exception the exception */ @AfterThrowing(pointcut = "execution(* org.onap.policy.pap.main.*.*.*(..))", throwing = "exception") - public void handleTransactionException(JoinPoint joinPoint, TransactionException exception) { + public void handleTransactionException(TransactionException exception) { throw new PfModelRuntimeException(Response.Status.INTERNAL_SERVER_ERROR, exception.getMessage(), exception); } } diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupStateChangeControllerV1.java b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupStateChangeControllerV1.java index f63fc1d5..bf6cf244 100644 --- a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupStateChangeControllerV1.java +++ b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupStateChangeControllerV1.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019-2023 Nordix Foundation. + * Copyright (C) 2019-2024 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. * Modifications Copyright (C) 2021, 2023 Bell Canada. All rights reserved. * ================================================================================ @@ -53,13 +53,12 @@ public class PdpGroupStateChangeControllerV1 extends PapRestControllerV1 impleme * * @param requestId request ID used in ONAP logging * @param groupName name of the PDP group to be deleted - * @param state state of the PDP group + * @param state state of the PDP group * @return a response - * @throws PfModelException Exception thrown by changeGroupState */ @Override - public ResponseEntity changeGroupState( - String groupName, PdpState state, UUID requestId) { + public ResponseEntity changeGroupState(String groupName, PdpState state, + UUID requestId) { try { final Pair pair = provider.changeGroupState(groupName, state); return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.status(pair.getLeft())), requestId) 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 648b56f1..7b3b1b94 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 @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019-2021, 2023 Nordix Foundation. + * Copyright (C) 2019-2021, 2023-2024 Nordix Foundation. * Modifications Copyright (C) 2019-2021 AT&T Intellectual Property. * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ @@ -36,7 +36,6 @@ 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; @@ -50,43 +49,39 @@ public class PdpGroupStateChangeProvider extends PdpMessageGenerator { private static final Logger LOGGER = LoggerFactory.getLogger(PdpGroupStateChangeProvider.class); - @Autowired - private PdpGroupService pdpGroupService; + private final PdpGroupService pdpGroupService; /** * Constructs the object. */ - public PdpGroupStateChangeProvider() { + public PdpGroupStateChangeProvider(PdpGroupService pdpGroupService) { super(false); + this.pdpGroupService = pdpGroupService; } /** * Changes state of a PDP group. * - * @param groupName name of the PDP group + * @param groupName name of the PDP group * @param pdpGroupState state of the PDP group * @return a pair containing the status and the response * @throws PfModelException in case of errors */ public Pair changeGroupState(final String groupName, - final PdpState pdpGroupState) throws PfModelException { + final PdpState pdpGroupState) + throws PfModelException { synchronized (updateLock) { switch (pdpGroupState) { - case ACTIVE: - handleActiveState(groupName); - break; - case PASSIVE: - handlePassiveState(groupName); - break; - default: - throw new PfModelException(Response.Status.BAD_REQUEST, - "Only ACTIVE or PASSIVE state changes are allowed"); + case ACTIVE -> handleActiveState(groupName); + case PASSIVE -> handlePassiveState(groupName); + default -> throw new PfModelException(Response.Status.BAD_REQUEST, + "Only ACTIVE or PASSIVE state changes are allowed"); } return Pair.of(HttpStatus.OK, new PdpGroupStateChangeResponse()); } } - private void handleActiveState(final String groupName) throws PfModelException { + private void handleActiveState(final String groupName) { final List pdpGroups = pdpGroupService.getPdpGroups(groupName); if (!pdpGroups.isEmpty() && !PdpState.ACTIVE.equals(pdpGroups.get(0).getPdpGroupState())) { updatePdpGroupAndPdp(pdpGroups, PdpState.ACTIVE); @@ -94,7 +89,7 @@ public class PdpGroupStateChangeProvider extends PdpMessageGenerator { } } - private void handlePassiveState(final String groupName) throws PfModelException { + private void handlePassiveState(final String groupName) { final List pdpGroups = pdpGroupService.getPdpGroups(groupName); if (!pdpGroups.isEmpty() && !PdpState.PASSIVE.equals(pdpGroups.get(0).getPdpGroupState())) { updatePdpGroupAndPdp(pdpGroups, PdpState.PASSIVE); @@ -114,21 +109,21 @@ public class PdpGroupStateChangeProvider extends PdpMessageGenerator { LOGGER.debug("Updated PdpGroup and Pdp in DB - {} ", pdpGroups); } - private void sendPdpMessage(final PdpGroup pdpGroup, final PdpState pdpState) throws PfModelException { + private void sendPdpMessage(final PdpGroup pdpGroup, final PdpState pdpState) { String pdpGroupName = pdpGroup.getName(); for (final PdpSubGroup subGroup : pdpGroup.getPdpSubgroups()) { List policies = getToscaPolicies(subGroup); for (final Pdp pdp : subGroup.getPdpInstances()) { String pdpInstanceId = pdp.getInstanceId(); - final var pdpUpdatemessage = + final var pdpUpdateMessage = createPdpUpdateMessage(pdpGroup.getName(), subGroup, pdp.getInstanceId(), - policies, null); + policies, null); final var pdpStateChangeMessage = createPdpStateChangeMessage(pdpGroupName, subGroup, pdpInstanceId, pdpState); updateDeploymentStatus(pdpGroupName, subGroup.getPdpType(), pdpInstanceId, - pdpStateChangeMessage.getState(), pdpUpdatemessage.getPoliciesToBeDeployed()); - requestMap.addRequest(pdpUpdatemessage, pdpStateChangeMessage); - LOGGER.debug("Sent PdpUpdate message - {}", pdpUpdatemessage); + 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/PolicyStatusControllerV1.java b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyStatusControllerV1.java index dfa4ae9a..0a6f4b31 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 @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021-2023 Nordix Foundation. + * Modifications Copyright (C) 2021-2024 Nordix Foundation. * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -26,7 +26,6 @@ import com.google.re2j.PatternSyntaxException; import java.util.Collection; import java.util.UUID; import lombok.RequiredArgsConstructor; -import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pap.concepts.PolicyStatus; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifierOptVersion; @@ -58,7 +57,7 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 implements Pol * policies that match regex * * @param requestId request ID used in ONAP logging - * @param regex regex for a policy name + * @param regex regex for a policy name * @return a response */ @Override @@ -74,11 +73,6 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 implements Pol } return makeListOrNotFoundResponse(requestId, result); - } catch (PfModelRuntimeException e) { - logger.warn(GET_DEPLOYMENTS_FAILED, e); - return addLoggingHeaders( - addVersionControlHeaders(ResponseEntity.status(e.getErrorResponse().getResponseCode().getStatusCode())), - requestId).body(e.getErrorResponse().getErrorMessage()); } catch (PatternSyntaxException e) { logger.warn(GET_DEPLOYMENTS_FAILED, e); return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.status(HttpStatus.BAD_REQUEST)), requestId) @@ -94,21 +88,12 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 implements Pol */ @Override public ResponseEntity queryDeployedPolicies(String name, UUID requestId) { + Collection result = provider.getStatus(new ToscaConceptIdentifierOptVersion(name, null)); + if (result.isEmpty()) { + return makeNotFoundResponse(requestId); - try { - Collection result = provider.getStatus(new ToscaConceptIdentifierOptVersion(name, null)); - if (result.isEmpty()) { - return makeNotFoundResponse(requestId); - - } else { - return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId).body(result); - } - - } catch (PfModelRuntimeException e) { - logger.warn(GET_DEPLOYMENTS_FAILED, e); - return addLoggingHeaders( - addVersionControlHeaders(ResponseEntity.status(e.getErrorResponse().getResponseCode().getStatusCode())), - requestId).body(e.getErrorResponse().getErrorMessage()); + } else { + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId).body(result); } } @@ -121,22 +106,13 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 implements Pol */ @Override public ResponseEntity queryDeployedPolicy(String name, String version, UUID requestId) { + Collection result = provider.getStatus(new ToscaConceptIdentifierOptVersion(name, version)); + if (result.isEmpty()) { + return makeNotFoundResponse(requestId); - try { - Collection result = provider.getStatus(new ToscaConceptIdentifierOptVersion(name, version)); - if (result.isEmpty()) { - return makeNotFoundResponse(requestId); - - } else { - return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId) - .body(result.iterator().next()); - } - - } catch (PfModelRuntimeException e) { - logger.warn(GET_DEPLOYMENTS_FAILED, e); - return addLoggingHeaders( - addVersionControlHeaders(ResponseEntity.status(e.getErrorResponse().getResponseCode().getStatusCode())), - requestId).body(e.getErrorResponse().getErrorMessage()); + } else { + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId) + .body(result.iterator().next()); } } @@ -149,17 +125,8 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 implements Pol */ @Override public ResponseEntity getStatusOfAllPolicies(UUID requestId) { - - try { - return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId) - .body(provider.getPolicyStatus()); - - } catch (PfModelRuntimeException e) { - logger.warn(GET_DEPLOYMENTS_FAILED, e); - return addLoggingHeaders( - addVersionControlHeaders(ResponseEntity.status(e.getErrorResponse().getResponseCode().getStatusCode())), - requestId).body(e.getErrorResponse().getErrorMessage()); - } + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId) + .body(provider.getPolicyStatus()); } /** @@ -167,16 +134,12 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 implements Pol * policies that match regex * * @param pdpGroupName name of the PdpGroup - * @param requestId request ID used in ONAP logging - * @param regex regex for a policy name + * @param requestId request ID used in ONAP logging + * @param regex regex for a policy name * @return a response */ @Override - public ResponseEntity getStatusOfPoliciesByGroup( - String pdpGroupName, - UUID requestId, - String regex) { - + public ResponseEntity getStatusOfPoliciesByGroup(String pdpGroupName, UUID requestId, String regex) { try { final Collection result; if (regex == null) { @@ -188,11 +151,6 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 implements Pol } return makeListOrNotFoundResponse(requestId, result); - } catch (PfModelRuntimeException e) { - logger.warn(GET_DEPLOYMENTS_FAILED, e); - return addLoggingHeaders( - addVersionControlHeaders(ResponseEntity.status(e.getErrorResponse().getResponseCode().getStatusCode())), - requestId).body(e.getErrorResponse().getErrorMessage()); } catch (PatternSyntaxException e) { logger.warn(GET_DEPLOYMENTS_FAILED, e); return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.status(HttpStatus.BAD_REQUEST)), requestId) @@ -204,32 +162,18 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 implements Pol * Queries status of all versions of a specific policy in a specific PdpGroup. * * @param pdpGroupName name of the PdpGroup - * @param policyName name of the Policy - * @param requestId request ID used in ONAP logging + * @param policyName name of the Policy + * @param requestId request ID used in ONAP logging * @return a response */ @Override - public ResponseEntity getStatusOfPolicies( - String pdpGroupName, - String policyName, - UUID requestId) { - - try { - Collection result = - provider.getPolicyStatus(pdpGroupName, new ToscaConceptIdentifierOptVersion(policyName, null)); - if (result.isEmpty()) { - return makeNotFoundResponse(requestId); - - } else { - return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId) - .body(result); - } - - } catch (PfModelRuntimeException e) { - logger.warn(GET_DEPLOYMENTS_FAILED, e); - return addLoggingHeaders( - addVersionControlHeaders(ResponseEntity.status(e.getErrorResponse().getResponseCode().getStatusCode())), - requestId).body(e.getErrorResponse().getErrorMessage()); + public ResponseEntity getStatusOfPolicies(String pdpGroupName, String policyName, UUID requestId) { + Collection result = + provider.getPolicyStatus(pdpGroupName, new ToscaConceptIdentifierOptVersion(policyName, null)); + if (result.isEmpty()) { + return makeNotFoundResponse(requestId); + } else { + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId).body(result); } } @@ -237,36 +181,24 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 implements Pol /** * Queries status of a specific version of a specific policy in a specific PdpGroup. * - * @param pdpGroupName name of the PdpGroup - * @param policyName name of the Policy + * @param pdpGroupName name of the PdpGroup + * @param policyName name of the Policy * @param policyVersion version of the Policy - * @param requestId request ID used in ONAP logging + * @param requestId request ID used in ONAP logging * @return a response */ @Override - public ResponseEntity getStatusOfPolicy( - String pdpGroupName, - String policyName, - String policyVersion, - UUID requestId) { - - try { - Collection result = provider.getPolicyStatus(pdpGroupName, - new ToscaConceptIdentifierOptVersion(policyName, policyVersion)); - if (result.isEmpty()) { - return makeNotFoundResponse(requestId); - - } else { - return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId) - .body(result.iterator().next()); - } + public ResponseEntity getStatusOfPolicy(String pdpGroupName, String policyName, String policyVersion, + UUID requestId) { + Collection result = provider.getPolicyStatus(pdpGroupName, + new ToscaConceptIdentifierOptVersion(policyName, policyVersion)); + if (result.isEmpty()) { + return makeNotFoundResponse(requestId); - } catch (PfModelRuntimeException e) { - logger.warn(GET_DEPLOYMENTS_FAILED, e); - return addLoggingHeaders( - addVersionControlHeaders(ResponseEntity.status(e.getErrorResponse().getResponseCode().getStatusCode())), - requestId).body(e.getErrorResponse().getErrorMessage()); + } else { + return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId) + .body(result.iterator().next()); } } @@ -278,7 +210,7 @@ public class PolicyStatusControllerV1 extends PapRestControllerV1 implements Pol */ private ResponseEntity makeNotFoundResponse(final UUID requestId) { return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.status(HttpStatus.NOT_FOUND)), requestId) - .build(); + .build(); } private ResponseEntity makeRegexNotFoundResponse(UUID requestId) { 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 631c9c03..ac2c3c8d 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 @@ -4,7 +4,7 @@ * ================================================================================ * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. - * Modifications Copyright (C) 2021 Nordix Foundation. + * Modifications Copyright (C) 2021, 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,6 @@ package org.onap.policy.pap.main.rest; import com.google.re2j.Pattern; import java.util.Collection; import java.util.List; -import java.util.stream.Collectors; import lombok.RequiredArgsConstructor; import org.onap.policy.models.pap.concepts.PolicyStatus; import org.onap.policy.models.pdp.concepts.PdpPolicyStatus; @@ -126,8 +125,8 @@ public class PolicyStatusProvider { * @return the deployment status of the policy */ public Collection getPolicyStatus(String pdpGroupName, ToscaConceptIdentifierOptVersion policy) { - return policyStatusService.getAllPolicyStatus(policy).stream().filter(p -> p.getPdpGroup().equals(pdpGroupName)) - .collect(Collectors.toList()); + return policyStatusService.getAllPolicyStatus(policy).stream() + .filter(p -> p.getPdpGroup().equals(pdpGroupName)).toList(); } /** @@ -154,7 +153,6 @@ public class PolicyStatusProvider { .getPolicy() .getName(); return pattern.matcher(policyName).matches(); - }) - .collect(Collectors.toList()); + }).toList(); } } 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 bd9f6bc6..ce5fdc36 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 @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2022 Bell Canada. All rights reserved. - * Modifications Copyright (C) 2023 Nordix Foundation. + * Modifications Copyright (C) 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,6 @@ import jakarta.ws.rs.core.Response; import java.time.Instant; import java.util.Date; import java.util.List; -import java.util.stream.Collectors; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.onap.policy.common.parameters.BeanValidationResult; @@ -55,7 +54,7 @@ public class PolicyAuditService { * @param audits list of policy audit */ public void createAuditRecords(@NonNull final List audits) { - List jpaAudits = audits.stream().map(JpaPolicyAudit::new).collect(Collectors.toList()); + List jpaAudits = audits.stream().map(JpaPolicyAudit::new).toList(); var result = new BeanValidationResult("createAuditRecords", jpaAudits); @@ -186,6 +185,6 @@ public class PolicyAuditService { } private List asPolicyAuditList(List jpaPolicyAuditList) { - return jpaPolicyAuditList.stream().map(JpaPolicyAudit::toAuthorative).collect(Collectors.toList()); + return jpaPolicyAuditList.stream().map(JpaPolicyAudit::toAuthorative).toList(); } } diff --git a/main/src/main/java/org/onap/policy/pap/main/service/PolicyStatusService.java b/main/src/main/java/org/onap/policy/pap/main/service/PolicyStatusService.java index ac7830d2..d4ade785 100644 --- a/main/src/main/java/org/onap/policy/pap/main/service/PolicyStatusService.java +++ b/main/src/main/java/org/onap/policy/pap/main/service/PolicyStatusService.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2022 Bell Canada. All rights reserved. - * Modifications Copyright (C) 2023 Nordix Foundation. + * Modifications Copyright (C) 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,6 @@ import jakarta.ws.rs.core.Response; import java.util.Collection; import java.util.Collections; import java.util.List; -import java.util.stream.Collectors; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.onap.policy.common.parameters.BeanValidationResult; @@ -70,11 +69,9 @@ public class PolicyStatusService { * @return the policy status list found */ public List getAllPolicyStatus(@NonNull ToscaConceptIdentifierOptVersion policy) { - if (policy.getVersion() != null) { return asPolicyStatusList(policyStatusRepository .findByKeyParentKeyNameAndKeyParentKeyVersion(policy.getName(), policy.getVersion())); - } else { return asPolicyStatusList(policyStatusRepository.findByKeyParentKeyName(policy.getName())); } @@ -84,11 +81,11 @@ public class PolicyStatusService { * Gets all status for a policy in a group. * * @param pdpGroup the group's name - * @param policy the policy + * @param policy the policy * @return the policy status list found */ public List getAllPolicyStatus(@NonNull String pdpGroup, - @NonNull ToscaConceptIdentifierOptVersion policy) { + @NonNull ToscaConceptIdentifierOptVersion policy) { if (policy.getVersion() != null) { return asPolicyStatusList(policyStatusRepository.findByPdpGroupAndKeyParentKeyNameAndKeyParentKeyVersion( pdpGroup, policy.getName(), policy.getVersion())); @@ -106,7 +103,7 @@ public class PolicyStatusService { * @param deleteObjs the objects to delete */ public void cudPolicyStatus(Collection createObjs, Collection updateObjs, - Collection deleteObjs) { + Collection deleteObjs) { try { policyStatusRepository.deleteAll(fromAuthorativeStatus(deleteObjs, "deletePdpPolicyStatusList")); policyStatusRepository.saveAll(fromAuthorativeStatus(createObjs, "createPdpPolicyStatusList")); @@ -121,7 +118,7 @@ public class PolicyStatusService { * Converts a collection of authorative policy status to a collection of JPA policy * status. Validates the resulting list. * - * @param objs authorative policy status to convert + * @param objs authorative policy status to convert * @param fieldName name of the field containing the collection * @return a list of JPA policy status */ @@ -130,7 +127,7 @@ public class PolicyStatusService { return Collections.emptyList(); } - List jpas = objs.stream().map(JpaPdpPolicyStatus::new).collect(Collectors.toList()); + List jpas = objs.stream().map(JpaPdpPolicyStatus::new).toList(); // validate the objects var result = new BeanValidationResult(fieldName, jpas); @@ -148,6 +145,6 @@ public class PolicyStatusService { } private List asPolicyStatusList(List jpaPdpPolicyStatusList) { - return jpaPdpPolicyStatusList.stream().map(JpaPdpPolicyStatus::toAuthorative).collect(Collectors.toList()); + return jpaPdpPolicyStatusList.stream().map(JpaPdpPolicyStatus::toAuthorative).toList(); } } 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 222f240c..f992ebe6 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 @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2022 Bell Canada. All rights reserved. - * Modifications Copyright (C) 2022-2023 Nordix Foundation. + * Modifications Copyright (C) 2022-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,6 @@ import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.stream.Collectors; import lombok.RequiredArgsConstructor; import org.onap.policy.models.base.PfConceptKey; import org.onap.policy.models.base.PfModelException; @@ -63,12 +62,11 @@ public class ToscaServiceTemplateService { /** * Get policies. * - * @param name the name of the policy to get, null to get all policies + * @param name the name of the policy to get, null to get all policies * @param version the version of the policy to get, null to get all versions of a policy * @return the policies found - * @throws PfModelException on errors getting policies */ - public List getPolicyList(final String name, final String version) throws PfModelException { + public List getPolicyList(final String name, final String version) { LOGGER.debug("->getPolicyList: name={}, version={}", name, version); @@ -77,7 +75,7 @@ public class ToscaServiceTemplateService { try { List> policies = getToscaServiceTemplate(name, version, "policy").toAuthorative() .getToscaTopologyTemplate().getPolicies(); - policyList = policies.stream().flatMap(policy -> policy.values().stream()).collect(Collectors.toList()); + policyList = policies.stream().flatMap(policy -> policy.values().stream()).toList(); populateMetadataSet(policyList); } catch (PfModelRuntimeException pfme) { return handlePfModelRuntimeException(pfme); @@ -105,7 +103,7 @@ public class ToscaServiceTemplateService { /** * Get policy types. * - * @param name the name of the policy type to get, set to null to get all policy types + * @param name the name of the policy type to get, set to null to get all policy types * @param version the version of the policy type to get, set to null to get all versions * @return the policy types found * @throws PfModelException on errors getting policy types @@ -152,7 +150,8 @@ public class ToscaServiceTemplateService { } private JpaToscaServiceTemplate getToscaPolicies(final String name, final String version, - JpaToscaServiceTemplate dbServiceTemplate) throws PfModelException { + JpaToscaServiceTemplate dbServiceTemplate) + throws PfModelException { if (!ToscaUtils.doPoliciesExist(dbServiceTemplate)) { throw new PfModelRuntimeException(Response.Status.NOT_FOUND, "policies for " + name + ":" + version + " do not exist"); @@ -166,7 +165,8 @@ public class ToscaServiceTemplateService { } private JpaToscaServiceTemplate getToscaPolicyTypes(final String name, final String version, - JpaToscaServiceTemplate dbServiceTemplate) throws PfModelException { + JpaToscaServiceTemplate dbServiceTemplate) + throws PfModelException { if (!ToscaUtils.doPolicyTypesExist(dbServiceTemplate)) { throw new PfModelRuntimeException(Response.Status.NOT_FOUND, "policy types for " + name + ":" + version + " do not exist"); 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 790d9517..aeb1f189 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 @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019, 2023 Nordix Foundation. + * Copyright (C) 2019, 2023-2024 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ @@ -34,7 +34,6 @@ import org.onap.policy.pap.main.PolicyPapException; 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.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Component; @@ -52,8 +51,7 @@ public class PapDatabaseInitializer { private final StandardCoder standardCoder; - @Autowired - private PdpGroupService pdpGroupService; + private final PdpGroupService pdpGroupService; @Value("${group-config-file:PapDb.json}") private String groupConfigFile; @@ -61,7 +59,8 @@ public class PapDatabaseInitializer { /** * Constructs the object. */ - public PapDatabaseInitializer() { + public PapDatabaseInitializer(PdpGroupService pdpGroupService) { + this.pdpGroupService = pdpGroupService; standardCoder = new StandardCoder(); } diff --git a/main/src/test/java/org/onap/policy/pap/main/comm/PdpModifyRequestMapTest.java b/main/src/test/java/org/onap/policy/pap/main/comm/PdpModifyRequestMapTest.java index 7290be7a..57fc5e94 100644 --- a/main/src/test/java/org/onap/policy/pap/main/comm/PdpModifyRequestMapTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/comm/PdpModifyRequestMapTest.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2020-2021, 2023 Nordix Foundation. + * Modifications Copyright (C) 2020-2021, 2023-2024 Nordix Foundation. * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -438,13 +438,6 @@ class PdpModifyRequestMapTest extends CommonRequestBase { assertThatCode(map::removeExpiredPdps).doesNotThrowAnyException(); } - @Test - void testRemoveExpiredPdps_DaoRtEx() { - when(pdpGroupService.getFilteredPdpGroups(any())).thenThrow(makeRuntimeException()); - - assertThatCode(map::removeExpiredPdps).doesNotThrowAnyException(); - } - @Test void testRemoveFromSubgroup() { PdpGroup group = makeGroup(MY_GROUP); @@ -603,20 +596,6 @@ class PdpModifyRequestMapTest extends CommonRequestBase { assertEquals(2, map.nalloc); } - @Test - void testRequestCompleted_LastRequest() { - map.addRequest(change); - - // invoke the method - invokeSuccessHandler(); - - verify(requests, never()).stopPublishing(); - - // requests should have been removed from the map so this should allocate another - map.addRequest(update); - assertEquals(2, map.nalloc); - } - @Test void testRequestCompleted_NameMismatch() { // use a different name @@ -790,7 +769,6 @@ class PdpModifyRequestMapTest extends CommonRequestBase { public MyMap(PdpModifyRequestMapParams params) { super(pdpGroupService, policyStatusService, responseHandler, undeployer, notifier); super.initialize(params); - ; } @Override diff --git a/main/src/test/java/org/onap/policy/pap/main/comm/TimerManagerTest.java b/main/src/test/java/org/onap/policy/pap/main/comm/TimerManagerTest.java index 6d4ac025..67f3d363 100644 --- a/main/src/test/java/org/onap/policy/pap/main/comm/TimerManagerTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/comm/TimerManagerTest.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2023 Nordix Foundation. + * Modifications Copyright (C) 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,13 +51,14 @@ class TimerManagerTest extends Threaded { * This is a field rather than a local variable to prevent checkstyle from complaining * about the distance between its assignment and its use. */ - private long tcur; + private long tcur1; /** * Sets up. * * @throws Exception if an error occurs */ + @Override @BeforeEach public void setUp() throws Exception { super.setUp(); @@ -65,13 +66,8 @@ class TimerManagerTest extends Threaded { mgr = new MyManager(MGR_NAME, MGR_TIMEOUT_MS); } - @AfterEach - public void tearDown() throws Exception { - super.tearDown(); - } - @Override - protected void stopThread() throws Exception { + protected void stopThread() { if (mgr != null) { mgr.stop(); mgr.allowSleep(10); @@ -149,26 +145,6 @@ class TimerManagerTest extends Threaded { mgr.awaitSleep(); } - @Test - void testProcessTimer_StopWhileWaiting() throws Exception { - startThread(mgr); - mgr.register(NAME1, mgr::addToQueue); - mgr.awaitSleep(); - mgr.allowSleep(1); - - mgr.registerNewTime(NAME2, mgr::addToQueue); - mgr.awaitSleep(); - - mgr.stop(); - mgr.allowSleep(1); - - assertTrue(waitStop()); - - // should have stopped after processing the first timer - assertEquals(NAME1, mgr.pollTimer()); - assertNull(mgr.pollTimer()); - } - @Test void testProcessTimer_CancelWhileWaiting() throws Exception { startThread(mgr); @@ -220,7 +196,7 @@ class TimerManagerTest extends Threaded { mgr.register(NAME2, mgr::addToQueue); mgr.awaitSleep(); - tcur = mgr.currentTimeMillis(); + tcur1 = mgr.currentTimeMillis(); mgr.allowSleep(1); @@ -229,7 +205,7 @@ class TimerManagerTest extends Threaded { mgr.awaitSleep(); long tcur2 = mgr.currentTimeMillis(); - assertTrue(tcur2 >= tcur + MGR_TIMEOUT_MS); + assertTrue(tcur2 >= tcur1 + MGR_TIMEOUT_MS); assertEquals(NAME1, mgr.pollTimer()); assertEquals(NAME2, mgr.pollTimer()); @@ -321,18 +297,15 @@ class TimerManagerTest extends Threaded { * current time when determining the expiration time, we have to temporarily * fiddle with {@link #curTime}, but we leave it unchanged when we're done. * Increases the {@link #offset} each time it's invoked. - * - * @return the new timer */ - public Timer registerNewTime(String timerName, Consumer action) { + public void registerNewTime(String timerName, Consumer action) { synchronized (lockit) { offset++; curTime += offset; - Timer timer = super.register(timerName, action); + super.register(timerName, action); curTime -= offset; - return timer; } } diff --git a/main/src/test/java/org/onap/policy/pap/main/comm/msgdata/UpdateReqTest.java b/main/src/test/java/org/onap/policy/pap/main/comm/msgdata/UpdateReqTest.java index 7d62c7ef..b5db3013 100644 --- a/main/src/test/java/org/onap/policy/pap/main/comm/msgdata/UpdateReqTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/comm/msgdata/UpdateReqTest.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021, 2023 Nordix Foundation. + * Modifications Copyright (C) 2021, 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,7 +74,7 @@ class UpdateReqTest extends CommonRequestBase { response.setPdpSubgroup(update.getPdpSubgroup()); response.setPolicies( update.getPoliciesToBeDeployed().stream().map(ToscaPolicy::getIdentifier) - .collect(Collectors.toList())); + .toList()); data = new UpdateReq(reqParams, MY_REQ_NAME, update); data.setNotifier(notifier); @@ -153,7 +153,7 @@ class UpdateReqTest extends CommonRequestBase { ArrayList policies = new ArrayList<>(update.getPoliciesToBeDeployed()); policies.set(0, makePolicy(DIFFERENT, "10.0.0")); - response.setPolicies(policies.stream().map(ToscaPolicy::getIdentifier).collect(Collectors.toList())); + response.setPolicies(policies.stream().map(ToscaPolicy::getIdentifier).toList()); assertEquals("policies do not match", data.checkResponse(response)); verifyResponse(); @@ -243,7 +243,7 @@ class UpdateReqTest extends CommonRequestBase { policies = new ArrayList<>(update.getPoliciesToBeDeployed()); List polsToUndep = policies.parallelStream() .map(ToscaPolicy::getIdentifier) - .collect(Collectors.toList()); + .toList(); msg2.setPoliciesToBeUndeployed(polsToUndep); assertTrue(data.reconfigure(msg2)); @@ -267,8 +267,7 @@ class UpdateReqTest extends CommonRequestBase { // some items in both undeploy and newMessage.deploy policies = new ArrayList<>(update.getPoliciesToBeDeployed()); List polsToUndep2 = policies.parallelStream() - .map(ToscaPolicy::getIdentifier) - .collect(Collectors.toList()); + .map(ToscaPolicy::getIdentifier).toList(); data.getMessage().setPoliciesToBeUndeployed(polsToUndep2); List polsToDep2 = new LinkedList<>(); @@ -280,13 +279,12 @@ class UpdateReqTest extends CommonRequestBase { List dataPols2 = data.getMessage().getPoliciesToBeDeployed().stream() .map(ToscaPolicy::getIdentifier) - .collect(Collectors.toList()); + .toList(); assertThat(data.getMessage().getPoliciesToBeUndeployed()) .doesNotContainAnyElementsOf(dataPols2); // some items only in undeploy - pols = policies.stream().map(ToscaPolicy::getIdentifier) - .collect(Collectors.toList()); + pols = policies.stream().map(ToscaPolicy::getIdentifier).toList(); msg2.setPoliciesToBeUndeployed(pols); data.getMessage().setPoliciesToBeUndeployed(new LinkedList<>()); assertTrue(data.reconfigure(msg2)); diff --git a/main/src/test/java/org/onap/policy/pap/main/notification/PolicyNotifierTest.java b/main/src/test/java/org/onap/policy/pap/main/notification/PolicyNotifierTest.java index 69c74205..8196dd73 100644 --- a/main/src/test/java/org/onap/policy/pap/main/notification/PolicyNotifierTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/notification/PolicyNotifierTest.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021, 2023 Nordix Foundation. + * Modifications Copyright (C) 2021, 2023-2024 Nordix Foundation. * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -27,6 +27,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -38,25 +39,23 @@ import java.util.Set; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.onap.policy.common.utils.services.Registry; -import org.onap.policy.models.base.PfModelException; import org.onap.policy.models.base.PfModelRuntimeException; import org.onap.policy.models.pap.concepts.PolicyNotification; import org.onap.policy.models.pap.concepts.PolicyStatus; import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier; import org.onap.policy.pap.main.PapConstants; -import org.onap.policy.pap.main.PolicyPapRuntimeException; import org.onap.policy.pap.main.comm.Publisher; import org.onap.policy.pap.main.comm.QueueToken; import org.onap.policy.pap.main.service.PolicyStatusService; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) class PolicyNotifierTest { private static final String GROUP_A = "groupA"; private static final String PDP1 = "pdp-1"; @@ -85,14 +84,9 @@ class PolicyNotifierTest { @BeforeEach public void setUp() { closeable = MockitoAnnotations.openMocks(this); - try { - when(policyStatusService.getGroupPolicyStatus(anyString())).thenReturn(Collections.emptyList()); - Registry.registerOrReplace(PapConstants.REG_METER_REGISTRY, new SimpleMeterRegistry()); - notifier = new MyNotifier(publisher); - - } catch (PfModelException e) { - throw new PolicyPapRuntimeException(e); - } + lenient().when(policyStatusService.getGroupPolicyStatus(anyString())).thenReturn(Collections.emptyList()); + Registry.registerOrReplace(PapConstants.REG_METER_REGISTRY, new SimpleMeterRegistry()); + notifier = new MyNotifier(publisher); } @AfterEach @@ -164,7 +158,7 @@ class PolicyNotifierTest { private class MyNotifier extends PolicyNotifier { - public MyNotifier(Publisher publisher) throws PfModelException { + public MyNotifier(Publisher publisher) { super(policyStatusService); super.setPublisher(publisher); } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java b/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java index fe22cd89..f976d597 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/CommonPapRestServer.java @@ -1,6 +1,6 @@ /* * ============LICENSE_START======================================================= - * Copyright (C) 2019, 2023 Nordix Foundation. + * Copyright (C) 2019, 2023-2024 Nordix Foundation. * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property. * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ @@ -87,6 +87,8 @@ public abstract class CommonPapRestServer { private boolean activatorWasAlive; protected String httpsPrefix; + protected Client client; + @LocalServerPort private int port; @@ -134,6 +136,9 @@ public abstract class CommonPapRestServer { @AfterEach public void tearDown() { markActivator(activatorWasAlive); + if (client != null) { + client.close(); + } } @AfterAll @@ -181,6 +186,7 @@ public abstract class CommonPapRestServer { Object manager = ReflectionTestUtils.getField(papActivator, "serviceManager"); AtomicBoolean running = (AtomicBoolean) ReflectionTestUtils .getField(Objects.requireNonNull(manager), "running"); + assert running != null; running.set(wasAlive); } @@ -193,8 +199,10 @@ public abstract class CommonPapRestServer { */ protected void checkUnauthRequest(final String endpoint, Function sender) throws Exception { - assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), - sender.apply(sendNoAuthRequest(endpoint)).getStatus()); + var resp = sender.apply(sendNoAuthRequest(endpoint)); + assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(), resp.getStatus()); + resp.close(); + } /** @@ -245,7 +253,7 @@ public abstract class CommonPapRestServer { sc.init(null, NetworkUtil.getAlwaysTrustingManager(), new SecureRandom()); final ClientBuilder clientBuilder = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier((host, session) -> true); - final Client client = clientBuilder.build(); + client = clientBuilder.build(); client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true"); client.register((mediaType.equalsIgnoreCase(MediaType.APPLICATION_JSON) ? GsonMessageBodyHandler.class diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/ProviderSuper.java b/main/src/test/java/org/onap/policy/pap/main/rest/ProviderSuper.java index e5a83305..98ce4034 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/ProviderSuper.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/ProviderSuper.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021-2023 Nordix Foundation. + * Modifications Copyright (C) 2021-2024 Nordix Foundation. * Modifications Copyright (C) 2022-2023 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -102,7 +102,7 @@ public class ProviderSuper { * Configures DAO, captors, and various mocks. */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { Registry.newRegistry(); @@ -111,7 +111,7 @@ public class ProviderSuper { reqmap = mock(PdpModifyRequestMap.class); lockit = new Object(); - policy1 = loadPolicy("policy.json"); + policy1 = loadPolicy(); meterRegistry = mock(MeterRegistry.class); @@ -267,21 +267,19 @@ public class ProviderSuper { /** * Loads a policy. * - * @param fileName name of the file from which to load * @return a policy */ - protected ToscaPolicy loadPolicy(String fileName) { - return loadFile(fileName, ToscaPolicy.class); + protected ToscaPolicy loadPolicy() { + return loadFile("policy.json", ToscaPolicy.class); } /** * Loads a policy type. * - * @param fileName name of the file from which to load * @return a policy type */ - protected ToscaPolicyType loadPolicyType(String fileName) { - return loadFile(fileName, ToscaPolicyType.class); + protected ToscaPolicyType loadPolicyType() { + return loadFile("daoPolicyType.json", ToscaPolicyType.class); } /** diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateProvider.java index 445a921f..b96b53fb 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupCreateOrUpdateProvider.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP PAP * ================================================================================ - * Copyright (C) 2019-2021, 2023 Nordix Foundation. + * Copyright (C) 2019-2021, 2023-2024 Nordix Foundation. * Modifications Copyright (C) 2021 AT&T Intellectual Property. * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ @@ -33,7 +33,6 @@ import static org.mockito.Mockito.when; import jakarta.ws.rs.core.Response.Status; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.TreeMap; @@ -68,17 +67,19 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { /** * Configures mocks and objects. - * - * @throws Exception if an error occurs */ @BeforeEach @Override - public void setUp() throws Exception { + public void setUp() { super.setUp(); prov = new PdpGroupCreateOrUpdateProvider(); super.initialize(prov); - when(toscaService.getPolicyTypeList("typeA", "100.2.3")) - .thenReturn(Arrays.asList(loadPolicyType("daoPolicyType.json"))); + try { + when(toscaService.getPolicyTypeList("typeA", "100.2.3")) + .thenReturn(Collections.singletonList(loadPolicyType())); + } catch (PfModelException e) { + throw new RuntimeException(e); + } } @Test @@ -90,7 +91,7 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { } @Test - void testCreateOrUpdateGroups_InvalidRequest() throws Exception { + void testCreateOrUpdateGroups_InvalidRequest() { assertThatThrownBy(() -> prov.createOrUpdateGroups(new PdpGroups())).isInstanceOf(PfModelException.class) .hasMessageContaining("is null"); @@ -98,7 +99,7 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { } @Test - void testCreateOrUpdate_Invalid() throws Exception { + void testCreateOrUpdate_Invalid() { PdpGroups groups = loadPdpGroups("createGroups.json"); groups.getGroups().get(0).setPdpGroupState(PdpState.TERMINATED); @@ -123,18 +124,7 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { } @Test - void testAddGroup_Invalid() throws Exception { - PdpGroups groups = loadPdpGroups("createGroups.json"); - groups.getGroups().get(0).setPdpGroupState(PdpState.TERMINATED); - - assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) - .hasMessageContaining("pdpGroupState"); - - assertNoGroupAction(); - } - - @Test - void testAddGroup_InvalidSubGroup() throws Exception { + void testAddGroup_InvalidSubGroup() { PdpGroups groups = loadPdpGroups("createGroups.json"); groups.getGroups().get(0).getPdpSubgroups().get(0).getSupportedPolicyTypes().get(0).setVersion("99.99.99"); @@ -181,7 +171,7 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { // DB group = new group PdpGroup group = new PdpGroup(groups.getGroups().get(0)); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); prov.createOrUpdateGroups(groups); @@ -189,13 +179,13 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { } @Test - void testUpdateGroup_PropertiesChanged() throws Exception { + void testUpdateGroup_PropertiesChanged() { PdpGroups groups = loadPdpGroups("createGroups.json"); PdpGroup group = new PdpGroup(groups.getGroups().get(0)); group.setProperties(new TreeMap<>()); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); assertThatThrownBy(() -> prov.createOrUpdateGroups(groups)).isInstanceOf(PfModelException.class) .hasMessageContaining("properties"); @@ -209,7 +199,7 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { PdpGroup newgrp = groups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); group.setDescription("old description"); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); prov.createOrUpdateGroups(groups); @@ -225,7 +215,7 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { PdpGroup newgrp = groups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); group.setPdpGroupState(PdpState.TEST); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); prov.createOrUpdateGroups(groups); @@ -239,7 +229,7 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { void testUpdateGroup_NewSubGroup() throws Exception { PdpGroups groups = loadPdpGroups("createGroupsNewSub.json"); PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); prov.createOrUpdateGroups(groups); @@ -253,7 +243,7 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { PdpGroups groups = loadPdpGroups("createGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); // something different in this subgroup group.getPdpSubgroups().get(0).setDesiredInstanceCount(10); @@ -267,7 +257,7 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { @Test void testUpdateGroup_notifyPdpsDelSubGroups() throws Exception { PdpGroup dbgroup = new PdpGroup(loadPdpGroups("createGroupsDelSub.json").getGroups().get(0)); - when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); + when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(List.of(dbgroup)); PdpGroups groups = loadPdpGroups("createGroups.json"); @@ -322,7 +312,7 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { PdpGroups groups = loadPdpGroups("createGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); prov.createOrUpdateGroups(groups); @@ -334,7 +324,7 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { PdpGroups groups = loadPdpGroups("createGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); group.setDescription(null); @@ -349,7 +339,7 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { PdpGroups groups = loadPdpGroups("createGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); newgrp.setDescription(null); @@ -364,7 +354,7 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { PdpGroups groups = loadPdpGroups("createGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); newgrp.setDescription(group.getDescription() + "-changed"); @@ -378,7 +368,7 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { void testAddSubGroup() throws Exception { PdpGroups groups = loadPdpGroups("createGroupsNewSub.json"); PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); prov.createOrUpdateGroups(groups); @@ -404,7 +394,7 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { PdpGroups groups = loadPdpGroups("createGroupsWildCard.json"); PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); prov.createOrUpdateGroups(groups); @@ -421,7 +411,7 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { void testAddSubGroup_ValidationPolicyTypeNotFound() throws Exception { PdpGroups groups = loadPdpGroups("createGroupsNewSub.json"); PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); when(toscaService.getPolicyTypeList(any(), any())).thenReturn(Collections.emptyList()); @@ -432,7 +422,7 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { void testAddSubGroup_ValidationPolicyTypeDaoEx() throws Exception { PdpGroups groups = loadPdpGroups("createGroupsNewSub.json"); PdpGroup group = loadPdpGroups("createGroups.json").getGroups().get(0); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); PfModelException exc = new PfModelException(Status.CONFLICT, EXPECTED_EXCEPTION); when(toscaService.getPolicyTypeList(any(), any())).thenThrow(exc); @@ -445,7 +435,7 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { PdpGroups groups = loadPdpGroups("createGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); PdpGroup dbgroup = new PdpGroup(newgrp); - when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(Arrays.asList(dbgroup)); + when(pdpGroupService.getPdpGroups(dbgroup.getName())).thenReturn(List.of(dbgroup)); when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json")) .thenReturn(loadPolicies("daoPolicyList.json")).thenReturn(loadPolicies("createGroupNewPolicy.json")); @@ -461,11 +451,11 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { } @Test - void testUpdateSubGroup_Invalid() throws Exception { + void testUpdateSubGroup_Invalid() { PdpGroups groups = loadPdpGroups("createGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); // change properties newgrp.getPdpSubgroups().get(0).setProperties(new TreeMap<>()); @@ -481,7 +471,7 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { PdpGroups groups = loadPdpGroups("createGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); newgrp.getPdpSubgroups().get(0).getSupportedPolicyTypes() .add(new ToscaConceptIdentifier("typeX.*", "9.8.7")); @@ -500,7 +490,7 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { PdpGroups groups = loadPdpGroups("createGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); newgrp.getPdpSubgroups().get(0).setDesiredInstanceCount(20); @@ -515,7 +505,7 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { PdpGroups groups = loadPdpGroups("createGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); prov.createOrUpdateGroups(groups); @@ -532,11 +522,11 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { } @Test - void testValidateSubGroup_PropertiesMismatch() throws Exception { + void testValidateSubGroup_PropertiesMismatch() { PdpGroups groups = loadPdpGroups("createGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); PdpGroup group = new PdpGroup(newgrp); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group)); + when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); newgrp.setProperties(new TreeMap<>()); @@ -546,17 +536,17 @@ public class TestPdpGroupCreateOrUpdateProvider extends ProviderSuper { assertNoGroupAction(); } - private void assertNoGroupAction() throws Exception { + private void assertNoGroupAction() { verify(pdpGroupService, never()).createPdpGroups(any()); verify(pdpGroupService, never()).updatePdpGroups(any()); verify(reqmap, never()).addRequest(any(), any()); } - private void assertGroupUpdateOnly(PdpGroup group) throws Exception { + private void assertGroupUpdateOnly(PdpGroup group) { verify(pdpGroupService, never()).createPdpGroups(any()); verify(reqmap, never()).addRequest(any(), any()); List updates = getGroupUpdates(); - assertEquals(Arrays.asList(group), updates); + assertEquals(Collections.singletonList(group), updates); } } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java index aff3fa2b..23a62f8d 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2020-2023 Nordix Foundation. + * Modifications Copyright (C) 2020-2024 Nordix Foundation. * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -78,12 +78,10 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { /** * Configures mocks and objects. - * - * @throws Exception if an error occurs */ @BeforeEach @Override - public void setUp() throws Exception { + public void setUp() { super.setUp(); prov = new MyProvider(); super.initialize(prov); @@ -187,7 +185,7 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { } @Test - void testUndeployPolicy_DaoEx() throws Exception { + void testUndeployPolicy_DaoEx() throws PfModelException { PfModelException exc = new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION); prov = spy(prov); @@ -197,7 +195,7 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { } @Test - void testUndeployPolicy_RtEx() throws Exception { + void testUndeployPolicy_RtEx() throws PfModelException { RuntimeException exc = new RuntimeException(EXPECTED_EXCEPTION); prov = spy(prov); @@ -279,7 +277,7 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper { @Override protected void processPolicy(SessionData data, ToscaConceptIdentifierOptVersion desiredPolicy) - throws PfModelException { + throws PfModelException { // NOSONAR // do nothing } } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java index 0de42396..6b9ecafa 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021, 2023 Nordix Foundation. + * Modifications Copyright (C) 2021, 2023-2024 Nordix Foundation. * Modifications Copyright (C) 2021-2023 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -80,19 +80,22 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { /** * Configures mocks and objects. * - * @throws Exception if an error occurs */ @Override @BeforeEach - public void setUp() throws Exception { + public void setUp() { super.setUp(); prov = new PdpGroupDeployProvider(); super.initialize(prov); - when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList2.json")); - when(toscaService.getPolicyTypeList("typeA", "100.2.3")) - .thenReturn(List.of(loadPolicyType("daoPolicyType.json"))); + try { + when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList2.json")); + when(toscaService.getPolicyTypeList("typeA", "100.2.3")) + .thenReturn(List.of(loadPolicyType())); + } catch (PfModelException e) { + throw new RuntimeException(e); + } } /** @@ -229,7 +232,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test - void testUpdateGroupPolicies_InvalidRequest() throws Exception { + void testUpdateGroupPolicies_InvalidRequest() { assertThatThrownBy(() -> prov.updateGroupPolicies(new DeploymentGroups(), DEFAULT_USER)) .isInstanceOf(PfModelException.class).hasMessageContaining("is null"); @@ -237,7 +240,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test - void testUpdateGroup_UnknownGroup() throws Exception { + void testUpdateGroup_UnknownGroup() { PdpGroups groups = loadPdpGroups("deployGroups.json"); String groupName = groups.getGroups().get(0).getName(); @@ -266,7 +269,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test - void testUpdateGroup_NewSubGroup() throws Exception { + void testUpdateGroup_NewSubGroup() { PdpGroups groups = loadPdpGroups("createGroupsNewSub.json"); PdpGroup group = loadPdpGroups("deployGroups.json").getGroups().get(0); when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); @@ -278,22 +281,6 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { assertNoGroupAction(); } - @Test - void testUpdateGroup_UpdatedSubGroup() throws Exception { - PdpGroups groups = loadPdpGroups("deployGroups.json"); - PdpGroup newgrp = groups.getGroups().get(0); - PdpGroup group = new PdpGroup(newgrp); - when(pdpGroupService.getPdpGroups(group.getName())).thenReturn(List.of(group)); - - // something different in this subgroup - group.getPdpSubgroups().get(0).getPolicies().add(new ToscaConceptIdentifier(POLICY2_NAME, POLICY2_VERSION)); - - prov.updateGroupPolicies(toDeploymentGroups(groups), DEFAULT_USER); - - assertEquals(newgrp.toString(), group.toString()); - assertGroupUpdate(group, group.getPdpSubgroups().get(0)); - } - @Test void testUpdateSubGroup_Invalid() throws Exception { PdpGroups groups = loadPdpGroups("deployGroups.json"); @@ -381,7 +368,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { } @Test - void testUpdateSubGroup_PolicyVersionPrefixMismatch() throws Exception { + void testUpdateSubGroup_PolicyVersionPrefixMismatch() { PdpGroups groups = loadPdpGroups("deployGroups.json"); PdpGroup newgrp = groups.getGroups().get(0); @@ -530,7 +517,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { assertGroup(getGroupUpdates(), GROUP1_NAME); List requests = getUpdateRequests(1); - assertUpdate(requests, GROUP1_NAME, PDP2_TYPE, PDP2); + assertUpdate(requests, PDP2_TYPE, PDP2); // nothing is complete - notification should be empty checkEmptyNotification(); @@ -587,8 +574,8 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { assertGroup(getGroupUpdates(), GROUP1_NAME); List requests = getUpdateRequests(2); - assertUpdate(requests, GROUP1_NAME, PDP2_TYPE, PDP2); - assertUpdate(requests, GROUP1_NAME, PDP4_TYPE, PDP4); + assertUpdate(requests, PDP2_TYPE, PDP2); + assertUpdate(requests, PDP4_TYPE, PDP4); // nothing is complete - notification should be empty checkEmptyNotification(); @@ -624,11 +611,11 @@ public class TestPdpGroupDeployProvider extends ProviderSuper { verify(reqmap, never()).addRequest(any(PdpUpdate.class)); } - protected void assertUpdate(List updates, String groupName, String pdpType, String pdpName) { + protected void assertUpdate(List updates, String pdpType, String pdpName) { PdpUpdate update = updates.remove(0); - assertEquals(groupName, update.getPdpGroup()); + assertEquals(TestPdpGroupDeployProvider.GROUP1_NAME, update.getPdpGroup()); assertEquals(pdpType, update.getPdpSubgroup()); assertEquals(pdpName, update.getName()); assertThat(update.getPoliciesToBeDeployed()).contains(policy1); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckProvider.java index dff023cc..59aa6d2f 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupHealthCheckProvider.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019, 2023 Nordix Foundation. + * Copyright (C) 2019, 2023-2024 Nordix Foundation. * Modifications Copyright (C) 2020-2022 Bell Canada. All rights reserved. * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ @@ -65,7 +65,7 @@ class TestPdpGroupHealthCheckProvider { * Configures DAO and mocks. */ @BeforeEach - public void setUp() throws Exception { + public void setUp() { autoCloseable = MockitoAnnotations.openMocks(this); Registry.newRegistry(); groups = loadFile().getGroups(); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupStateChangeControllerV1.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupStateChangeControllerV1.java index 0701bd97..6343d198 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupStateChangeControllerV1.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupStateChangeControllerV1.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019, 2022-2023 Nordix Foundation. + * Copyright (C) 2019, 2022-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,7 @@ package org.onap.policy.pap.main.rest; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; @@ -55,12 +56,19 @@ class TestPdpGroupStateChangeControllerV1 extends CommonPapRestServer { assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus()); assertNull(resp.getErrorDetails()); - rawresp = invocationBuilder.put(Entity.json("")); - resp = rawresp.readEntity(PdpGroupStateChangeResponse.class); - assertEquals(Response.Status.OK.getStatusCode(), rawresp.getStatus()); - assertNull(resp.getErrorDetails()); - // verify it fails when no authorization info is included checkUnauthRequest(uri, req -> req.put(Entity.json(""))); + rawresp.close(); + } + + @Test + void testChangeGroupState_Exception() throws Exception { + final String uri = GROUP_ENDPOINT + "/my-name?state=TEST"; + + final Invocation.Builder invocationBuilder = sendRequest(uri); + Response rawresp = invocationBuilder.put(Entity.json("")); + assertThat(rawresp.getStatusInfo().getStatusCode()) + .isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + rawresp.close(); } } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditManager.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditManager.java index 12b9b351..9fa5948d 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditManager.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditManager.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2021, 2023 Nordix Foundation. + * Copyright (C) 2021, 2023-2024 Nordix Foundation. * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -46,11 +46,11 @@ public class TestPolicyAuditManager extends ProviderSuper { PolicyAuditManager auditManager; /** - * Setup the test variables. + * Set up the test variables. */ @Override @BeforeEach - public void setUp() throws Exception { + public void setUp() { super.setUp(); auditManager = new PolicyAuditManager(policyAuditService); } @@ -77,9 +77,7 @@ public class TestPolicyAuditManager extends ProviderSuper { @Test void testSaveRecordsToDb_EmptyList() { assertThat(auditManager.getAuditRecords()).isEmpty(); - ; auditManager.saveRecordsToDb(); - assertThatCode(() -> auditManager.saveRecordsToDb()).doesNotThrowAnyException(); } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusProvider.java index 0455f3f0..0eb4e7fc 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusProvider.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyStatusProvider.java @@ -4,7 +4,7 @@ * ================================================================================ * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. - * Modifications Copyright (C) 2021, 2023 Nordix Foundation. + * Modifications Copyright (C) 2021, 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,11 +73,10 @@ public class TestPolicyStatusProvider extends ProviderSuper { /** * Configures mocks and objects. * - * @throws Exception if an error occurs */ @Override @BeforeEach - public void setUp() throws Exception { + public void setUp() { super.setUp(); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyUndeployerImpl.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyUndeployerImpl.java index ccd083cc..ccd0fe46 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyUndeployerImpl.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyUndeployerImpl.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021, 2023 Nordix Foundation. + * Modifications Copyright (C) 2021, 2023-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,11 +74,10 @@ public class TestPolicyUndeployerImpl extends ProviderSuper { /** * Configures mocks and objects. * - * @throws Exception if an error occurs */ @Override @BeforeEach - public void setUp() throws Exception { + public void setUp() { super.setUp(); @@ -106,8 +105,12 @@ public class TestPolicyUndeployerImpl extends ProviderSuper { group.setPdpSubgroups(List.of(subgroup0, subgroup)); - when(session.getGroup(MY_GROUP)).thenReturn(group); - when(session.getPolicy(any())).thenReturn(policy1); + try { + when(session.getGroup(MY_GROUP)).thenReturn(group); + when(session.getPolicy(any())).thenReturn(policy1); + } catch (PfModelException e) { + throw new RuntimeException(e); + } prov = new MyProvider(); } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java index 9a95590e..70d25fde 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021, 2023 Nordix Foundation. + * Modifications Copyright (C) 2021, 2023-2024 Nordix Foundation. * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -78,15 +78,18 @@ public class TestProviderBase extends ProviderSuper { /** * Configures mocks and objects. * - * @throws Exception if an error occurs */ @Override @BeforeEach - public void setUp() throws Exception { + public void setUp() { super.setUp(); prov = new MyProvider(); super.initialize(prov); - when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json")); + try { + when(toscaService.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json")); + } catch (PfModelException e) { + throw new RuntimeException(e); + } } @Test @@ -101,13 +104,13 @@ public class TestProviderBase extends ProviderSuper { assertGroup(getGroupUpdates(), GROUP1_NAME); - assertUpdate(getUpdateRequests(1), GROUP1_NAME, PDP1_TYPE, PDP1); + assertUpdate(getUpdateRequests(1), PDP1_TYPE, PDP1); checkEmptyNotification(); } @Test - void testProcess_PfRtEx() throws Exception { + void testProcess_PfRtEx() { PfModelRuntimeException ex = new PfModelRuntimeException(Status.BAD_REQUEST, EXPECTED_EXCEPTION); when(pdpGroupService.updatePdpGroups(any())).thenThrow(ex); @@ -115,7 +118,7 @@ public class TestProviderBase extends ProviderSuper { } @Test - void testProcess_RuntimeEx() throws Exception { + void testProcess_RuntimeEx() { RuntimeException ex = new RuntimeException(EXPECTED_EXCEPTION); when(pdpGroupService.updatePdpGroups(any())).thenThrow(ex); @@ -124,7 +127,7 @@ public class TestProviderBase extends ProviderSuper { } @Test - void testProcessPolicy_NoGroups() throws Exception { + void testProcessPolicy_NoGroups() { when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Collections.emptyList()); SessionData session = @@ -190,8 +193,8 @@ public class TestProviderBase extends ProviderSuper { assertGroup(getGroupUpdates(), GROUP1_NAME); List requests = getUpdateRequests(2); - assertUpdate(requests, GROUP1_NAME, PDP2_TYPE, PDP2); - assertUpdate(requests, GROUP1_NAME, PDP4_TYPE, PDP4); + assertUpdate(requests, PDP2_TYPE, PDP2); + assertUpdate(requests, PDP4_TYPE, PDP4); } @Test @@ -265,12 +268,12 @@ public class TestProviderBase extends ProviderSuper { } - protected void assertUpdate(List updates, String groupName, String pdpType, String pdpName) { + protected void assertUpdate(List updates, String pdpType, String pdpName) { PdpUpdate update = updates.remove(0); assertEquals(PapConstants.PAP_NAME, update.getSource()); - assertEquals(groupName, update.getPdpGroup()); + assertEquals(TestProviderBase.GROUP1_NAME, update.getPdpGroup()); assertEquals(pdpType, update.getPdpSubgroup()); assertEquals(pdpName, update.getName()); assertTrue(update.getPoliciesToBeDeployed().contains(policy1)); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestSessionData.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestSessionData.java index 82f34616..4434c0db 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/TestSessionData.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestSessionData.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021, 2023 Nordix Foundation. + * Modifications Copyright (C) 2021, 2023-2024 Nordix Foundation. * Modifications Copyright (C) 2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -86,11 +86,10 @@ class TestSessionData extends ProviderSuper { /** * Initializes mocks and a session. * - * @throws Exception if an error occurs */ @Override @BeforeEach - public void setUp() throws Exception { + public void setUp() { super.setUp(); ident = new ToscaConceptIdentifierOptVersion(POLICY_NAME, POLICY_VERSION); @@ -104,7 +103,7 @@ class TestSessionData extends ProviderSuper { @Test void testGetPolicyType() throws Exception { - ToscaPolicyType policy1 = makePolicyType(POLICY_TYPE, POLICY_TYPE_VERSION); + ToscaPolicyType policy1 = makePolicyType(); when(toscaService.getPolicyTypeList(POLICY_TYPE, POLICY_TYPE_VERSION)).thenReturn(List.of(policy1)); assertSame(policy1, session.getPolicyType(type)); @@ -130,7 +129,7 @@ class TestSessionData extends ProviderSuper { @Test void testGetPolicy_NullVersion() throws Exception { - ToscaPolicy policy1 = makePolicy(POLICY_NAME, POLICY_VERSION); + ToscaPolicy policy1 = makePolicy(); when(toscaService.getFilteredPolicyList(any())).thenReturn(List.of(policy1)); ident.setVersion(null); @@ -148,7 +147,7 @@ class TestSessionData extends ProviderSuper { @Test void testGetPolicy_MajorVersion() throws Exception { - ToscaPolicy policy1 = makePolicy(POLICY_NAME, POLICY_VERSION); + ToscaPolicy policy1 = makePolicy(); when(toscaService.getFilteredPolicyList(any())).thenReturn(List.of(policy1)); ident.setVersion("1"); @@ -166,7 +165,7 @@ class TestSessionData extends ProviderSuper { @Test void testGetPolicy_MajorMinorVersion() throws Exception { - ToscaPolicy policy1 = makePolicy(POLICY_NAME, POLICY_VERSION); + ToscaPolicy policy1 = makePolicy(); when(toscaService.getFilteredPolicyList(any())).thenReturn(List.of(policy1)); ident.setVersion(POLICY_VERSION); @@ -322,20 +321,20 @@ class TestSessionData extends ProviderSuper { assertEquals(List.of(change1, change2, change3).toString(), lst.toString()); } - private ToscaPolicyType makePolicyType(String name, String version) { - ToscaPolicyType type = new ToscaPolicyType(); + private ToscaPolicyType makePolicyType() { + ToscaPolicyType newType = new ToscaPolicyType(); - type.setName(name); - type.setVersion(version); + newType.setName(TestSessionData.POLICY_TYPE); + newType.setVersion(TestSessionData.POLICY_TYPE_VERSION); - return type; + return newType; } - private ToscaPolicy makePolicy(String name, String version) { + private ToscaPolicy makePolicy() { ToscaPolicy policy = new ToscaPolicy(); - policy.setName(name); - policy.setVersion(version); + policy.setName(TestSessionData.POLICY_NAME); + policy.setVersion(TestSessionData.POLICY_VERSION); return policy; } @@ -561,7 +560,7 @@ class TestSessionData extends ProviderSuper { } }; - ToscaPolicy policy = makePolicy(POLICY_NAME, POLICY_VERSION); + ToscaPolicy policy = makePolicy(); policy.setType(POLICY_TYPE); policy.setTypeVersion(POLICY_TYPE_VERSION); diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndBase.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndBase.java index 1aa40a28..4315cf33 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndBase.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/End2EndBase.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2019-2020, 2022-2023 Nordix Foundation. + * Modifications Copyright (C) 2019-2020, 2022-2024 Nordix Foundation. * Modifications Copyright (C) 2021-2023 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -130,9 +130,7 @@ public abstract class End2EndBase extends CommonPapRestServer { * @param yamlFile name of the YAML file specifying the data to be loaded */ public void addToscaPolicies(final String yamlFile) { - final ToscaServiceTemplate serviceTemplate = loadYamlFile(yamlFile, ToscaServiceTemplate.class); - JpaToscaServiceTemplate jpaToscaServiceTemplate = mergeWithExistingTemplate(serviceTemplate); - serviceTemplateRepository.save(jpaToscaServiceTemplate); + addToscaPolicyTypes(yamlFile); } private JpaToscaServiceTemplate mergeWithExistingTemplate(ToscaServiceTemplate serviceTemplate) { @@ -243,7 +241,7 @@ public abstract class End2EndBase extends CommonPapRestServer { } } - public class PolicyStatusRecords { + public static class PolicyStatusRecords { private List records; } } diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeployTest.java b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeployTest.java index 5bc8dd09..7dbf5a0b 100644 --- a/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeployTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/rest/e2e/PdpGroupDeployTest.java @@ -3,7 +3,7 @@ * ONAP PAP * ================================================================================ * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2021-2023 Nordix Foundation. + * Modifications Copyright (C) 2021-2024 Nordix Foundation. * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -129,6 +129,7 @@ class PdpGroupDeployTest extends End2EndBase { resp = rawresp.readEntity(PdpGroupDeployResponse.class); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), rawresp.getStatus()); assertTrue(resp.getErrorDetails().contains("unknown group")); + rawresp.close(); } @Test @@ -205,5 +206,6 @@ class PdpGroupDeployTest extends End2EndBase { assertNull(resp.getErrorDetails()); assertThat(meterRegistry.counter(deploymentsCounterName, deploymentSuccessTag).count()).isEqualTo(2); + rawresp.close(); } } diff --git a/main/src/test/java/org/onap/policy/pap/main/service/PolicyAuditServiceTest.java b/main/src/test/java/org/onap/policy/pap/main/service/PolicyAuditServiceTest.java index 11f2045d..8617c4eb 100644 --- a/main/src/test/java/org/onap/policy/pap/main/service/PolicyAuditServiceTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/service/PolicyAuditServiceTest.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2022 Bell Canada. All rights reserved. - * Modifications Copyright (C) 2022-2023 Nordix Foundation. + * Modifications Copyright (C) 2022-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -110,7 +110,7 @@ class PolicyAuditServiceTest extends CommonPapRestServer { NUMBER_RECORDS, null, null)).hasSize(2); assertThat( policyAuditService.getAuditRecords(GROUP_A, MY_POLICY.getName(), "9.9.9", NUMBER_RECORDS, null, null)) - .isEmpty(); + .isEmpty(); assertThat(policyAuditService.getAuditRecords(GROUP_B, MY_POLICY.getName(), MY_POLICY.getVersion(), NUMBER_RECORDS, null, null)).isEmpty(); assertThat(policyAuditService.getAuditRecords(GROUP_B, MY_POLICY2.getName(), MY_POLICY2.getVersion(), @@ -119,10 +119,58 @@ class PolicyAuditServiceTest extends CommonPapRestServer { null, null)).hasSize(2); assertThat( policyAuditService.getAuditRecords(MY_POLICY.getName(), MY_POLICY.getVersion(), NUMBER_RECORDS, null, null)) - .hasSize(2); + .hasSize(2); } + @Test + void testGetAuditRecords_ForCoverage() { + Instant startDate1 = Instant.now(); + + policyAuditService.createAuditRecords(generatePolicyAudits(startDate1, GROUP_A, MY_POLICY)); + assertThat(policyAuditService.getAuditRecords(NUMBER_RECORDS, null, startDate1)).hasSize(1); + assertThat(policyAuditService.getAuditRecords(GROUP_A, NUMBER_RECORDS, null, startDate1)).hasSize(1); + assertThat(policyAuditService.getAuditRecords(GROUP_A, NUMBER_RECORDS, startDate1, null)).hasSize(1); + + var listByPolicy = policyAuditService.getAuditRecords(GROUP_A, MY_POLICY.getName(), MY_POLICY.getVersion(), + NUMBER_RECORDS, startDate1, null); + assertThat(listByPolicy).hasSize(1); + listByPolicy = policyAuditService.getAuditRecords(MY_POLICY.getName(), MY_POLICY.getVersion(), + NUMBER_RECORDS, null, startDate1); + assertThat(listByPolicy).hasSize(1); + + listByPolicy = policyAuditService.getAuditRecords(GROUP_A, MY_POLICY.getName(), MY_POLICY.getVersion(), + NUMBER_RECORDS, startDate1, null); + assertThat(listByPolicy).hasSize(1); + listByPolicy = policyAuditService.getAuditRecords(MY_POLICY.getName(), MY_POLICY.getVersion(), + NUMBER_RECORDS, startDate1, null); + assertThat(listByPolicy).hasSize(1); + + + listByPolicy = policyAuditService.getAuditRecords(MY_POLICY.getName(), MY_POLICY.getVersion(), + 0, null, null); + assertThat(listByPolicy).hasSize(2); + + listByPolicy = policyAuditService.getAuditRecords(GROUP_A, MY_POLICY.getName(), MY_POLICY.getVersion(), + NUMBER_RECORDS, null, startDate1); + assertThat(listByPolicy).hasSize(1); + + listByPolicy = policyAuditService.getAuditRecords(GROUP_A, MY_POLICY.getName(), MY_POLICY.getVersion(), + NUMBER_RECORDS, startDate1, startDate1.plusSeconds(10)); + assertThat(listByPolicy).hasSize(1); + } + + @Test + void testPageable() { + Instant startDate1 = Instant.now(); + + policyAuditService.createAuditRecords(generatePolicyAudits(startDate1, GROUP_A, MY_POLICY)); + policyAuditService.createAuditRecords(generatePolicyAudits(startDate1, GROUP_B, MY_POLICY2)); + + assertThat(policyAuditService.getAuditRecords(-1, null, null)).hasSize(4); + assertThat(policyAuditService.getAuditRecords(Integer.MAX_VALUE, null, null)).hasSize(4); + } + private List generatePolicyAudits(Instant date, String group, ToscaConceptIdentifier policy) { PolicyAudit deploy = PolicyAudit.builder().pdpGroup(group).pdpType("pdpType").policy(policy) .action(AuditAction.DEPLOYMENT).timestamp(date.truncatedTo(ChronoUnit.SECONDS)).build(); diff --git a/main/src/test/java/org/onap/policy/pap/main/service/PolicyStatusServiceTest.java b/main/src/test/java/org/onap/policy/pap/main/service/PolicyStatusServiceTest.java index ecdecf36..ba026d09 100644 --- a/main/src/test/java/org/onap/policy/pap/main/service/PolicyStatusServiceTest.java +++ b/main/src/test/java/org/onap/policy/pap/main/service/PolicyStatusServiceTest.java @@ -1,7 +1,7 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2022-2023 Bell Canada. All rights reserved. - * Modifications Copyright (C) 2022-2023 Nordix Foundation. + * Modifications Copyright (C) 2022-2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.util.ArrayList; import java.util.List; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.onap.policy.models.base.PfModelRuntimeException; @@ -49,6 +51,8 @@ class PolicyStatusServiceTest extends CommonPapRestServer { private PdpPolicyStatus.PdpPolicyStatusBuilder statusBuilder; + private List statusList = new ArrayList<>(); + /** * Setup before tests. * @@ -64,14 +68,20 @@ class PolicyStatusServiceTest extends CommonPapRestServer { .policyType(policyType).state(PdpPolicyStatus.State.SUCCESS); } + @AfterEach + void after() { + if (!statusList.isEmpty()) { + policyStatusService.cudPolicyStatus(null, null, statusList); + } + } + @Test void testGetAllPolicyStatus() { assertThat(policyStatusService.getAllPolicyStatus()).isEmpty(); - var statusList = createStatusList(); + statusList = createStatusList(); policyStatusService.cudPolicyStatus(statusList, null, null); assertThat(policyStatusService.getAllPolicyStatus()).hasSize(5); - policyStatusService.cudPolicyStatus(null, null, statusList); } @Test @@ -83,14 +93,14 @@ class PolicyStatusServiceTest extends CommonPapRestServer { assertThat(policyStatusService.getAllPolicyStatus(new ToscaConceptIdentifierOptVersion("somePdp", null))) .isEmpty(); - var statusList = createStatusList(); + statusList = createStatusList(); policyStatusService.cudPolicyStatus(statusList, null, null); assertThat(policyStatusService.getAllPolicyStatus(new ToscaConceptIdentifierOptVersion(MY_POLICY))).hasSize(2); - assertThat( - policyStatusService.getAllPolicyStatus(new ToscaConceptIdentifierOptVersion(MY_POLICY.getName(), null))) - .hasSize(3); - policyStatusService.cudPolicyStatus(null, null, statusList); + + var toscaConceptIdentifierOptVersion = new ToscaConceptIdentifierOptVersion(MY_POLICY.getName(), null); + assertThat(policyStatusService.getAllPolicyStatus(toscaConceptIdentifierOptVersion)) + .hasSize(3); } @Test @@ -101,10 +111,15 @@ class PolicyStatusServiceTest extends CommonPapRestServer { assertThat(policyStatusService.getGroupPolicyStatus("PdpGroup0")).isEmpty(); - var statusList = createStatusList(); + statusList = createStatusList(); policyStatusService.cudPolicyStatus(statusList, null, null); assertThat(policyStatusService.getGroupPolicyStatus(GROUP_A)).hasSize(3); - policyStatusService.cudPolicyStatus(null, null, statusList); + + assertThat(policyStatusService.getAllPolicyStatus(GROUP_A, new ToscaConceptIdentifierOptVersion(MY_POLICY))) + .hasSize(1); + + var myOtherPolicy = new ToscaConceptIdentifierOptVersion("myOtherPolicy", null); + assertThat(policyStatusService.getAllPolicyStatus(GROUP_A, myOtherPolicy)).isEmpty(); } @Test diff --git a/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapDatabaseInitializer.java b/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapDatabaseInitializer.java new file mode 100644 index 00000000..a8a73cb2 --- /dev/null +++ b/main/src/test/java/org/onap/policy/pap/main/startstop/TestPapDatabaseInitializer.java @@ -0,0 +1,80 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2024 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.main.startstop; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.onap.policy.common.utils.services.Registry; +import org.onap.policy.pap.main.PolicyPapException; +import org.onap.policy.pap.main.service.PdpGroupService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.util.ReflectionTestUtils; + +@SpringBootTest +@ActiveProfiles("test-db") +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) +class TestPapDatabaseInitializer { + + @Autowired + private PapDatabaseInitializer papDatabaseInitializer; + + @Autowired + private PdpGroupService pdpGroupService; + + @BeforeAll + static void before() { + Registry.newRegistry(); + } + + @Order(1) + @Test + void testDatabaseCreated() { + assertNotNull(pdpGroupService.getPdpGroups()); + + assertDoesNotThrow(() -> papDatabaseInitializer.loadData()); + } + + @Order(2) + @Test + void testDatabase_Exception() { + ReflectionTestUtils.setField(papDatabaseInitializer, "groupConfigFile", "invalid.json"); + assertThrows(PolicyPapException.class, () -> papDatabaseInitializer.loadData()); + + + ReflectionTestUtils.setField(papDatabaseInitializer, "groupConfigFile", "simpleDeploy/emptyGroups.json"); + assertThrows(PolicyPapException.class, () -> papDatabaseInitializer.loadData()); + + ReflectionTestUtils.setField(papDatabaseInitializer, "groupConfigFile", + "simpleDeploy/createGroupDuplicateSubGroups.json"); + assertThrows(PolicyPapException.class, () -> papDatabaseInitializer.loadData()); + } +} diff --git a/main/src/test/resources/application-test-db.yaml b/main/src/test/resources/application-test-db.yaml new file mode 100644 index 00000000..725a3a76 --- /dev/null +++ b/main/src/test/resources/application-test-db.yaml @@ -0,0 +1,14 @@ +spring: + datasource: + url: jdbc:h2:mem:testdb + driverClassName: org.h2.Driver + jpa: + hibernate: + ddl-auto: create-drop + naming: + physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl + implicit-strategy: org.onap.policy.common.spring.utils.CustomImplicitNamingStrategy + open-in-view: false + +pap: + name: "PapGroupDB" diff --git a/main/src/test/resources/simpleDeploy/createGroupDuplicateSubGroups.json b/main/src/test/resources/simpleDeploy/createGroupDuplicateSubGroups.json new file mode 100644 index 00000000..fa98b62a --- /dev/null +++ b/main/src/test/resources/simpleDeploy/createGroupDuplicateSubGroups.json @@ -0,0 +1,53 @@ +{ + "groups": [ + { + "name": "groupA", + "version": "200.2.3", + "description": "my description", + "pdpGroupState": "ACTIVE", + "properties": { + "hello": "world" + }, + "pdpSubgroups": [ + { + "pdpType": "pdpTypeA", + "desiredInstanceCount": 1, + "properties": { + "abc": "def" + }, + "supportedPolicyTypes": [ + { + "name": "typeA", + "version": "100.2.3" + } + ], + "pdpInstances": [ + { + "instanceId": "pdpA" + } + ], + "policies": [] + }, + { + "pdpType": "pdpTypeA", + "desiredInstanceCount": 1, + "properties": { + "abc": "def" + }, + "supportedPolicyTypes": [ + { + "name": "typeA", + "version": "100.2.3" + } + ], + "pdpInstances": [ + { + "instanceId": "pdpA" + } + ], + "policies": [] + } + ] + } + ] +} -- cgit 1.2.3-korg