Changes for Checkstyle 8.32
[policy/api.git] / main / src / main / java / org / onap / policy / api / main / rest / provider / CommonModelProvider.java
index 6e9b52b..03f46b9 100644 (file)
@@ -2,7 +2,8 @@
  * ============LICENSE_START=======================================================\r
  * ONAP Policy API\r
  * ================================================================================\r
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.\r
+ * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.\r
+ * Modifications Copyright (C) 2019-2020 Nordix Foundation.\r
  * ================================================================================\r
  * Licensed under the Apache License, Version 2.0 (the "License");\r
  * you may not use this file except in compliance with the License.\r
 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
+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.ToscaServiceTemplate;\r
+import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier;\r
+import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;\r
 \r
 /**\r
  * Super class for providers that use a model provider.\r
@@ -67,96 +75,174 @@ public class CommonModelProvider implements AutoCloseable {
     }\r
 \r
     /**\r
-     * Checks if service template contains any policy.\r
+     * Collects all deployed versions of specified policy in all pdp groups.\r
      *\r
-     * @param serviceTemplate the service template to check against\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
-     * @return boolean whether service template contains any policy\r
+     * @throws PfModelException the PfModel parsing exception\r
      */\r
-    protected boolean hasPolicy(ToscaServiceTemplate serviceTemplate) {\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
-        return hasData(serviceTemplate.getToscaTopologyTemplate().getPolicies());\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 service template contains any policy type.\r
+     * Checks if the list of pdp groups is empty. If so, throws exception saying specified policy deployment is not\r
+     * found in all existing pdp groups.\r
      *\r
-     * @param serviceTemplate the service template to check against\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
-     * @return boolean whether service template contains any policy type\r
+     * @throws PfModelException the PfModel parsing exception\r
      */\r
-    protected boolean hasPolicyType(ToscaServiceTemplate serviceTemplate) {\r
+    private void hasActivePdpGroup(List<PdpGroup> pdpGroups, PfConceptKey policyType, String policyId)\r
+            throws PfModelException {\r
 \r
-        return hasData(serviceTemplate.getPolicyTypes());\r
+        if (pdpGroups.isEmpty()) {\r
+            throw new PfModelException(Response.Status.NOT_FOUND,\r
+                    constructDeploymentNotFoundMessage(policyType, policyId));\r
+        }\r
     }\r
 \r
     /**\r
-     * Checks if the first element of a list contains data.\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
-     * @param list list to be examined\r
-     * @return {@code true} if the list contains data, {@code false} otherwise\r
+     * @return a list of pdp groups supporting specified policy type\r
+     *\r
+     * @throws PfModelException the PfModel parsing exception\r
      */\r
-    protected <T> boolean hasData(List<Map<String, T>> list) {\r
+    private List<PdpGroup> getPolicyTypeFilteredPdpGroups(PfConceptKey policyType) throws PfModelException {\r
 \r
-        return (list != null && !list.isEmpty() && !list.get(0).isEmpty());\r
+        List<ToscaPolicyTypeIdentifier> policyTypes = new ArrayList<>();\r
+        policyTypes.add(new ToscaPolicyTypeIdentifier(policyType.getName(), policyType.getVersion()));\r
+        PdpGroupFilter pdpGroupFilter = PdpGroupFilter.builder().policyTypeList(policyTypes).groupState(PdpState.ACTIVE)\r
+                .pdpState(PdpState.ACTIVE).build();\r
+        return modelsProvider.getFilteredPdpGroups(pdpGroupFilter);\r
     }\r
 \r
     /**\r
-     * Validates that some text represents a number.\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
-     * @param text text to be validated\r
-     * @param errorMsg error message included in the exception, if the text is not a valid\r
-     *        number\r
-     * @throws PfModelException if the text is not a valid number\r
+     * @throws PfModelException the PfModel parsing exception\r
      */\r
-    protected void validNumber(String text, String errorMsg) throws PfModelException {\r
-        try {\r
-            Integer.parseInt(text);\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
-        } catch (NumberFormatException exc) {\r
-            throw new PfModelException(Response.Status.BAD_REQUEST, errorMsg, exc);\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
-     * Constructs returned message for policy delete rule violation.\r
+     * Extracts policy identifiers matching specified policy ID from specified pdp group.\r
      *\r
-     * @param policyId the ID of policy\r
-     * @param policyVersion the version of policy\r
-     * @param pdpGroups the list of pdp groups\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
-     * @return the constructed message\r
+     * @throws PfModelException the PfModel parsing exception\r
      */\r
-    protected String constructDeletePolicyViolationMessage(String policyId, String policyVersion,\r
-                    List<PdpGroup> pdpGroups) {\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
-        List<String> pdpGroupNameVersionList = new ArrayList<>(pdpGroups.size());\r
-        for (PdpGroup pdpGroup : pdpGroups) {\r
-            pdpGroupNameVersionList.add(pdpGroup.getName() + ":" + pdpGroup.getVersion());\r
+        for (ToscaPolicyIdentifier policyIdentifier : policyIdentifiers) {\r
+            R result = getter.apply(policyIdentifier.getName(),\r
+                    getTrimedVersionForLegacyType(policyIdentifier.getVersion(), policyType));\r
+            consumer.accept(data, result);\r
         }\r
-        String deployedPdpGroups = String.join(",", pdpGroupNameVersionList);\r
-        return "policy with ID " + policyId + ":" + policyVersion\r
-                        + " cannot be deleted as it is deployed in pdp groups " + deployedPdpGroups;\r
+        return data;\r
     }\r
 \r
     /**\r
-     * Constructs returned message for policy type delete rule violation.\r
+     * Trims the version for legacy policies.\r
      *\r
-     * @param policyTypeId the ID of policy type\r
-     * @param policyTypeVersion the version of policy type\r
-     * @param policies the list of policies that parameterizes specified policy type\r
+     * @param fullVersion the full version format with major, minor, patch\r
+     * @param policyType the concept key of policy type\r
      *\r
-     * @return the constructed message\r
+     * @return the trimmed version\r
      */\r
-    protected String constructDeletePolicyTypeViolationMessage(String policyTypeId, String policyTypeVersion,\r
-                    List<ToscaPolicy> policies) {\r
+    private String getTrimedVersionForLegacyType(String fullVersion, PfConceptKey policyType) {\r
+        return (policyType.getName().contains("guard") || policyType.getName().contains("Operational"))\r
+                ? fullVersion.split("\\.")[0]\r
+                : fullVersion;\r
+    }\r
 \r
-        List<String> policyNameVersionList = new ArrayList<>(policies.size());\r
-        for (ToscaPolicy policy : policies) {\r
-            policyNameVersionList.add(policy.getName() + ":" + policy.getVersion());\r
-        }\r
-        String parameterizedPolicies = String.join(",", policyNameVersionList);\r
-        return "policy type with ID " + policyTypeId + ":" + policyTypeVersion\r
-                        + " cannot be deleted as it is parameterized by policies " + parameterizedPolicies;\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 " + policyType.getName() + ":"\r
+                + policyType.getVersion() + " deployed in any pdp group";\r
     }\r
 }\r