Add get deployed endpoints for legacy policies 16/92616/2
authorChenfei Gao <cgao@research.att.com>
Fri, 2 Aug 2019 20:41:19 +0000 (16:41 -0400)
committerChenfei Gao <cgao@research.att.com>
Thu, 8 Aug 2019 20:08:47 +0000 (16:08 -0400)
Issue-ID: POLICY-1810
Change-Id: I47046fbbd7d319b58cabf57ff470ec0d5246c88a
Signed-off-by: Chenfei Gao <cgao@research.att.com>
main/src/main/java/org/onap/policy/api/main/rest/ApiRestController.java
main/src/main/java/org/onap/policy/api/main/rest/LegacyApiRestController.java
main/src/main/java/org/onap/policy/api/main/rest/provider/CommonModelProvider.java
main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyGuardPolicyProvider.java
main/src/main/java/org/onap/policy/api/main/rest/provider/LegacyOperationalPolicyProvider.java
main/src/main/java/org/onap/policy/api/main/rest/provider/PolicyProvider.java
main/src/main/java/org/onap/policy/api/main/startstop/ApiActivator.java
main/src/test/java/org/onap/policy/api/main/rest/TestApiRestServer.java
main/src/test/java/org/onap/policy/api/main/rest/provider/TestLegacyGuardPolicyProvider.java
main/src/test/java/org/onap/policy/api/main/rest/provider/TestLegacyOperationalPolicyProvider.java
main/src/test/java/org/onap/policy/api/main/rest/provider/TestPolicyProvider.java

