/*
* ============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");
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;
/**
/*-
* ============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.
* ================================================================================
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;
*
* @author Ram Krishna Verma (ram.krishna.verma@est.tech)
*/
-@AllArgsConstructor
@NoArgsConstructor
@Component
public class PdpHeartbeatListener implements TypedMessageListener<PdpStatus> {
- @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) {
* 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");
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;
* 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;
}
protected PdpUpdate createPdpUpdateMessage(final String pdpGroupName, final PdpSubGroup subGroup,
- final String pdpInstanceId,
- final List<ToscaPolicy> policiesToBeDeployed,
- final List<ToscaConceptIdentifier> policiesToBeUndeployed) {
+ final String pdpInstanceId, final List<ToscaPolicy> policiesToBeDeployed,
+ final List<ToscaConceptIdentifier> policiesToBeUndeployed) {
final var update = new PdpUpdate();
*
* @param subGroup PdpSubGroup to retrieve policies from
* @return a list of ToscaPolicy
- * @throws PfModelException the exception
**/
- public List<ToscaPolicy> getToscaPolicies(final PdpSubGroup subGroup) throws PfModelException {
+ public List<ToscaPolicy> getToscaPolicies(final PdpSubGroup subGroup) {
final List<ToscaPolicy> policies = new LinkedList<>();
for (final ToscaConceptIdentifier policyIdentifier : subGroup.getPolicies()) {
}
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);
* 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<ToscaPolicy> policies) {
+ PdpState pdpState, List<ToscaPolicy> policies) {
var deploymentStatus = new DeploymentStatus(policyStatusService);
deploymentStatus.loadByGroup(pdpGroupName);
if (pdpState.equals(PdpState.PASSIVE)) {
* 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");
/**
* Used to undeploy policies from the system, when they cannot be deployed to a PDP.
- *
* <p/>
* Note: The request map needs an undeployer during creation, and the undeployer
* needs the request map when it's initialize method is called.
/**
* 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;
/**
* 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) {
* 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)) {
var request = new UpdateReq(reqparams, name, update);
addSingleton(request);
- return request;
}
/**
* 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);
* 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<String> removeFromGroup(Instant minAge, PdpGroup group) {
* 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<String> pdps) {
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);
/*-
* ============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.
* ================================================================================
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;
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;
/**
* Constructs the object.
*
- * @param parameterGroup the parameterGroup
+ * @param parameterGroup the parameterGroup
* @param pdpGroupService the pdpGroupService
*/
public PdpStatusMessageHandler(PapParameterGroup parameterGroup, PdpGroupService pdpGroupService) {
* 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);
/**
* 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
*/
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);
}
}
- 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<PdpGroup> pdpGroups = pdpGroupService.getFilteredPdpGroups(filter);
if (!pdpGroups.isEmpty()) {
return pdpGroupFound;
}
- private boolean registerPdp(final PdpStatus message, final PdpGroup finalizedPdpGroup) throws PfModelException {
+ private boolean registerPdp(final PdpStatus message, final PdpGroup finalizedPdpGroup) {
Optional<PdpSubGroup> subGroup;
var pdpGroupFound = false;
subGroup = findPdpSubGroup(message, finalizedPdpGroup);
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);
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<PdpGroup> pdpGroups = pdpGroupService.getFilteredPdpGroups(filter);
if (!pdpGroups.isEmpty()) {
var pdpGroup = pdpGroups.get(0);
}
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<ToscaConceptIdentifier, ToscaPolicy> 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);
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());
}
private void sendPdpMessage(final String pdpGroupName, final PdpSubGroup subGroup, final String pdpInstanceId,
- final PdpState pdpState) {
+ final PdpState pdpState) {
final List<ToscaPolicy> 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(),
/*-
* ============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.
http
.httpBasic(Customizer.withDefaults())
.authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated())
- .csrf(AbstractHttpConfigurer::disable);
+ .csrf(AbstractHttpConfigurer::disable); // NOSONAR
return http.build();
}
}
/*-
* ============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.
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;
* 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);
}
* 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);
}
}
/*-
* ============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.
* ================================================================================
*
* @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<PdpGroupStateChangeResponse> changeGroupState(
- String groupName, PdpState state, UUID requestId) {
+ public ResponseEntity<PdpGroupStateChangeResponse> changeGroupState(String groupName, PdpState state,
+ UUID requestId) {
try {
final Pair<HttpStatus, PdpGroupStateChangeResponse> pair = provider.changeGroupState(groupName, state);
return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.status(pair.getLeft())), requestId)
/*-
* ============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.
* ================================================================================
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;
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<HttpStatus, PdpGroupStateChangeResponse> 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<PdpGroup> pdpGroups = pdpGroupService.getPdpGroups(groupName);
if (!pdpGroups.isEmpty() && !PdpState.ACTIVE.equals(pdpGroups.get(0).getPdpGroupState())) {
updatePdpGroupAndPdp(pdpGroups, PdpState.ACTIVE);
}
}
- private void handlePassiveState(final String groupName) throws PfModelException {
+ private void handlePassiveState(final String groupName) {
final List<PdpGroup> pdpGroups = pdpGroupService.getPdpGroups(groupName);
if (!pdpGroups.isEmpty() && !PdpState.PASSIVE.equals(pdpGroups.get(0).getPdpGroupState())) {
updatePdpGroupAndPdp(pdpGroups, PdpState.PASSIVE);
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<ToscaPolicy> 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);
}
}
* 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");
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;
* 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
}
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)
*/
@Override
public ResponseEntity<Object> queryDeployedPolicies(String name, UUID requestId) {
+ Collection<PolicyStatus> result = provider.getStatus(new ToscaConceptIdentifierOptVersion(name, null));
+ if (result.isEmpty()) {
+ return makeNotFoundResponse(requestId);
- try {
- Collection<PolicyStatus> 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);
}
}
*/
@Override
public ResponseEntity<Object> queryDeployedPolicy(String name, String version, UUID requestId) {
+ Collection<PolicyStatus> result = provider.getStatus(new ToscaConceptIdentifierOptVersion(name, version));
+ if (result.isEmpty()) {
+ return makeNotFoundResponse(requestId);
- try {
- Collection<PolicyStatus> 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());
}
}
*/
@Override
public ResponseEntity<Object> 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());
}
/**
* 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<Object> getStatusOfPoliciesByGroup(
- String pdpGroupName,
- UUID requestId,
- String regex) {
-
+ public ResponseEntity<Object> getStatusOfPoliciesByGroup(String pdpGroupName, UUID requestId, String regex) {
try {
final Collection<PdpPolicyStatus> result;
if (regex == null) {
}
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)
* 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<Object> getStatusOfPolicies(
- String pdpGroupName,
- String policyName,
- UUID requestId) {
-
- try {
- Collection<PdpPolicyStatus> 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<Object> getStatusOfPolicies(String pdpGroupName, String policyName, UUID requestId) {
+ Collection<PdpPolicyStatus> result =
+ provider.getPolicyStatus(pdpGroupName, new ToscaConceptIdentifierOptVersion(policyName, null));
+ if (result.isEmpty()) {
+ return makeNotFoundResponse(requestId);
+ } else {
+ return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.ok()), requestId).body(result);
}
}
/**
* 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<Object> getStatusOfPolicy(
- String pdpGroupName,
- String policyName,
- String policyVersion,
- UUID requestId) {
-
- try {
- Collection<PdpPolicyStatus> 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<Object> getStatusOfPolicy(String pdpGroupName, String policyName, String policyVersion,
+ UUID requestId) {
+ Collection<PdpPolicyStatus> 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());
}
}
*/
private ResponseEntity<Object> makeNotFoundResponse(final UUID requestId) {
return addLoggingHeaders(addVersionControlHeaders(ResponseEntity.status(HttpStatus.NOT_FOUND)), requestId)
- .build();
+ .build();
}
private ResponseEntity<Object> makeRegexNotFoundResponse(UUID requestId) {
* ================================================================================
* 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.
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;
* @return the deployment status of the policy
*/
public Collection<PdpPolicyStatus> 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();
}
/**
.getPolicy()
.getName();
return pattern.matcher(policyName).matches();
- })
- .collect(Collectors.toList());
+ }).toList();
}
}
/*-
* ============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.
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;
* @param audits list of policy audit
*/
public void createAuditRecords(@NonNull final List<PolicyAudit> audits) {
- List<JpaPolicyAudit> jpaAudits = audits.stream().map(JpaPolicyAudit::new).collect(Collectors.toList());
+ List<JpaPolicyAudit> jpaAudits = audits.stream().map(JpaPolicyAudit::new).toList();
var result = new BeanValidationResult("createAuditRecords", jpaAudits);
}
private List<PolicyAudit> asPolicyAuditList(List<JpaPolicyAudit> jpaPolicyAuditList) {
- return jpaPolicyAuditList.stream().map(JpaPolicyAudit::toAuthorative).collect(Collectors.toList());
+ return jpaPolicyAuditList.stream().map(JpaPolicyAudit::toAuthorative).toList();
}
}
/*-
* ============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.
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;
* @return the policy status list found
*/
public List<PdpPolicyStatus> getAllPolicyStatus(@NonNull ToscaConceptIdentifierOptVersion policy) {
-
if (policy.getVersion() != null) {
return asPolicyStatusList(policyStatusRepository
.findByKeyParentKeyNameAndKeyParentKeyVersion(policy.getName(), policy.getVersion()));
-
} else {
return asPolicyStatusList(policyStatusRepository.findByKeyParentKeyName(policy.getName()));
}
* 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<PdpPolicyStatus> getAllPolicyStatus(@NonNull String pdpGroup,
- @NonNull ToscaConceptIdentifierOptVersion policy) {
+ @NonNull ToscaConceptIdentifierOptVersion policy) {
if (policy.getVersion() != null) {
return asPolicyStatusList(policyStatusRepository.findByPdpGroupAndKeyParentKeyNameAndKeyParentKeyVersion(
pdpGroup, policy.getName(), policy.getVersion()));
* @param deleteObjs the objects to delete
*/
public void cudPolicyStatus(Collection<PdpPolicyStatus> createObjs, Collection<PdpPolicyStatus> updateObjs,
- Collection<PdpPolicyStatus> deleteObjs) {
+ Collection<PdpPolicyStatus> deleteObjs) {
try {
policyStatusRepository.deleteAll(fromAuthorativeStatus(deleteObjs, "deletePdpPolicyStatusList"));
policyStatusRepository.saveAll(fromAuthorativeStatus(createObjs, "createPdpPolicyStatusList"));
* 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
*/
return Collections.emptyList();
}
- List<JpaPdpPolicyStatus> jpas = objs.stream().map(JpaPdpPolicyStatus::new).collect(Collectors.toList());
+ List<JpaPdpPolicyStatus> jpas = objs.stream().map(JpaPdpPolicyStatus::new).toList();
// validate the objects
var result = new BeanValidationResult(fieldName, jpas);
}
private List<PdpPolicyStatus> asPolicyStatusList(List<JpaPdpPolicyStatus> jpaPdpPolicyStatusList) {
- return jpaPdpPolicyStatusList.stream().map(JpaPdpPolicyStatus::toAuthorative).collect(Collectors.toList());
+ return jpaPdpPolicyStatusList.stream().map(JpaPdpPolicyStatus::toAuthorative).toList();
}
}
/*-
* ============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.
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;
/**
* 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<ToscaPolicy> getPolicyList(final String name, final String version) throws PfModelException {
+ public List<ToscaPolicy> getPolicyList(final String name, final String version) {
LOGGER.debug("->getPolicyList: name={}, version={}", name, version);
try {
List<Map<String, ToscaPolicy>> 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);
/**
* 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
}
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");
}
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");
/*-
* ============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.
* ================================================================================
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;
private final StandardCoder standardCoder;
- @Autowired
- private PdpGroupService pdpGroupService;
+ private final PdpGroupService pdpGroupService;
@Value("${group-config-file:PapDb.json}")
private String groupConfigFile;
/**
* Constructs the object.
*/
- public PapDatabaseInitializer() {
+ public PapDatabaseInitializer(PdpGroupService pdpGroupService) {
+ this.pdpGroupService = pdpGroupService;
standardCoder = new StandardCoder();
}
* 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");
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);
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
public MyMap(PdpModifyRequestMapParams params) {
super(pdpGroupService, policyStatusService, responseHandler, undeployer, notifier);
super.initialize(params);
- ;
}
@Override
* 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.
* 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();
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);
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);
mgr.register(NAME2, mgr::addToQueue);
mgr.awaitSleep();
- tcur = mgr.currentTimeMillis();
+ tcur1 = mgr.currentTimeMillis();
mgr.allowSleep(1);
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());
* 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<String> action) {
+ public void registerNewTime(String timerName, Consumer<String> action) {
synchronized (lockit) {
offset++;
curTime += offset;
- Timer timer = super.register(timerName, action);
+ super.register(timerName, action);
curTime -= offset;
- return timer;
}
}
* 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.
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);
ArrayList<ToscaPolicy> 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();
policies = new ArrayList<>(update.getPoliciesToBeDeployed());
List<ToscaConceptIdentifier> polsToUndep = policies.parallelStream()
.map(ToscaPolicy::getIdentifier)
- .collect(Collectors.toList());
+ .toList();
msg2.setPoliciesToBeUndeployed(polsToUndep);
assertTrue(data.reconfigure(msg2));
// some items in both undeploy and newMessage.deploy
policies = new ArrayList<>(update.getPoliciesToBeDeployed());
List<ToscaConceptIdentifier> polsToUndep2 = policies.parallelStream()
- .map(ToscaPolicy::getIdentifier)
- .collect(Collectors.toList());
+ .map(ToscaPolicy::getIdentifier).toList();
data.getMessage().setPoliciesToBeUndeployed(polsToUndep2);
List<ToscaPolicy> polsToDep2 = new LinkedList<>();
List<ToscaConceptIdentifier> 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));
* 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");
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;
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";
@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
private class MyNotifier extends PolicyNotifier {
- public MyNotifier(Publisher<PolicyNotification> publisher) throws PfModelException {
+ public MyNotifier(Publisher<PolicyNotification> publisher) {
super(policyStatusService);
super.setPublisher(publisher);
}
/*
* ============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.
* ================================================================================
private boolean activatorWasAlive;
protected String httpsPrefix;
+ protected Client client;
+
@LocalServerPort
private int port;
@AfterEach
public void tearDown() {
markActivator(activatorWasAlive);
+ if (client != null) {
+ client.close();
+ }
}
@AfterAll
Object manager = ReflectionTestUtils.getField(papActivator, "serviceManager");
AtomicBoolean running = (AtomicBoolean) ReflectionTestUtils
.getField(Objects.requireNonNull(manager), "running");
+ assert running != null;
running.set(wasAlive);
}
*/
protected void checkUnauthRequest(final String endpoint, Function<Invocation.Builder, Response> 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();
+
}
/**
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
* 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");
* Configures DAO, captors, and various mocks.
*/
@BeforeEach
- public void setUp() throws Exception {
+ public void setUp() {
Registry.newRegistry();
reqmap = mock(PdpModifyRequestMap.class);
lockit = new Object();
- policy1 = loadPolicy("policy.json");
+ policy1 = loadPolicy();
meterRegistry = mock(MeterRegistry.class);
/**
* 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);
}
/**
* ============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.
* ================================================================================
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;
/**
* 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
}
@Test
- void testCreateOrUpdateGroups_InvalidRequest() throws Exception {
+ void testCreateOrUpdateGroups_InvalidRequest() {
assertThatThrownBy(() -> prov.createOrUpdateGroups(new PdpGroups())).isInstanceOf(PfModelException.class)
.hasMessageContaining("is null");
}
@Test
- void testCreateOrUpdate_Invalid() throws Exception {
+ void testCreateOrUpdate_Invalid() {
PdpGroups groups = loadPdpGroups("createGroups.json");
groups.getGroups().get(0).setPdpGroupState(PdpState.TERMINATED);
}
@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");
// 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);
}
@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");
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);
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);
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);
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);
@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");
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);
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);
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);
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");
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);
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);
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());
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);
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"));
}
@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<>());
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"));
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);
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);
}
@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<>());
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<PdpGroup> updates = getGroupUpdates();
- assertEquals(Arrays.asList(group), updates);
+ assertEquals(Collections.singletonList(group), updates);
}
}
* 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");
/**
* 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);
}
@Test
- void testUndeployPolicy_DaoEx() throws Exception {
+ void testUndeployPolicy_DaoEx() throws PfModelException {
PfModelException exc = new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION);
prov = spy(prov);
}
@Test
- void testUndeployPolicy_RtEx() throws Exception {
+ void testUndeployPolicy_RtEx() throws PfModelException {
RuntimeException exc = new RuntimeException(EXPECTED_EXCEPTION);
prov = spy(prov);
@Override
protected void processPolicy(SessionData data, ToscaConceptIdentifierOptVersion desiredPolicy)
- throws PfModelException {
+ throws PfModelException { // NOSONAR
// do nothing
}
}
* 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");
/**
* 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);
+ }
}
/**
}
@Test
- void testUpdateGroupPolicies_InvalidRequest() throws Exception {
+ void testUpdateGroupPolicies_InvalidRequest() {
assertThatThrownBy(() -> prov.updateGroupPolicies(new DeploymentGroups(), DEFAULT_USER))
.isInstanceOf(PfModelException.class).hasMessageContaining("is null");
}
@Test
- void testUpdateGroup_UnknownGroup() throws Exception {
+ void testUpdateGroup_UnknownGroup() {
PdpGroups groups = loadPdpGroups("deployGroups.json");
String groupName = groups.getGroups().get(0).getName();
}
@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));
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");
}
@Test
- void testUpdateSubGroup_PolicyVersionPrefixMismatch() throws Exception {
+ void testUpdateSubGroup_PolicyVersionPrefixMismatch() {
PdpGroups groups = loadPdpGroups("deployGroups.json");
PdpGroup newgrp = groups.getGroups().get(0);
assertGroup(getGroupUpdates(), GROUP1_NAME);
List<PdpUpdate> requests = getUpdateRequests(1);
- assertUpdate(requests, GROUP1_NAME, PDP2_TYPE, PDP2);
+ assertUpdate(requests, PDP2_TYPE, PDP2);
// nothing is complete - notification should be empty
checkEmptyNotification();
assertGroup(getGroupUpdates(), GROUP1_NAME);
List<PdpUpdate> 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();
verify(reqmap, never()).addRequest(any(PdpUpdate.class));
}
- protected void assertUpdate(List<PdpUpdate> updates, String groupName, String pdpType, String pdpName) {
+ protected void assertUpdate(List<PdpUpdate> 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);
/*-
* ============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.
* ================================================================================
* Configures DAO and mocks.
*/
@BeforeEach
- public void setUp() throws Exception {
+ public void setUp() {
autoCloseable = MockitoAnnotations.openMocks(this);
Registry.newRegistry();
groups = loadFile().getGroups();
/*-
* ============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.
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;
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();
}
}
/*-
* ============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");
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);
}
@Test
void testSaveRecordsToDb_EmptyList() {
assertThat(auditManager.getAuditRecords()).isEmpty();
- ;
auditManager.saveRecordsToDb();
-
assertThatCode(() -> auditManager.saveRecordsToDb()).doesNotThrowAnyException();
}
* ================================================================================
* 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.
/**
* Configures mocks and objects.
*
- * @throws Exception if an error occurs
*/
@Override
@BeforeEach
- public void setUp() throws Exception {
+ public void setUp() {
super.setUp();
* 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.
/**
* Configures mocks and objects.
*
- * @throws Exception if an error occurs
*/
@Override
@BeforeEach
- public void setUp() throws Exception {
+ public void setUp() {
super.setUp();
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();
}
* 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");
/**
* 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
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);
}
@Test
- void testProcess_RuntimeEx() throws Exception {
+ void testProcess_RuntimeEx() {
RuntimeException ex = new RuntimeException(EXPECTED_EXCEPTION);
when(pdpGroupService.updatePdpGroups(any())).thenThrow(ex);
}
@Test
- void testProcessPolicy_NoGroups() throws Exception {
+ void testProcessPolicy_NoGroups() {
when(pdpGroupService.getFilteredPdpGroups(any())).thenReturn(Collections.emptyList());
SessionData session =
assertGroup(getGroupUpdates(), GROUP1_NAME);
List<PdpUpdate> 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
}
- protected void assertUpdate(List<PdpUpdate> updates, String groupName, String pdpType, String pdpName) {
+ protected void assertUpdate(List<PdpUpdate> 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));
* 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");
/**
* 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);
@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));
@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);
@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");
@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);
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;
}
}
};
- ToscaPolicy policy = makePolicy(POLICY_NAME, POLICY_VERSION);
+ ToscaPolicy policy = makePolicy();
policy.setType(POLICY_TYPE);
policy.setTypeVersion(POLICY_TYPE_VERSION);
* 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");
* @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) {
}
}
- public class PolicyStatusRecords {
+ public static class PolicyStatusRecords {
private List<PdpPolicyStatus> records;
}
}
* 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");
resp = rawresp.readEntity(PdpGroupDeployResponse.class);
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), rawresp.getStatus());
assertTrue(resp.getErrorDetails().contains("unknown group"));
+ rawresp.close();
}
@Test
assertNull(resp.getErrorDetails());
assertThat(meterRegistry.counter(deploymentsCounterName, deploymentSuccessTag).count()).isEqualTo(2);
+ rawresp.close();
}
}
/*-
* ============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.
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(),
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<PolicyAudit> 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();
/*-
* ============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.
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;
private PdpPolicyStatus.PdpPolicyStatusBuilder statusBuilder;
+ private List<PdpPolicyStatus> statusList = new ArrayList<>();
+
/**
* Setup before tests.
*
.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
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
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
--- /dev/null
+/*-
+ * ============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());
+ }
+}
--- /dev/null
+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"
--- /dev/null
+{
+ "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": []
+ }
+ ]
+ }
+ ]
+}