Knock on of changing policy types to map
[policy/api.git] / main / src / main / java / org / onap / policy / api / main / rest / provider / CommonModelProvider.java
1 /*-\r
2  * ============LICENSE_START=======================================================\r
3  * ONAP Policy API\r
4  * ================================================================================\r
5  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.\r
6  * Modifications Copyright (C) 2019 Nordix Foundation.\r
7  * ================================================================================\r
8  * Licensed under the Apache License, Version 2.0 (the "License");\r
9  * you may not use this file except in compliance with the License.\r
10  * You may obtain a copy of the License at\r
11  *\r
12  *      http://www.apache.org/licenses/LICENSE-2.0\r
13  *\r
14  * Unless required by applicable law or agreed to in writing, software\r
15  * distributed under the License is distributed on an "AS IS" BASIS,\r
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
17  * See the License for the specific language governing permissions and\r
18  * limitations under the License.\r
19  *\r
20  * SPDX-License-Identifier: Apache-2.0\r
21  * ============LICENSE_END=========================================================\r
22  */\r
23 \r
24 package org.onap.policy.api.main.rest.provider;\r
25 \r
26 import java.util.ArrayList;\r
27 import java.util.HashMap;\r
28 import java.util.List;\r
29 import java.util.Map;\r
30 import java.util.function.BiConsumer;\r
31 import javax.ws.rs.core.Response;\r
32 \r
33 import org.apache.commons.lang3.tuple.Pair;\r
34 import org.onap.policy.api.main.parameters.ApiParameterGroup;\r
35 import org.onap.policy.common.parameters.ParameterService;\r
36 import org.onap.policy.models.base.PfConceptKey;\r
37 import org.onap.policy.models.base.PfModelException;\r
38 import org.onap.policy.models.pdp.concepts.PdpGroup;\r
39 import org.onap.policy.models.pdp.concepts.PdpGroupFilter;\r
40 import org.onap.policy.models.pdp.concepts.PdpSubGroup;\r
41 import org.onap.policy.models.pdp.enums.PdpState;\r
42 import org.onap.policy.models.provider.PolicyModelsProvider;\r
43 import org.onap.policy.models.provider.PolicyModelsProviderFactory;\r
44 import org.onap.policy.models.provider.PolicyModelsProviderParameters;\r
45 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;\r
46 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyIdentifier;\r
47 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;\r
48 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;\r
49 \r
50 /**\r
51  * Super class for providers that use a model provider.\r
52  */\r
53 public class CommonModelProvider implements AutoCloseable {\r
54 \r
55     protected final PolicyModelsProvider modelsProvider;\r
56 \r
57     /**\r
58      * Constructs the object, populating {@link #modelsProvider}.\r
59      *\r
60      * @throws PfModelException if an error occurs\r
61      */\r
62     public CommonModelProvider() throws PfModelException {\r
63 \r
64         ApiParameterGroup parameterGroup = ParameterService.get("ApiGroup");\r
65         PolicyModelsProviderParameters providerParameters = parameterGroup.getDatabaseProviderParameters();\r
66         modelsProvider = new PolicyModelsProviderFactory().createPolicyModelsProvider(providerParameters);\r
67     }\r
68 \r
69     /**\r
70      * Closes the connection to database.\r
71      *\r
72      * @throws PfModelException the PfModel parsing exception\r
73      */\r
74     @Override\r
75     public void close() throws PfModelException {\r
76 \r
77         modelsProvider.close();\r
78     }\r
79 \r
80     /**\r
81      * Checks if service template contains any policy.\r
82      *\r
83      * @param serviceTemplate the service template to check against\r
84      *\r
85      * @return boolean whether service template contains any policy\r
86      */\r
87     protected boolean hasPolicy(ToscaServiceTemplate serviceTemplate) {\r
88 \r
89         return hasData(serviceTemplate.getToscaTopologyTemplate().getPolicies());\r
90     }\r
91 \r
92     /**\r
93      * Checks if service template contains any policy type.\r
94      *\r
95      * @param serviceTemplate the service template to check against\r
96      *\r
97      * @return boolean whether service template contains any policy type\r
98      */\r
99     protected boolean hasPolicyType(ToscaServiceTemplate serviceTemplate) {\r
100 \r
101         return hasData(serviceTemplate.getPolicyTypes());\r
102     }\r
103 \r
104     /**\r
105      * Checks if the first element of a list of maps contains data.\r
106      *\r
107      * @param listOfMapsToCheck list of maps to be examined\r
108      * @return {@code true} if the list contains data, {@code false} otherwise\r
109      */\r
110     protected <T> boolean hasData(List<Map<String, T>> listOfMapsToCheck) {\r
111 \r
112         return (listOfMapsToCheck != null && !listOfMapsToCheck.isEmpty() && !listOfMapsToCheck.get(0).isEmpty());\r
113     }\r
114 \r
115 \r
116     /**\r
117      * Checks if a maps contains data.\r
118      *\r
119      * @param mapToCheck map to be examined\r
120      * @return {@code true} if the list contains data, {@code false} otherwise\r
121      */\r
122     protected <T> boolean hasData(Map<String, T> mapToCheck) {\r
123 \r
124         return (mapToCheck != null && !mapToCheck.isEmpty());\r
125     }\r
126 \r
127     /**\r
128      * Validates that some text represents a number.\r
129      *\r
130      * @param text text to be validated\r
131      * @param errorMsg error message included in the exception, if the text is not a valid\r
132      *        number\r
133      * @throws PfModelException if the text is not a valid number\r
134      */\r
135     protected void validNumber(String text, String errorMsg) throws PfModelException {\r
136         try {\r
137             Integer.parseInt(text);\r
138 \r
139         } catch (NumberFormatException exc) {\r
140             throw new PfModelException(Response.Status.BAD_REQUEST, errorMsg, exc);\r
141         }\r
142     }\r
143 \r
144     /**\r
145      * Constructs returned message for policy delete rule violation.\r
146      *\r
147      * @param policyId the ID of policy\r
148      * @param policyVersion the version of policy\r
149      * @param pdpGroups the list of pdp groups\r
150      *\r
151      * @return the constructed message\r
152      */\r
153     protected String constructDeletePolicyViolationMessage(String policyId, String policyVersion,\r
154                     List<PdpGroup> pdpGroups) {\r
155 \r
156         List<String> pdpGroupNameVersionList = new ArrayList<>(pdpGroups.size());\r
157         for (PdpGroup pdpGroup : pdpGroups) {\r
158             pdpGroupNameVersionList.add(pdpGroup.getName() + ":" + pdpGroup.getVersion());\r
159         }\r
160         String deployedPdpGroups = String.join(",", pdpGroupNameVersionList);\r
161         return "policy with ID " + policyId + ":" + policyVersion\r
162                         + " cannot be deleted as it is deployed in pdp groups " + deployedPdpGroups;\r
163     }\r
164 \r
165     /**\r
166      * Constructs returned message for policy type delete rule violation.\r
167      *\r
168      * @param policyTypeId the ID of policy type\r
169      * @param policyTypeVersion the version of policy type\r
170      * @param policies the list of policies that parameterizes specified policy type\r
171      *\r
172      * @return the constructed message\r
173      */\r
174     protected String constructDeletePolicyTypeViolationMessage(String policyTypeId, String policyTypeVersion,\r
175                     List<ToscaPolicy> policies) {\r
176 \r
177         List<String> policyNameVersionList = new ArrayList<>(policies.size());\r
178         for (ToscaPolicy policy : policies) {\r
179             policyNameVersionList.add(policy.getName() + ":" + policy.getVersion());\r
180         }\r
181         String parameterizedPolicies = String.join(",", policyNameVersionList);\r
182         return "policy type with ID " + policyTypeId + ":" + policyTypeVersion\r
183                         + " cannot be deleted as it is parameterized by policies " + parameterizedPolicies;\r
184     }\r
185 \r
186     /**\r
187      * Collects all deployed versions of specified policy in all pdp groups.\r
188      *\r
189      * @param policyId the ID of policy\r
190      * @param policyType the concept key of policy type\r
191      * @param getter the custom generic getter Bifunction\r
192      * @param consumer the BiConsumer\r
193      * @param data the data structure storing retrieved deployed policies\r
194      *\r
195      * @return a map between pdp group and deployed versions of specified policy in that group\r
196      *\r
197      * @throws PfModelException the PfModel parsing exception\r
198      */\r
199     protected <T, R> Map<Pair<String, String>, T> collectDeployedPolicies(String policyId, PfConceptKey policyType,\r
200             BiFunctionWithEx<String, String, R> getter, BiConsumer<T, R> consumer, T data) throws PfModelException {\r
201 \r
202         List<PdpGroup> pdpGroups = getPolicyTypeFilteredPdpGroups(policyType);\r
203         hasActivePdpGroup(pdpGroups, policyType, policyId);\r
204         return constructDeployedPolicyMap(pdpGroups, policyId, policyType, getter, consumer, data);\r
205     }\r
206 \r
207     @FunctionalInterface\r
208     protected interface BiFunctionWithEx<T,U,R> {\r
209         public R apply(T value1, U value2) throws PfModelException;\r
210     }\r
211 \r
212     /**\r
213      * Checks if the list of pdp groups is empty.\r
214      * If so, throws exception saying specified policy deployment is not found in all existing pdp groups.\r
215      *\r
216      * @param pdpGroups the list of pdp groups to check against\r
217      * @param policyType the concept key of policy type\r
218      * @param policyId the ID of policy\r
219      *\r
220      * @throws PfModelException the PfModel parsing exception\r
221      */\r
222     private void hasActivePdpGroup(List<PdpGroup> pdpGroups, PfConceptKey policyType, String policyId)\r
223             throws PfModelException {\r
224 \r
225         if (pdpGroups.isEmpty()) {\r
226             throw new PfModelException(Response.Status.NOT_FOUND,\r
227                     constructDeploymentNotFoundMessage(policyType, policyId));\r
228         }\r
229     }\r
230 \r
231     /**\r
232      * Retrieves all pdp groups supporting specified policy type.\r
233      *\r
234      * @param policyTypeId the ID of policy type\r
235      * @param policyTypeVersion the version of policy type\r
236      *\r
237      * @return a list of pdp groups supporting specified policy type\r
238      *\r
239      * @throws PfModelException the PfModel parsing exception\r
240      */\r
241     private List<PdpGroup> getPolicyTypeFilteredPdpGroups(PfConceptKey policyType)\r
242             throws PfModelException {\r
243 \r
244         List<ToscaPolicyTypeIdentifier> policyTypes = new ArrayList<>();\r
245         policyTypes.add(new ToscaPolicyTypeIdentifier(policyType.getName(), policyType.getVersion()));\r
246         PdpGroupFilter pdpGroupFilter = PdpGroupFilter.builder().policyTypeList(policyTypes)\r
247                 .groupState(PdpState.ACTIVE).pdpState(PdpState.ACTIVE).build();\r
248         return modelsProvider.getFilteredPdpGroups(pdpGroupFilter);\r
249     }\r
250 \r
251     /**\r
252      * Constructs the map of deployed pdp groups and deployed policies.\r
253      *\r
254      * @param pdpGroups the list of pdp groups that contain the specified policy\r
255      * @param policyId the ID of policy\r
256      * @param policyType the concept key of policy type\r
257      * @param getter the custom generic getter BiFunction\r
258      * @param consumer the BiConsumer\r
259      * @param data the data structure storing retrieved deployed policies\r
260      *\r
261      * @return the constructed map of pdp groups and deployed policies\r
262      *\r
263      * @throws PfModelException the PfModel parsing exception\r
264      */\r
265     private <T, R> Map<Pair<String, String>, T> constructDeployedPolicyMap(List<PdpGroup> pdpGroups, String policyId,\r
266             PfConceptKey policyType, BiFunctionWithEx<String, String, R> getter, BiConsumer<T, R> consumer, T data)\r
267                     throws PfModelException {\r
268 \r
269         Map<Pair<String, String>, T> deployedPolicyMap = new HashMap<>();\r
270         for (PdpGroup pdpGroup : pdpGroups) {\r
271             List<ToscaPolicyIdentifier> policyIdentifiers = extractPolicyIdentifiers(policyId, pdpGroup, policyType);\r
272             T deployedPolicies = getDeployedPolicies(policyIdentifiers, policyType, getter, consumer, data);\r
273             deployedPolicyMap.put(Pair.of(pdpGroup.getName(), pdpGroup.getVersion()), deployedPolicies);\r
274         }\r
275         return deployedPolicyMap;\r
276     }\r
277 \r
278     /**\r
279      * Extracts policy identifiers matching specified policy ID from specified pdp group.\r
280      *\r
281      * @param policyId the ID of policy to match\r
282      * @param pdpGroup the target pdp group to search\r
283      * @param policyType the concept key of policy type\r
284      *\r
285      * @return the list of policy identifiers\r
286      *\r
287      * @throws PfModelException the PfModel parsing exception\r
288      */\r
289     private List<ToscaPolicyIdentifier> extractPolicyIdentifiers(String policyId, PdpGroup pdpGroup,\r
290             PfConceptKey policyType) throws PfModelException {\r
291 \r
292         List<ToscaPolicyIdentifier> policyIdentifiers = new ArrayList<>();\r
293         for (PdpSubGroup pdpSubGroup : pdpGroup.getPdpSubgroups()) {\r
294             for (ToscaPolicyIdentifier policyIdentifier : pdpSubGroup.getPolicies()) {\r
295                 if (policyId.equalsIgnoreCase(policyIdentifier.getName())) {\r
296                     policyIdentifiers.add(policyIdentifier);\r
297                 }\r
298             }\r
299         }\r
300         if (policyIdentifiers.isEmpty()) {\r
301             throw new PfModelException(Response.Status.NOT_FOUND,\r
302                     constructDeploymentNotFoundMessage(policyType, policyId));\r
303         }\r
304         return policyIdentifiers;\r
305     }\r
306 \r
307     /**\r
308      * Retrieves deployed policies in a generic way.\r
309      *\r
310      * @param policyIdentifiers the identifiers of the policies to return\r
311      * @param policyType the concept key of current policy type\r
312      * @param getter the method reference of getting deployed policies\r
313      * @param consumer the method reference of consuming the returned policies\r
314      * @param data the data structure of deployed policies to return\r
315      *\r
316      * @return the generic type of policy data structure to return\r
317      *\r
318      * @throws PfModelException the PfModel parsing exception\r
319      */\r
320     private <T, R> T getDeployedPolicies(List<ToscaPolicyIdentifier> policyIdentifiers, PfConceptKey policyType,\r
321             BiFunctionWithEx<String, String, R> getter, BiConsumer<T, R> consumer, T data) throws PfModelException {\r
322 \r
323         for (ToscaPolicyIdentifier policyIdentifier : policyIdentifiers) {\r
324             R result = getter.apply(policyIdentifier.getName(),\r
325                     getTrimedVersionForLegacyType(policyIdentifier.getVersion(), policyType));\r
326             consumer.accept(data, result);\r
327         }\r
328         return data;\r
329     }\r
330 \r
331     /**\r
332      * Trims the version for legacy policies.\r
333      *\r
334      * @param fullVersion the full version format with major, minor, patch\r
335      * @param policyType the concept key of policy type\r
336      *\r
337      * @return the trimmed version\r
338      */\r
339     private String getTrimedVersionForLegacyType(String fullVersion, PfConceptKey policyType) {\r
340         return (policyType.getName().contains("guard")\r
341                 || policyType.getName().contains("Operational")) ? fullVersion.split("\\.")[0] : fullVersion;\r
342     }\r
343 \r
344     /**\r
345      * Constructs returned message for not found policy deployment.\r
346      *\r
347      * @param policyType the concept key of policy type\r
348      * @param policyId the ID of policy\r
349      *\r
350      * @return constructed message\r
351      */\r
352     private String constructDeploymentNotFoundMessage(PfConceptKey policyType, String policyId) {\r
353 \r
354         return "could not find policy with ID " + policyId + " and type "\r
355                 + policyType.getName() + ":" + policyType.getVersion() + " deployed in any pdp group";\r
356     }\r
357 }\r