index 30b004b..8c3d55f 100644 (file)
@@ -803,7 +803,7 @@ public class ApiRestController extends CommonRestController {
     }\r
 \r
     /**\r
-     * Retrieves deployed versions of a particular policy in pdp groups.\r
+     * Retrieves deployed versions of a particular policy in PDP groups.\r
      *\r
      * @param policyTypeId the ID of specified policy type\r
      * @param policyTypeVersion the version of specified policy type\r
index 54155a6..89ca042 100644 (file)
@@ -31,6 +31,7 @@ import io.swagger.annotations.Authorization;
 import io.swagger.annotations.Extension;
 import io.swagger.annotations.ExtensionProperty;
 import io.swagger.annotations.ResponseHeader;
+import java.util.List;
 import java.util.Map;
 import java.util.UUID;
 import javax.ws.rs.Consumes;
@@ -42,6 +43,7 @@ import javax.ws.rs.Path;
 import javax.ws.rs.PathParam;
 import javax.ws.rs.Produces;
 import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.tuple.Pair;
 import org.onap.policy.api.main.rest.provider.LegacyGuardPolicyProvider;
 import org.onap.policy.api.main.rest.provider.LegacyOperationalPolicyProvider;
 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
@@ -185,6 +187,65 @@ public class LegacyApiRestController extends CommonRestController {
         }
     }
 
+    /**
+     * Retrieves deployed versions of a particular guard policy in PDP groups.
+     *
+     * @param policyId the ID of specified policy
+     *
+     * @return the Response object containing the results of the API operation
+     */
+    @GET
+    @Path("/policytypes/onap.policies.controlloop.Guard/versions/1.0.0/"
+         + "policies/{policyId}/versions/deployed")
+    @ApiOperation(value = "Retrieve deployed versions of a particular guard policy in pdp groups",
+            notes = "Returns deployed versions of a specified guard policy in pdp groups",
+            response = LegacyGuardPolicyOutput.class, responseContainer = "Map",
+            responseHeaders = {
+                    @ResponseHeader(name = "X-MinorVersion",
+                                    description = "Used to request or communicate a MINOR version back from the client"
+                                                + " to the server, and from the server back to the client",
+                                    response = String.class),
+                    @ResponseHeader(name = "X-PatchVersion",
+                                    description = "Used only to communicate a PATCH version in a response for"
+                                                + " troubleshooting purposes only, and will not be provided by"
+                                                + " the client on request",
+                                    response = String.class),
+                    @ResponseHeader(name = "X-LatestVersion",
+                                    description = "Used only to communicate an API's latest version",
+                                    response = String.class),
+                    @ResponseHeader(name = "X-ONAP-RequestID",
+                                    description = "Used to track REST transactions for logging purpose",
+                                    response = UUID.class)
+            },
+            authorizations = @Authorization(value = "basicAuth"),
+            tags = { "Legacy Guard Policy", },
+            extensions = {
+                    @Extension(name = "interface info", properties = {
+                            @ExtensionProperty(name = "api-version", value = "1.0.0"),
+                            @ExtensionProperty(name = "last-mod-release", value = "Dublin")
+                    })
+            })
+    @ApiResponses(value = {
+            @ApiResponse(code = 401, message = "Authentication Error"),
+            @ApiResponse(code = 403, message = "Authorization Error"),
+            @ApiResponse(code = 404, message = "Resource Not Found"),
+            @ApiResponse(code = 500, message = "Internal Server Error")
+        })
+    public Response getDeployedVersionsOfGuardPolicy(
+            @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,
+            @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
+
+        try (LegacyGuardPolicyProvider guardPolicyProvider = new LegacyGuardPolicyProvider()) {
+            Map<Pair<String, String>, Map<String, LegacyGuardPolicyOutput>> deployedGuardPolicies =
+                    guardPolicyProvider.fetchDeployedGuardPolicies(policyId);
+            return makeOkResponse(requestId, deployedGuardPolicies);
+        } catch (PfModelException | PfModelRuntimeException pfme) {
+            LOGGER.error("GET /policytypes/onap.policies.controlloop.Guard/versions/1.0.0/"
+                + "policies/{}/versions/deployed", policyId, pfme);
+            return makeErrorResponse(requestId, pfme);
+        }
+    }
+
     /**
      * Creates a new guard policy.
      *
@@ -424,6 +485,65 @@ public class LegacyApiRestController extends CommonRestController {
         }
     }
 
+    /**
+     * Retrieves deployed versions of a particular operational policy in PDP groups.
+     *
+     * @param policyId the ID of specified policy
+     *
+     * @return the Response object containing the results of the API operation
+     */
+    @GET
+    @Path("/policytypes/onap.policies.controlloop.Operational/versions/1.0.0/"
+         + "policies/{policyId}/versions/deployed")
+    @ApiOperation(value = "Retrieve deployed versions of a particular operational policy in pdp groups",
+            notes = "Returns deployed versions of a specified operational policy in pdp groups",
+            response = LegacyOperationalPolicy.class, responseContainer = "List",
+            responseHeaders = {
+                    @ResponseHeader(name = "X-MinorVersion",
+                                    description = "Used to request or communicate a MINOR version back from the client"
+                                                + " to the server, and from the server back to the client",
+                                    response = String.class),
+                    @ResponseHeader(name = "X-PatchVersion",
+                                    description = "Used only to communicate a PATCH version in a response for"
+                                                + " troubleshooting purposes only, and will not be provided by"
+                                                + " the client on request",
+                                    response = String.class),
+                    @ResponseHeader(name = "X-LatestVersion",
+                                    description = "Used only to communicate an API's latest version",
+                                    response = String.class),
+                    @ResponseHeader(name = "X-ONAP-RequestID",
+                                    description = "Used to track REST transactions for logging purpose",
+                                    response = UUID.class)
+            },
+            authorizations = @Authorization(value = "basicAuth"),
+            tags = { "Legacy Operational Policy", },
+            extensions = {
+                    @Extension(name = "interface info", properties = {
+                            @ExtensionProperty(name = "api-version", value = "1.0.0"),
+                            @ExtensionProperty(name = "last-mod-release", value = "Dublin")
+                    })
+            })
+    @ApiResponses(value = {
+            @ApiResponse(code = 401, message = "Authentication Error"),
+            @ApiResponse(code = 403, message = "Authorization Error"),
+            @ApiResponse(code = 404, message = "Resource Not Found"),
+            @ApiResponse(code = 500, message = "Internal Server Error")
+        })
+    public Response getDeployedVersionsOfOperationalPolicy(
+            @PathParam("policyId") @ApiParam(value = "ID of policy", required = true) String policyId,
+            @HeaderParam("X-ONAP-RequestID") @ApiParam("RequestID for http transaction") UUID requestId) {
+
+        try (LegacyOperationalPolicyProvider operationalPolicyProvider = new LegacyOperationalPolicyProvider()) {
+            Map<Pair<String, String>, List<LegacyOperationalPolicy>> deployedOperationalPolicies =
+                    operationalPolicyProvider.fetchDeployedOperationalPolicies(policyId);
+            return makeOkResponse(requestId, deployedOperationalPolicies);
+        } catch (PfModelException | PfModelRuntimeException pfme) {
+            LOGGER.error("GET /policytypes/onap.policies.controlloop.Operational/versions/1.0.0/"
+                + "policies/{}/versions/deployed", policyId, pfme);
+            return makeErrorResponse(requestId, pfme);
+        }
+    }
+
     /**
      * Creates a new operational policy.
      *
index 6e9b52b..f3634b3 100644 (file)
 package org.onap.policy.api.main.rest.provider;\r
 \r
 import java.util.ArrayList;\r
+import java.util.HashMap;\r
 import java.util.List;\r
 import java.util.Map;\r
+import java.util.function.BiConsumer;\r
 import javax.ws.rs.core.Response;\r
+\r
+import org.apache.commons.lang3.tuple.Pair;\r
 import org.onap.policy.api.main.parameters.ApiParameterGroup;\r
 import org.onap.policy.common.parameters.ParameterService;\r
+import org.onap.policy.models.base.PfConceptKey;\r
 import org.onap.policy.models.base.PfModelException;\r
 import org.onap.policy.models.pdp.concepts.PdpGroup;\r
+import org.onap.policy.models.pdp.concepts.PdpGroupFilter;\r
+import org.onap.policy.models.pdp.concepts.PdpSubGroup;\r
+import org.onap.policy.models.pdp.enums.PdpState;\r
 import org.onap.policy.models.provider.PolicyModelsProvider;\r
 import org.onap.policy.models.provider.PolicyModelsProviderFactory;\r
 import org.onap.policy.models.provider.PolicyModelsProviderParameters;\r
 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;\r
+import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier;\r
+import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;\r
 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;\r
 \r
 /**\r
@@ -159,4 +169,176 @@ public class CommonModelProvider implements AutoCloseable {
         return "policy type with ID " + policyTypeId + ":" + policyTypeVersion\r
                         + " cannot be deleted as it is parameterized by policies " + parameterizedPolicies;\r
     }\r
-}\r
+\r
+    /**\r
+     * Collects all deployed versions of specified policy in all pdp groups.\r
+     *\r
+     * @param policyId the ID of policy\r
+     * @param policyType the concept key of policy type\r
+     * @param getter the custom generic getter Bifunction\r
+     * @param consumer the BiConsumer\r
+     * @param data the data structure storing retrieved deployed policies\r
+     *\r
+     * @return a map between pdp group and deployed versions of specified policy in that group\r
+     *\r
+     * @throws PfModelException the PfModel parsing exception\r
+     */\r
+    protected <T, R> Map<Pair<String, String>, T> collectDeployedPolicies(String policyId, PfConceptKey policyType,\r
+            BiFunctionWithEx<String, String, R> getter, BiConsumer<T, R> consumer, T data) throws PfModelException {\r
+\r
+        List<PdpGroup> pdpGroups = getPolicyTypeFilteredPdpGroups(policyType);\r
+        hasActivePdpGroup(pdpGroups, policyType, policyId);\r
+        return constructDeployedPolicyMap(pdpGroups, policyId, policyType, getter, consumer, data);\r
+    }\r
+\r
+    @FunctionalInterface\r
+    protected interface BiFunctionWithEx<T,U,R> {\r
+        public R apply(T value1, U value2) throws PfModelException;\r
+    }\r
+\r
+    /**\r
+     * Checks if the list of pdp groups is empty.\r
+     * If so, throws exception saying specified policy deployment is not found in all existing pdp groups.\r
+     *\r
+     * @param pdpGroups the list of pdp groups to check against\r
+     * @param policyType the concept key of policy type\r
+     * @param policyId the ID of policy\r
+     *\r
+     * @throws PfModelException the PfModel parsing exception\r
+     */\r
+    private void hasActivePdpGroup(List<PdpGroup> pdpGroups, PfConceptKey policyType, String policyId)\r
+            throws PfModelException {\r
+\r
+        if (pdpGroups.isEmpty()) {\r
+            throw new PfModelException(Response.Status.NOT_FOUND,\r
+                    constructDeploymentNotFoundMessage(policyType, policyId));\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Retrieves all pdp groups supporting specified policy type.\r
+     *\r
+     * @param policyTypeId the ID of policy type\r
+     * @param policyTypeVersion the version of policy type\r
+     *\r
+     * @return a list of pdp groups supporting specified policy type\r
+     *\r
+     * @throws PfModelException the PfModel parsing exception\r
+     */\r
+    private List<PdpGroup> getPolicyTypeFilteredPdpGroups(PfConceptKey policyType)\r
+            throws PfModelException {\r
+\r
+        List<ToscaPolicyTypeIdentifier> policyTypes = new ArrayList<>();\r
+        policyTypes.add(new ToscaPolicyTypeIdentifier(policyType.getName(), policyType.getVersion()));\r
+        PdpGroupFilter pdpGroupFilter = PdpGroupFilter.builder().policyTypeList(policyTypes)\r
+                .groupState(PdpState.ACTIVE).pdpState(PdpState.ACTIVE).build();\r
+        return modelsProvider.getFilteredPdpGroups(pdpGroupFilter);\r
+    }\r
+\r
+    /**\r
+     * Constructs the map of deployed pdp groups and deployed policies.\r
+     *\r
+     * @param pdpGroups the list of pdp groups that contain the specified policy\r
+     * @param policyId the ID of policy\r
+     * @param policyType the concept key of policy type\r
+     * @param getter the custom generic getter BiFunction\r
+     * @param consumer the BiConsumer\r
+     * @param data the data structure storing retrieved deployed policies\r
+     *\r
+     * @return the constructed map of pdp groups and deployed policies\r
+     *\r
+     * @throws PfModelException the PfModel parsing exception\r
+     */\r
+    private <T, R> Map<Pair<String, String>, T> constructDeployedPolicyMap(List<PdpGroup> pdpGroups, String policyId,\r
+            PfConceptKey policyType, BiFunctionWithEx<String, String, R> getter, BiConsumer<T, R> consumer, T data)\r
+                    throws PfModelException {\r
+\r
+        Map<Pair<String, String>, T> deployedPolicyMap = new HashMap<>();\r
+        for (PdpGroup pdpGroup : pdpGroups) {\r
+            List<ToscaPolicyIdentifier> policyIdentifiers = extractPolicyIdentifiers(policyId, pdpGroup, policyType);\r
+            T deployedPolicies = getDeployedPolicies(policyIdentifiers, policyType, getter, consumer, data);\r
+            deployedPolicyMap.put(Pair.of(pdpGroup.getName(), pdpGroup.getVersion()), deployedPolicies);\r
+        }\r
+        return deployedPolicyMap;\r
+    }\r
+\r
+    /**\r
+     * Extracts policy identifiers matching specified policy ID from specified pdp group.\r
+     *\r
+     * @param policyId the ID of policy to match\r
+     * @param pdpGroup the target pdp group to search\r
+     * @param policyType the concept key of policy type\r
+     *\r
+     * @return the list of policy identifiers\r
+     *\r
+     * @throws PfModelException the PfModel parsing exception\r
+     */\r
+    private List<ToscaPolicyIdentifier> extractPolicyIdentifiers(String policyId, PdpGroup pdpGroup,\r
+            PfConceptKey policyType) throws PfModelException {\r
+\r
+        List<ToscaPolicyIdentifier> policyIdentifiers = new ArrayList<>();\r
+        for (PdpSubGroup pdpSubGroup : pdpGroup.getPdpSubgroups()) {\r
+            for (ToscaPolicyIdentifier policyIdentifier : pdpSubGroup.getPolicies()) {\r
+                if (policyId.equalsIgnoreCase(policyIdentifier.getName())) {\r
+                    policyIdentifiers.add(policyIdentifier);\r
+                }\r
+            }\r
+        }\r
+        if (policyIdentifiers.isEmpty()) {\r
+            throw new PfModelException(Response.Status.NOT_FOUND,\r
+                    constructDeploymentNotFoundMessage(policyType, policyId));\r
+        }\r
+        return policyIdentifiers;\r
+    }\r
+\r
+    /**\r
+     * Retrieves deployed policies in a generic way.\r
+     *\r
+     * @param policyIdentifiers the identifiers of the policies to return\r
+     * @param policyType the concept key of current policy type\r
+     * @param getter the method reference of getting deployed policies\r
+     * @param consumer the method reference of consuming the returned policies\r
+     * @param data the data structure of deployed policies to return\r
+     *\r
+     * @return the generic type of policy data structure to return\r
+     *\r
+     * @throws PfModelException the PfModel parsing exception\r
+     */\r
+    private <T, R> T getDeployedPolicies(List<ToscaPolicyIdentifier> policyIdentifiers, PfConceptKey policyType,\r
+            BiFunctionWithEx<String, String, R> getter, BiConsumer<T, R> consumer, T data) throws PfModelException {\r
+\r
+        for (ToscaPolicyIdentifier policyIdentifier : policyIdentifiers) {\r
+            R result = getter.apply(policyIdentifier.getName(),\r
+                    getTrimedVersionForLegacyType(policyIdentifier.getVersion(), policyType));\r
+            consumer.accept(data, result);\r
+        }\r
+        return data;\r
+    }\r
+\r
+    /**\r
+     * Trims the version for legacy policies.\r
+     *\r
+     * @param fullVersion the full version format with major, minor, patch\r
+     * @param policyType the concept key of policy type\r
+     *\r
+     * @return the trimmed version\r
+     */\r
+    private String getTrimedVersionForLegacyType(String fullVersion, PfConceptKey policyType) {\r
+        return (policyType.getName().contains("guard")\r
+                || policyType.getName().contains("Operational")) ? fullVersion.split("\\.")[0] : fullVersion;\r
+    }\r
+\r
+    /**\r
+     * Constructs returned message for not found policy deployment.\r
+     *\r
+     * @param policyType the concept key of policy type\r
+     * @param policyId the ID of policy\r
+     *\r
+     * @return constructed message\r
+     */\r
+    private String constructDeploymentNotFoundMessage(PfConceptKey policyType, String policyId) {\r
+\r
+        return "could not find policy with ID " + policyId + " and type "\r
+                + policyType.getName() + ":" + policyType.getVersion() + " deployed in any pdp group";\r
+    }\r
+}
\ No newline at end of file
index d0032b0..978a8c0 100644 (file)
 package org.onap.policy.api.main.rest.provider;
 
 import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
-
+import java.util.Map.Entry;
 import javax.ws.rs.core.Response;
 
+import org.apache.commons.lang3.tuple.Pair;
+import org.onap.policy.models.base.PfConceptKey;
 import org.onap.policy.models.base.PfModelException;
 import org.onap.policy.models.pdp.concepts.PdpGroup;
 import org.onap.policy.models.pdp.concepts.PdpGroupFilter;
@@ -44,7 +48,16 @@ public class LegacyGuardPolicyProvider extends CommonModelProvider {
 
     private static final String INVALID_POLICY_VERSION = "legacy policy version is not an integer";
     private static final String LEGACY_MINOR_PATCH_SUFFIX = ".0.0";
-
+    private static final Map<String, PfConceptKey> GUARD_POLICY_TYPE_MAP = new LinkedHashMap<>();
+
+    static {
+        GUARD_POLICY_TYPE_MAP.put("guard.frequency.",
+                new PfConceptKey("onap.policies.controlloop.guard.FrequencyLimiter:1.0.0"));
+        GUARD_POLICY_TYPE_MAP.put("guard.minmax.",
+                new PfConceptKey("onap.policies.controlloop.guard.MinMax:1.0.0"));
+        GUARD_POLICY_TYPE_MAP.put("guard.blacklist.",
+                new PfConceptKey("onap.policies.controlloop.guard.Blacklist:1.0.0"));
+    }
 
     /**
      * Default constructor.
@@ -70,6 +83,22 @@ public class LegacyGuardPolicyProvider extends CommonModelProvider {
         return modelsProvider.getGuardPolicy(policyId, policyVersion);
     }
 
+    /**
+     * Retrieves a list of deployed guard policies in each pdp group.
+     *
+     * @param policyId the ID of the policy
+     *
+     * @return a list of deployed policies in each pdp group
+     *
+     * @throws PfModelException the PfModel parsing exception
+     */
+    public Map<Pair<String, String>, Map<String, LegacyGuardPolicyOutput>> fetchDeployedGuardPolicies(String policyId)
+            throws PfModelException {
+
+        return collectDeployedPolicies(
+                policyId, getGuardPolicyType(policyId), modelsProvider::getGuardPolicy, Map::putAll, new HashMap<>());
+    }
+
     /**
      * Creates a new guard policy.
      *
@@ -121,4 +150,23 @@ public class LegacyGuardPolicyProvider extends CommonModelProvider {
                     constructDeletePolicyViolationMessage(policyId, policyVersion, pdpGroups));
         }
     }
+
+    /**
+     * Retrieves guard policy type given guard policy ID.
+     *
+     * @param policyId the ID of guard policy
+     *
+     * @return the concept key of guard policy type
+     *
+     * @throws PfModelException the PfModel parsing exception
+     */
+    private PfConceptKey getGuardPolicyType(String policyId) throws PfModelException {
+
+        for (Entry<String, PfConceptKey> guardPolicyTypeEntry : GUARD_POLICY_TYPE_MAP.entrySet()) {
+            if (policyId.startsWith(guardPolicyTypeEntry.getKey())) {
+                return guardPolicyTypeEntry.getValue();
+            }
+        }
+        throw new PfModelException(Response.Status.BAD_REQUEST, "No policy type defined for " + policyId);
+    }
 }
\ No newline at end of file
index ac8fa26..8319de4 100644 (file)
@@ -24,9 +24,11 @@ package org.onap.policy.api.main.rest.provider;
 
 import java.util.ArrayList;
 import java.util.List;
-
+import java.util.Map;
 import javax.ws.rs.core.Response;
 
+import org.apache.commons.lang3.tuple.Pair;
+import org.onap.policy.models.base.PfConceptKey;
 import org.onap.policy.models.base.PfModelException;
 import org.onap.policy.models.pdp.concepts.PdpGroup;
 import org.onap.policy.models.pdp.concepts.PdpGroupFilter;
@@ -42,7 +44,8 @@ public class LegacyOperationalPolicyProvider extends CommonModelProvider {
 
     private static final String INVALID_POLICY_VERSION = "legacy policy version is not an integer";
     private static final String LEGACY_MINOR_PATCH_SUFFIX = ".0.0";
-
+    private static final PfConceptKey LEGACY_OPERATIONAL_TYPE =
+            new PfConceptKey("onap.policies.controlloop.Operational", "1.0.0");
 
     /**
      * Default constructor.
@@ -68,6 +71,22 @@ public class LegacyOperationalPolicyProvider extends CommonModelProvider {
         return modelsProvider.getOperationalPolicy(policyId, policyVersion);
     }
 
+    /**
+     * Retrieves a list of deployed operational policies in each pdp group.
+     *
+     * @param policyId the ID of the policy
+     *
+     * @return a list of deployed policies in each pdp group
+     *
+     * @throws PfModelException the PfModel parsing exception
+     */
+    public Map<Pair<String, String>, List<LegacyOperationalPolicy>> fetchDeployedOperationalPolicies(String policyId)
+            throws PfModelException {
+
+        return collectDeployedPolicies(
+                policyId, LEGACY_OPERATIONAL_TYPE, modelsProvider::getOperationalPolicy, List::add, new ArrayList<>());
+    }
+
     /**
      * Creates a new operational policy.
      *
index a4440da..66fd7f0 100644 (file)
 package org.onap.policy.api.main.rest.provider;\r
 \r
 import java.util.ArrayList;\r
-import java.util.HashMap;\r
 import java.util.List;\r
 import java.util.Map;\r
 import javax.ws.rs.core.Response;\r
 import org.apache.commons.lang3.tuple.Pair;\r
+import org.onap.policy.models.base.PfConceptKey;\r
 import org.onap.policy.models.base.PfModelException;\r
 import org.onap.policy.models.pdp.concepts.PdpGroup;\r
 import org.onap.policy.models.pdp.concepts.PdpGroupFilter;\r
-import org.onap.policy.models.pdp.concepts.PdpSubGroup;\r
-import org.onap.policy.models.pdp.enums.PdpState;\r
 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;\r
 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyFilter;\r
 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier;\r
@@ -122,25 +120,8 @@ public class PolicyProvider extends CommonModelProvider {
     public Map<Pair<String, String>, List<ToscaPolicy>> fetchDeployedPolicies(\r
             String policyTypeId, String policyTypeVersion, String policyId) throws PfModelException {\r
 \r
-        List<ToscaPolicyTypeIdentifier> policyTypes = new ArrayList<>();\r
-        policyTypes.add(new ToscaPolicyTypeIdentifier(policyTypeId, policyTypeVersion));\r
-        PdpGroupFilter pdpGroupFilter = PdpGroupFilter.builder().policyTypeList(policyTypes)\r
-                .groupState(PdpState.ACTIVE).pdpState(PdpState.ACTIVE).build();\r
-        List<PdpGroup> pdpGroups = modelsProvider.getFilteredPdpGroups(pdpGroupFilter);\r
-\r
-        if (pdpGroups.isEmpty()) {\r
-            throw new PfModelException(Response.Status.NOT_FOUND,\r
-                    constructDeploymentNotFoundMessage(policyTypeId, policyTypeVersion, policyId));\r
-        }\r
-\r
-        Map<Pair<String, String>, List<ToscaPolicy>> deployedPolicyMap =\r
-                constructDeployedPolicyMap(pdpGroups, policyId);\r
-        if (deployedPolicyMap.isEmpty()) {\r
-            throw new PfModelException(Response.Status.NOT_FOUND,\r
-                    constructDeploymentNotFoundMessage(policyTypeId, policyTypeVersion, policyId));\r
-        }\r
-\r
-        return deployedPolicyMap;\r
+        return collectDeployedPolicies(policyId, new PfConceptKey(policyTypeId, policyTypeVersion),\r
+                modelsProvider::getPolicyList, List::addAll, new ArrayList<>());\r
     }\r
 \r
     /**\r
@@ -264,55 +245,6 @@ public class PolicyProvider extends CommonModelProvider {
         }\r
     }\r
 \r
-    /**\r
-     * Constructs the map of deployed pdp groups and deployed policies.\r
-     *\r
-     * @param pdpGroups the list of pdp groups that contain the specified policy\r
-     * @param policyId the ID of policy\r
-     *\r
-     * @return the constructed map of pdp groups and deployed policies\r
-     *\r
-     * @throws PfModelException the PfModel parsing exception\r
-     */\r
-    private Map<Pair<String, String>, List<ToscaPolicy>> constructDeployedPolicyMap(\r
-            List<PdpGroup> pdpGroups, String policyId) throws PfModelException {\r
-\r
-        Map<Pair<String, String>, List<ToscaPolicy>> deployedPolicyMap = new HashMap<>();\r
-        for (PdpGroup pdpGroup : pdpGroups) {\r
-            List<ToscaPolicyIdentifier> policyIdentifiers = extractPolicyIdentifiers(policyId, pdpGroup);\r
-            List<ToscaPolicy> deployedPolicies = getDeployedPolicies(policyIdentifiers);\r
-            if (!deployedPolicies.isEmpty()) {\r
-                deployedPolicyMap.put(Pair.of(pdpGroup.getName(), pdpGroup.getVersion()), deployedPolicies);\r
-            }\r
-        }\r
-        return deployedPolicyMap;\r
-    }\r
-\r
-    private List<ToscaPolicyIdentifier> extractPolicyIdentifiers(String policyId, PdpGroup pdpGroup) {\r
-        List<ToscaPolicyIdentifier> policyIdentifiers = new ArrayList<>();\r
-        for (PdpSubGroup pdpSubGroup : pdpGroup.getPdpSubgroups()) {\r
-            for (ToscaPolicyIdentifier policyIdentifier : pdpSubGroup.getPolicies()) {\r
-                if (policyId.equalsIgnoreCase(policyIdentifier.getName())) {\r
-                    policyIdentifiers.add(policyIdentifier);\r
-                }\r
-            }\r
-        }\r
-        return policyIdentifiers;\r
-    }\r
-\r
-    private List<ToscaPolicy> getDeployedPolicies(List<ToscaPolicyIdentifier> policyIdentifiers)\r
-                    throws PfModelException {\r
-\r
-        List<ToscaPolicy> deployedPolicies = new ArrayList<>();\r
-        if (!policyIdentifiers.isEmpty()) {\r
-            for (ToscaPolicyIdentifier policyIdentifier : policyIdentifiers) {\r
-                deployedPolicies.addAll(\r
-                        modelsProvider.getPolicyList(policyIdentifier.getName(), policyIdentifier.getVersion()));\r
-            }\r
-        }\r
-        return deployedPolicies;\r
-    }\r
-\r
     /**\r
      * Constructs returned message for not found resource.\r
      *\r
@@ -329,21 +261,4 @@ public class PolicyProvider extends CommonModelProvider {
         return "policy with ID " + policyId + ":" + policyVersion\r
                 + " and type " + policyTypeId + ":" + policyTypeVersion + " does not exist";\r
     }\r
-\r
-    /**\r
-     * Constructs returned message for not found policy deployment.\r
-     *\r
-     * @param policyTypeId the ID of policy type\r
-     * @param policyTypeVersion the version of policy type\r
-     * @param policyId the ID of policy\r
-     * @param policyVersion the version of policy\r
-     *\r
-     * @return constructed message\r
-     */\r
-    private String constructDeploymentNotFoundMessage(String policyTypeId, String policyTypeVersion,\r
-            String policyId) {\r
-\r
-        return "could not find policy with ID " + policyId + " and type "\r
-                + policyTypeId + ":" + policyTypeVersion + " deployed in any pdp group";\r
-    }\r
 }\r
index 9708d5f..41e4e43 100644 (file)
@@ -146,4 +146,4 @@ public class ApiActivator {
     public static void setAlive(final boolean status) {
         alive = status;
     }
-}
+}
\ No newline at end of file
index 665616b..442f9db 100644 (file)
@@ -105,12 +105,17 @@ public class TestApiRestServer {
         + "onap.policies.monitoring.cdap.tca.hi.lo.app/versions/1.0.0/policies/onap.restart.tca/versions/1.0.0";
     private static final String POLICYTYPES_TCA_POLICIES_VCPE_LATEST = "policytypes/"
         + "onap.policies.monitoring.cdap.tca.hi.lo.app/versions/1.0.0/policies/onap.restart.tca/versions/latest";
+    private static final String POLICYTYPES_TCA_POLICIES_VCPE_DEPLOYED = "policytypes/"
+            + "onap.policies.monitoring.cdap.tca.hi.lo.app/versions/1.0.0/policies/onap.restart.tca/versions/deployed";
 
     private static final String GUARD_POLICIES =
             "policytypes/onap.policies.controlloop.Guard/versions/1.0.0/policies";
     private static final String GUARD_POLICIES_VDNS_FL_LATEST =
             "policytypes/onap.policies.controlloop.Guard/versions/1.0.0/policies/guard.frequency.scaleout"
             + "/versions/latest";
+    private static final String GUARD_POLICIES_VDNS_FL_DEPLOYED =
+            "policytypes/onap.policies.controlloop.Guard/versions/1.0.0/policies/guard.frequency.scaleout"
+            + "/versions/deployed";
     private static final String GUARD_POLICIES_VDNS_MINMAX_LATEST =
             "policytypes/onap.policies.controlloop.Guard/versions/1.0.0/policies/guard.minmax.scaleout"
             + "/versions/latest";
@@ -122,33 +127,23 @@ public class TestApiRestServer {
     private static final String OPS_POLICIES =
             "policytypes/onap.policies.controlloop.Operational/versions/1.0.0/policies";
     private static final String OPS_POLICIES_VCPE_LATEST =
-            "policytypes/onap.policies.controlloop.Guard/versions/1.0.0/policies/operational.restart"
+            "policytypes/onap.policies.controlloop.Operational/versions/1.0.0/policies/operational.restart"
             + "/versions/latest";
+    private static final String OPS_POLICIES_VCPE_DEPLOYED =
+            "policytypes/onap.policies.controlloop.Operational/versions/1.0.0/policies/operational.restart"
+            + "/versions/deployed";
     private static final String OPS_POLICIES_VDNS_LATEST =
-            "policytypes/onap.policies.controlloop.Guard/versions/1.0.0/policies/operational.scaleout"
+            "policytypes/onap.policies.controlloop.Operational/versions/1.0.0/policies/operational.scaleout"
             + "/versions/latest";
     private static final String OPS_POLICIES_VFIREWALL_LATEST =
-            "policytypes/onap.policies.controlloop.Guard/versions/1.0.0/policies/operational.modifyconfig"
+            "policytypes/onap.policies.controlloop.Operational/versions/1.0.0/policies/operational.modifyconfig"
             + "/versions/latest";
     private static final String OPS_POLICIES_VCPE_VERSION = "policytypes/"
-        + "onap.policies.controlloop.Guard/versions/1.0.0/policies/operational.restart/versions/1";
+        + "onap.policies.controlloop.Operational/versions/1.0.0/policies/operational.restart/versions/1";
     private static final String OPS_POLICIES_VDNS_VERSION = "policytypes/"
-        + "onap.policies.controlloop.Guard/versions/1.0.0/policies/operational.scaleout/versions/1";
+        + "onap.policies.controlloop.Operational/versions/1.0.0/policies/operational.scaleout/versions/1";
     private static final String OPS_POLICIES_VFIREWALL_VERSION = "policytypes/"
-        + "onap.policies.controlloop.Guard/versions/1.0.0/policies/operational.modifyconfig/versions/1";
-
-    private static final String GET_DEPLOYED_VERSION_OF_POLICY =
-            "policytypes/onap.policies.monitoring.cdap.tca.hi.lo.app/versions/"
-        + "1.0.0/policies/onap.restart.tca/versions/deployed";
-    private static final String GET_LATEST_VERSION_OF_OPERATIONAL_POLICY =
-            "policytypes/onap.policies.controlloop.Operational/versions/"
-            + "1.0.0/policies/operational.scaleout/versions/latest";
-    private static final String GET_SPECIFIC_VERSION_OF_OPERATIONAL_POLICY =
-            "policytypes/onap.policies.controlloop.Operational/versions/"
-            + "1.0.0/policies/operational.scaleout/versions/3";
-    private static final String DEL_SPECIFIC_VERSION_OF_OPERATIONAL_POLICY =
-            "policytypes/onap.policies.controlloop.Operational/versions/1.0.0/"
-                    + "policies/operational.scaleout/versions/1";
+        + "onap.policies.controlloop.Operational/versions/1.0.0/policies/operational.modifyconfig/versions/1";
 
     private static final String KEYSTORE = System.getProperty("user.dir") + "/src/test/resources/ssl/policy-keystore";
     private static final CommonTestData COMMON_TEST_DATA = new CommonTestData();
@@ -567,6 +562,15 @@ public class TestApiRestServer {
         }).doesNotThrowAnyException();
     }
 
+    @Test
+    public void testGetDeployedVersionsOfGuardPolicy() {
+        assertThatCode(() -> {
+            main = startApiService(true);
+            Response rawResponse = readResource(GUARD_POLICIES_VDNS_FL_DEPLOYED, true);
+            assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus());
+        }).doesNotThrowAnyException();
+    }
+
     @Test
     public void testDeleteOperationalPolicy() {
 
@@ -638,7 +642,7 @@ public class TestApiRestServer {
     public void testGetDeployedVersionsOfPolicy() {
         assertThatCode(() -> {
             main = startApiService(true);
-            Response rawResponse = readResource(GET_DEPLOYED_VERSION_OF_POLICY, true);
+            Response rawResponse = readResource(POLICYTYPES_TCA_POLICIES_VCPE_DEPLOYED, true);
             assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus());
         }).doesNotThrowAnyException();
     }
@@ -647,7 +651,7 @@ public class TestApiRestServer {
     public void testGetLatestVersionOfOperationalPolicy() {
         assertThatCode(() -> {
             main = startApiService(true);
-            Response rawResponse = readResource(GET_LATEST_VERSION_OF_OPERATIONAL_POLICY, true);
+            Response rawResponse = readResource(OPS_POLICIES_VDNS_LATEST, true);
             assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), rawResponse.getStatus());
         }).doesNotThrowAnyException();
     }
@@ -656,16 +660,25 @@ public class TestApiRestServer {
     public void testGetSpecificVersionOfOperationalPolicy() {
         assertThatCode(() -> {
             main = startApiService(true);
-            Response rawResponse = readResource(GET_SPECIFIC_VERSION_OF_OPERATIONAL_POLICY, true);
+            Response rawResponse = readResource(OPS_POLICIES_VDNS_VERSION, true);
             assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), rawResponse.getStatus());
         }).doesNotThrowAnyException();
     }
 
+    @Test
+    public void testGetDeployedVersionsOfOperationalPolicy() {
+        assertThatCode(() -> {
+            main = startApiService(true);
+            Response rawResponse = readResource(OPS_POLICIES_VCPE_DEPLOYED, true);
+            assertEquals(Response.Status.NOT_FOUND.getStatusCode(), rawResponse.getStatus());
+        }).doesNotThrowAnyException();
+    }
+
     @Test
     public void testDeleteSpecificVersionOfOperationalPolicy() {
         assertThatCode(() -> {
             main = startApiService(true);
-            Response rawResponse = deleteResource(DEL_SPECIFIC_VERSION_OF_OPERATIONAL_POLICY, true);
+            Response rawResponse = deleteResource(OPS_POLICIES_VDNS_VERSION, true);
             assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), rawResponse.getStatus());
         }).doesNotThrowAnyException();
     }
index 6091e1d..1f0077d 100644 (file)
@@ -77,7 +77,12 @@ public class TestLegacyGuardPolicyProvider {
     private static final String POLICY_TYPE_RESOURCE =
             "policytypes/onap.policies.controlloop.guard.FrequencyLimiter.json";
     private static final String POLICY_TYPE_ID = "onap.policies.controlloop.guard.FrequencyLimiter:1.0.0";
+    private static final String POLICY_TYPE_NAME = "onap.policies.controlloop.guard.FrequencyLimiter";
+    private static final String POLICY_TYPE_VERSION = "1.0.0";
     private static final String POLICY_ID = "guard.frequency.scaleout:1.0.0";
+    private static final String POLICY_NAME = "guard.frequency.scaleout";
+    private static final String POLICY_VERSION = "1";
+    private static final String LEGACY_MINOR_PATCH_SUFFIX = ".0.0";
 
     /**
      * Initializes parameters.
@@ -171,6 +176,102 @@ public class TestLegacyGuardPolicyProvider {
         }).doesNotThrowAnyException();
     }
 
+    @Test
+    public void testFetchDeployedGuardPolicies() {
+
+        assertThatThrownBy(() -> {
+            guardPolicyProvider.fetchDeployedGuardPolicies("dummy");
+        }).hasMessage("No policy type defined for dummy");
+
+        try (PolicyModelsProvider databaseProvider =
+                new PolicyModelsProviderFactory().createPolicyModelsProvider(providerParams)) {
+            assertEquals(0, databaseProvider.getPdpGroups("name").size());
+            assertEquals(0, databaseProvider.getFilteredPdpGroups(PdpGroupFilter.builder().build()).size());
+
+            assertNotNull(databaseProvider.createPdpGroups(new ArrayList<>()));
+            assertNotNull(databaseProvider.updatePdpGroups(new ArrayList<>()));
+
+            PdpGroup pdpGroup = new PdpGroup();
+            pdpGroup.setName("group");
+            pdpGroup.setVersion("1.2.3");
+            pdpGroup.setPdpGroupState(PdpState.ACTIVE);
+            pdpGroup.setPdpSubgroups(new ArrayList<>());
+            List<PdpGroup> groupList = new ArrayList<>();
+            groupList.add(pdpGroup);
+
+            PdpSubGroup pdpSubGroup = new PdpSubGroup();
+            pdpSubGroup.setPdpType("type");
+            pdpSubGroup.setDesiredInstanceCount(123);
+            pdpSubGroup.setSupportedPolicyTypes(new ArrayList<>());
+            pdpSubGroup.getSupportedPolicyTypes().add(new ToscaPolicyTypeIdentifier(
+                    POLICY_TYPE_NAME, POLICY_TYPE_VERSION));
+            pdpGroup.getPdpSubgroups().add(pdpSubGroup);
+
+            Pdp pdp = new Pdp();
+            pdp.setInstanceId("type-0");
+            pdp.setMessage("Hello");
+            pdp.setPdpState(PdpState.ACTIVE);
+            pdp.setHealthy(PdpHealthStatus.UNKNOWN);
+            pdpSubGroup.setPdpInstances(new ArrayList<>());
+            pdpSubGroup.getPdpInstances().add(pdp);
+
+            // Create Pdp Groups
+            assertEquals(123, databaseProvider.createPdpGroups(groupList).get(0).getPdpSubgroups().get(0)
+                    .getDesiredInstanceCount());
+            assertEquals(1, databaseProvider.getPdpGroups("group").size());
+
+            // Create Policy Type
+            assertThatCode(() -> {
+                String policyTypeString = ResourceUtils.getResourceAsString(POLICY_TYPE_RESOURCE);
+                ToscaServiceTemplate policyTypeServiceTemplate =
+                        standardCoder.decode(policyTypeString, ToscaServiceTemplate.class);
+                policyTypeProvider.createPolicyType(policyTypeServiceTemplate);
+            }).doesNotThrowAnyException();
+
+            // Create Policy
+            assertThatCode(() -> {
+                String policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE);
+                LegacyGuardPolicyInput policyToCreate =
+                        standardCoder.decode(policyString, LegacyGuardPolicyInput.class);
+                Map<String, LegacyGuardPolicyOutput> policyCreated = guardPolicyProvider
+                        .createGuardPolicy(policyToCreate);
+                assertFalse(policyCreated.isEmpty());
+            }).doesNotThrowAnyException();
+
+            // Test fetchDeployedPolicies (deployedPolicyMap.isEmpty())==true
+            assertThatThrownBy(
+                () -> {
+                    guardPolicyProvider.fetchDeployedGuardPolicies(POLICY_NAME);
+                }).hasMessage("could not find policy with ID " + POLICY_NAME + " and type "
+                    + POLICY_TYPE_ID + " deployed in any pdp group");
+
+
+            // Update pdpSubGroup
+            pdpSubGroup.setPolicies(new ArrayList<>());
+            pdpSubGroup.getPolicies().add(
+                    new ToscaPolicyIdentifier(POLICY_NAME, POLICY_VERSION + LEGACY_MINOR_PATCH_SUFFIX));
+            assertEquals(1, databaseProvider.createPdpGroups(groupList).get(0).getPdpSubgroups().get(0)
+                    .getPolicies().size());
+
+            // Test fetchDeployedPolicies
+            assertThatCode(
+                () -> {
+                    guardPolicyProvider.fetchDeployedGuardPolicies(POLICY_NAME);
+                }).doesNotThrowAnyException();
+
+            // Test validateDeleteEligibility exception path(!pdpGroups.isEmpty())
+            assertThatThrownBy(
+                () -> {
+                    guardPolicyProvider.deleteGuardPolicy(
+                            POLICY_NAME, POLICY_VERSION);
+                }).hasMessageContaining("policy with ID " + POLICY_NAME + ":" + POLICY_VERSION
+                    + " cannot be deleted as it is deployed in pdp groups");
+        }
+        catch (Exception exc) {
+            fail("Test should not throw an exception");
+        }
+    }
+
     @Test
     public void testCreateGuardPolicy() {
 
index 2915f12..2479223 100644 (file)
@@ -25,6 +25,7 @@ package org.onap.policy.api.main.rest.provider;
 import static org.assertj.core.api.Assertions.assertThatCode;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
@@ -72,6 +73,11 @@ public class TestLegacyOperationalPolicyProvider {
     private static final String POLICY_TYPE_RESOURCE = "policytypes/onap.policies.controlloop.Operational.json";
     private static final String POLICY_TYPE_ID = "onap.policies.controlloop.Operational:1.0.0";
     private static final String POLICY_ID = "operational.restart:1.0.0";
+    private static final String POLICY_NAME = "operational.restart";
+    private static final String POLICY_VERSION = "1";
+    private static final String POLICY_TYPE_NAME = "onap.policies.controlloop.Operational";
+    private static final String POLICY_TYPE_VERSION = "1.0.0";
+    private static final String LEGACY_MINOR_PATCH_SUFFIX = ".0.0";
 
     /**
      * Initializes parameters.
@@ -162,6 +168,104 @@ public class TestLegacyOperationalPolicyProvider {
         }).doesNotThrowAnyException();
     }
 
+    @Test
+    public void testFetchDeployedOperationalPolicies() {
+
+        assertThatThrownBy(() -> {
+            operationalPolicyProvider.fetchDeployedOperationalPolicies("dummy");
+        }).hasMessage("could not find policy with ID dummy and type " + POLICY_TYPE_ID + " deployed in any pdp group");
+
+        try (PolicyModelsProvider databaseProvider =
+                new PolicyModelsProviderFactory().createPolicyModelsProvider(providerParams)) {
+            assertEquals(0, databaseProvider.getPdpGroups("name").size());
+            assertEquals(0, databaseProvider.getFilteredPdpGroups(PdpGroupFilter.builder().build()).size());
+
+            assertNotNull(databaseProvider.createPdpGroups(new ArrayList<>()));
+            assertNotNull(databaseProvider.updatePdpGroups(new ArrayList<>()));
+
+            PdpGroup pdpGroup = new PdpGroup();
+            pdpGroup.setName("group");
+            pdpGroup.setVersion("1.2.3");
+            pdpGroup.setPdpGroupState(PdpState.ACTIVE);
+            pdpGroup.setPdpSubgroups(new ArrayList<>());
+            List<PdpGroup> groupList = new ArrayList<>();
+            groupList.add(pdpGroup);
+
+            PdpSubGroup pdpSubGroup = new PdpSubGroup();
+            pdpSubGroup.setPdpType("type");
+            pdpSubGroup.setDesiredInstanceCount(123);
+            pdpSubGroup.setSupportedPolicyTypes(new ArrayList<>());
+            pdpSubGroup.getSupportedPolicyTypes().add(new ToscaPolicyTypeIdentifier(
+                    POLICY_TYPE_NAME, POLICY_TYPE_VERSION));
+            pdpGroup.getPdpSubgroups().add(pdpSubGroup);
+
+            Pdp pdp = new Pdp();
+            pdp.setInstanceId("type-0");
+            pdp.setMessage("Hello");
+            pdp.setPdpState(PdpState.ACTIVE);
+            pdp.setHealthy(PdpHealthStatus.UNKNOWN);
+            pdpSubGroup.setPdpInstances(new ArrayList<>());
+            pdpSubGroup.getPdpInstances().add(pdp);
+
+            // Create Pdp Groups
+            assertEquals(123, databaseProvider.createPdpGroups(groupList).get(0).getPdpSubgroups().get(0)
+                    .getDesiredInstanceCount());
+            assertEquals(1, databaseProvider.getPdpGroups("group").size());
+
+            // Create Policy Type
+            assertThatCode(() -> {
+                String policyTypeString = ResourceUtils.getResourceAsString(POLICY_TYPE_RESOURCE);
+                ToscaServiceTemplate policyTypeServiceTemplate =
+                        standardCoder.decode(policyTypeString, ToscaServiceTemplate.class);
+                policyTypeProvider.createPolicyType(policyTypeServiceTemplate);
+            }).doesNotThrowAnyException();
+
+            // Create Policy
+            assertThatCode(() -> {
+                String policyString = ResourceUtils.getResourceAsString(POLICY_RESOURCE);
+                LegacyOperationalPolicy policyToCreate =
+                        standardCoder.decode(policyString, LegacyOperationalPolicy.class);
+                LegacyOperationalPolicy policyCreated = operationalPolicyProvider
+                        .createOperationalPolicy(policyToCreate);
+                assertEquals("operational.restart", policyCreated.getPolicyId());
+                assertEquals("1", policyCreated.getPolicyVersion());
+                assertFalse(policyCreated.getContent() == null);
+            }).doesNotThrowAnyException();
+
+            // Test fetchDeployedPolicies (deployedPolicyMap.isEmpty())==true
+            assertThatThrownBy(
+                () -> {
+                    operationalPolicyProvider.fetchDeployedOperationalPolicies(POLICY_NAME);
+                }).hasMessage("could not find policy with ID " + POLICY_NAME + " and type "
+                    + POLICY_TYPE_ID + " deployed in any pdp group");
+
+
+            // Update pdpSubGroup
+            pdpSubGroup.setPolicies(new ArrayList<>());
+            pdpSubGroup.getPolicies().add(
+                    new ToscaPolicyIdentifier(POLICY_NAME, POLICY_VERSION + LEGACY_MINOR_PATCH_SUFFIX));
+            assertEquals(1, databaseProvider.createPdpGroups(groupList).get(0).getPdpSubgroups().get(0)
+                    .getPolicies().size());
+
+            // Test fetchDeployedPolicies
+            assertThatCode(
+                () -> {
+                    operationalPolicyProvider.fetchDeployedOperationalPolicies(POLICY_NAME);
+                }).doesNotThrowAnyException();
+
+            // Test validateDeleteEligibility exception path(!pdpGroups.isEmpty())
+            assertThatThrownBy(
+                () -> {
+                    operationalPolicyProvider.deleteOperationalPolicy(
+                            POLICY_NAME, POLICY_VERSION);
+                }).hasMessageContaining("policy with ID " + POLICY_NAME + ":" + POLICY_VERSION
+                    + " cannot be deleted as it is deployed in pdp groups");
+        }
+        catch (Exception exc) {
+            fail("Test should not throw an exception");
+        }
+    }
+
     @Test
     public void testCreateOperationalPolicy() {
 
index 3954106..ea88637 100644 (file)
@@ -141,8 +141,8 @@ public class TestPolicyProvider {
 
         //Basic Exception Throw
         assertThatThrownBy(() -> {
-            policyProvider.fetchDeployedPolicies("dummy", "dummy", "dummy");
-        }).hasMessage("could not find policy with ID dummy and type dummy:dummy deployed in any pdp group");
+            policyProvider.fetchDeployedPolicies("dummy", "1.0.0", "dummy");
+        }).hasMessage("could not find policy with ID dummy and type dummy:1.0.0 deployed in any pdp group");
 
         try (PolicyModelsProvider databaseProvider =
                 new PolicyModelsProviderFactory().createPolicyModelsProvider(providerParams)) {