Consolidate PolicyRestAdapter setup
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / controller / PDPController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.controller;
22
23 import com.att.research.xacml.api.pap.PAPException;
24 import com.att.research.xacml.api.pap.PDPPolicy;
25 import com.fasterxml.jackson.databind.DeserializationFeature;
26 import com.fasterxml.jackson.databind.JsonNode;
27 import com.fasterxml.jackson.databind.ObjectMapper;
28
29 import java.io.File;
30 import java.util.ArrayList;
31 import java.util.Collections;
32 import java.util.HashSet;
33 import java.util.Iterator;
34 import java.util.List;
35 import java.util.Set;
36
37 import javax.servlet.http.HttpServletRequest;
38 import javax.servlet.http.HttpServletResponse;
39 import lombok.Getter;
40 import lombok.Setter;
41 import org.json.JSONObject;
42 import org.onap.policy.admin.RESTfulPAPEngine;
43 import org.onap.policy.common.logging.flexlogger.FlexLogger;
44 import org.onap.policy.common.logging.flexlogger.Logger;
45 import org.onap.policy.model.PDPGroupContainer;
46 import org.onap.policy.utils.PolicyUtils;
47 import org.onap.policy.utils.UserUtils.Pair;
48 import org.onap.policy.xacml.api.XACMLErrorConstants;
49 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
50 import org.onap.policy.xacml.std.pap.StdPDP;
51 import org.onap.policy.xacml.std.pap.StdPDPGroup;
52 import org.onap.portalsdk.core.controller.RestrictedBaseController;
53 import org.onap.portalsdk.core.web.support.JsonMessage;
54 import org.onap.portalsdk.core.web.support.UserUtils;
55 import org.springframework.http.MediaType;
56 import org.springframework.stereotype.Controller;
57 import org.springframework.web.bind.annotation.RequestMapping;
58
59 @Controller
60 @RequestMapping({"/"})
61 public class PDPController extends RestrictedBaseController {
62     private static final Logger policyLogger = FlexLogger.getLogger(PDPController.class);
63
64     protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<OnapPDPGroup>());
65     private PDPGroupContainer container;
66
67     private static String SUPERADMIN = "super-admin";
68     private static String SUPEREDITOR = "super-editor";
69     private static String SUPERGUEST = "super-guest";
70
71     private Set<OnapPDPGroup> groupsData;
72
73     private boolean junit = false;
74
75     private PolicyController policyController;
76
77     public PolicyController getPolicyController() {
78         return policyController;
79     }
80
81     public void setPolicyController(PolicyController policyController) {
82         this.policyController = policyController;
83     }
84
85     /**
86      * refreshGroups.
87      *
88      * @param request HttpServletRequest
89      */
90     public synchronized void refreshGroups(HttpServletRequest request) {
91         synchronized (this.groups) {
92             this.groups.clear();
93             try {
94                 PolicyController controller = getPolicyControllerInstance();
95                 Set<PDPPolicy> filteredPolicies = new HashSet<>();
96                 Set<String> scopes;
97                 List<String> roles;
98                 String userId = isJunit() ? "Test" : UserUtils.getUserSession(request).getOrgUserId();
99                 List<Object> userRoles = controller.getRoles(userId);
100                 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
101                 roles = pair.second;
102                 scopes = pair.first;
103
104                 if (!junit && controller.getPapEngine() == null) {
105                     setPapEngine(request);
106                 }
107                 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) {
108                     if (!junit) {
109                         this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
110                     } else {
111                         this.groups.addAll(this.getGroupsData());
112                     }
113                 } else {
114                     if (!userRoles.isEmpty() && !scopes.isEmpty()) {
115                         this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
116                         List<OnapPDPGroup> tempGroups = new ArrayList<>();
117                         if (!groups.isEmpty()) {
118                             Iterator<OnapPDPGroup> pdpGroup = groups.iterator();
119                             while (pdpGroup.hasNext()) {
120                                 OnapPDPGroup group = pdpGroup.next();
121                                 Set<PDPPolicy> policies = group.getPolicies();
122                                 for (PDPPolicy policy : policies) {
123                                     for (String scope : scopes) {
124                                         scope = scope.replace(File.separator, ".");
125                                         String policyName = policy.getId();
126                                         if (policyName.contains(".Config_")) {
127                                             policyName = policyName.substring(0, policyName.lastIndexOf(".Config_"));
128                                         } else if (policyName.contains(".Action_")) {
129                                             policyName = policyName.substring(0, policyName.lastIndexOf(".Action_"));
130                                         } else if (policyName.contains(".Decision_")) {
131                                             policyName = policyName.substring(0, policyName.lastIndexOf(".Decision_"));
132                                         }
133                                         if (policyName.startsWith(scope)) {
134                                             filteredPolicies.add(policy);
135                                         }
136                                     }
137                                 }
138                                 pdpGroup.remove();
139                                 StdPDPGroup newGroup = (StdPDPGroup) group;
140                                 newGroup.setPolicies(filteredPolicies);
141                                 tempGroups.add(newGroup);
142                             }
143                             groups.clear();
144                             groups = tempGroups;
145                         }
146                     }
147                 }
148             } catch (PAPException e) {
149                 String message = "Unable to retrieve Groups from server: " + e;
150                 policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Pap Engine is Null" + message);
151             }
152         }
153     }
154
155     private void setPapEngine(HttpServletRequest request) {
156         try {
157             //
158             // Set the URL for the RESTful PAP Engine
159             //
160             PolicyController.setPapEngine(new RESTfulPAPEngine(request.getRequestURL().toString()));
161         } catch (Exception e) {
162             policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception Occured while loading PAP", e);
163         }
164     }
165
166     /**
167      * getPDPGroupEntityData.
168      *
169      * @param request HttpServletRequest
170      * @param response HttpServletResponse
171      */
172     @RequestMapping(
173             value = {"/get_PDPGroupData"},
174             method = {org.springframework.web.bind.annotation.RequestMethod.GET},
175             produces = MediaType.APPLICATION_JSON_VALUE)
176     public void getPDPGroupEntityData(HttpServletRequest request, HttpServletResponse response) {
177         try {
178             refreshGroups(request);
179             response.getWriter().write(new JSONObject(new JsonMessage(
180                     new ObjectMapper().writeValueAsString(groups))).toString());
181         } catch (Exception e) {
182             policyLogger.error(
183                     XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while retrieving the PDP Group data" + e);
184         }
185     }
186
187     /**
188      * savePDPGroup.
189      *
190      * @param request HttpServletRequest
191      * @param response HttpServletResponse
192      */
193     @RequestMapping(
194             value = {"/pdp_Group/save_pdp_group"},
195             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
196     public void savePDPGroup(HttpServletRequest request, HttpServletResponse response) {
197         try {
198             response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
199             request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
200             //
201             //
202             //
203             ObjectMapper mapper = new ObjectMapper();
204             PolicyController controller = getPolicyControllerInstance();
205             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
206             JsonNode root = mapper.readTree(request.getReader());
207             this.container = new PDPGroupContainer(controller.getPapEngine());
208
209             String userId = UserUtils.getUserSession(request).getOrgUserId();
210             policyLogger.info(
211                     "*******************Logging UserID for Save PDP Group Function*******************************");
212             policyLogger.info("UserId:  " + userId + "PDP Group Data:  " + root.get("pdpGroupData").toString());
213             policyLogger.info(
214                     "********************************************************************************************");
215
216             StdPDPGroup pdpGroupData = mapper
217                     .readValue(root.get("pdpGroupData").toString().replace("groupName", "name"), StdPDPGroup.class);
218             try {
219                 if (pdpGroupData.getId() == null) {
220                     this.container.addNewGroup(pdpGroupData.getName(), pdpGroupData.getDescription());
221                 } else {
222                     this.container.updateGroup(pdpGroupData);
223                 }
224
225             } catch (Exception e) {
226                 String message = "Unable to create Group.  Reason:\n" + e.getMessage();
227                 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while creating the PDP Group"
228                         + message + e);
229             }
230
231             response.setContentType(PolicyUtils.APPLICATION_JSON);
232
233             refreshGroups(request);
234             response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
235         } catch (Exception e) {
236             policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Saving the PDP Group" + e);
237             try {
238                 response.getWriter().write(e.getMessage());
239             } catch (Exception e1) {
240                 policyLogger
241                         .error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Saving the PDP Group" + e1);
242             }
243         }
244     }
245
246     /**
247      * removePDPGroup.
248      *
249      * @param request HttpServletRequest
250      * @param response HttpServletResponse
251      */
252     @RequestMapping(
253             value = {"/pdp_Group/remove_pdp_group"},
254             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
255     public void removePDPGroup(HttpServletRequest request, HttpServletResponse response) {
256         try {
257             response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
258             request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
259             //
260             //
261             //
262             ObjectMapper mapper = new ObjectMapper();
263             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
264             JsonNode root = mapper.readTree(request.getReader());
265             PolicyController controller = getPolicyControllerInstance();
266             this.container = new PDPGroupContainer(controller.getPapEngine());
267
268             String userId = UserUtils.getUserSession(request).getOrgUserId();
269             policyLogger.info(
270                     "*********************Logging UserID for Remove PDP Group Function*******************************");
271             policyLogger.info("UserId:  " + userId + "PDP Group Data:  " + root.get("pdpGroupData").toString());
272             policyLogger.info(
273                     "************************************************************************************************");
274
275             StdPDPGroup pdpGroupData = mapper.readValue(root.get("pdpGroupData").toString(), StdPDPGroup.class);
276             if ("Default".equals(pdpGroupData.getName())) {
277                 throw new UnsupportedOperationException("You can't remove the Default Group.");
278             } else {
279                 this.container.removeGroup(pdpGroupData, null);
280             }
281
282             response.setContentType(PolicyUtils.APPLICATION_JSON);
283             refreshGroups(request);
284             response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
285         } catch (Exception e) {
286             policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Removing the PDP Group" + e);
287             try {
288                 response.getWriter().write(e.getMessage());
289             } catch (Exception e1) {
290                 policyLogger.error("Exception Occured" + e1);
291             }
292         }
293     }
294
295     /**
296      * savePDPToGroup.
297      *
298      * @param request HttpServletRequest
299      * @param response HttpServletResponse
300      */
301     @RequestMapping(
302             value = {"/pdp_Group/save_pdpTogroup"},
303             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
304     public void savePDPToGroup(HttpServletRequest request, HttpServletResponse response) {
305         try {
306             response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
307             request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
308             //
309             //
310             //
311             ObjectMapper mapper = new ObjectMapper();
312             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
313             JsonNode root = mapper.readTree(request.getReader());
314             PolicyController controller = getPolicyControllerInstance();
315             this.container = new PDPGroupContainer(controller.getPapEngine());
316             String update = root.get("update").toString();
317             PdpData pdpGroupData = mapper.readValue(root.get("pdpInGroup").toString(), PdpData.class);
318             StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);
319
320             String userId = UserUtils.getUserSession(request).getOrgUserId();
321             policyLogger.info(
322                     "*************Logging UserID while Saving  pdp in  PDP Group***********************************");
323             policyLogger.info("UserId:  " + userId + "PDP Group Data:  " + root.get("pdpInGroup").toString()
324                     + "Active Group Data: " + root.get("activePDP").toString());
325             policyLogger.info(
326                     "**********************************************************************************************");
327
328             try {
329
330                 if (update.contains("false")) {
331                     this.container.addNewPDP(pdpGroupData.getId(), activeGroupData, pdpGroupData.getName(),
332                             pdpGroupData.getDescription(), pdpGroupData.getJmxPort());
333                 } else {
334                     this.container.updateGroup(activeGroupData);
335                 }
336             } catch (Exception e) {
337                 String message = "Unable to create Group.  Reason:\n" + e.getMessage();
338                 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE
339                         + "Error Occured while Creating Pdp in PDP Group" + message + e);
340             }
341
342             response.setContentType(PolicyUtils.APPLICATION_JSON);
343             refreshGroups(request);
344             response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
345         } catch (Exception e) {
346             policyLogger
347                     .error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Creating Pdp in PDP Group" + e);
348             try {
349                 response.getWriter().write(e.getMessage());
350             } catch (Exception e1) {
351                 policyLogger.error("Exception Occured" + e1);
352             }
353         }
354     }
355
356     /**
357      * removePDPFromGroup.
358      *
359      * @param request HttpServletRequest
360      * @param response HttpServletResponse
361      */
362     @RequestMapping(
363             value = {"/pdp_Group/remove_pdpFromGroup"},
364             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
365     public void removePDPFromGroup(HttpServletRequest request, HttpServletResponse response) {
366         try {
367             response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
368             request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
369             //
370             //
371             //
372             ObjectMapper mapper = new ObjectMapper();
373             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
374             JsonNode root = mapper.readTree(request.getReader());
375             PolicyController controller = getPolicyControllerInstance();
376             this.container = new PDPGroupContainer(controller.getPapEngine());
377
378             String userId = UserUtils.getUserSession(request).getOrgUserId();
379             policyLogger.info(
380                     "********************Logging UserID while Removing  pdp from  PDP Group**************************");
381             policyLogger.info("UserId:  " + userId + "Delete PDP Group Data:  " + root.get("data").toString()
382                     + "Active Group Data: " + root.get("activePDP").toString());
383             policyLogger.info(
384                     "************************************************************************************************");
385
386             StdPDP deletePdp = mapper.readValue(root.get("data").toString(), StdPDP.class);
387             StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);
388             this.container.removePDP(deletePdp, activeGroupData);
389             response.setContentType(PolicyUtils.APPLICATION_JSON);
390
391             refreshGroups(request);
392             response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
393         } catch (Exception e) {
394             policyLogger.error(
395                     XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Removing Pdp from PDP Group" + e);
396             try {
397                 response.getWriter().write(e.getMessage());
398             } catch (Exception e1) {
399                 policyLogger.error("Exception Occured" + e1);
400             }
401         }
402     }
403
404     private PolicyController getPolicyControllerInstance() {
405         return policyController != null ? getPolicyController() : new PolicyController();
406     }
407
408     public boolean isJunit() {
409         return junit;
410     }
411
412     public void setJunit(boolean junit) {
413         this.junit = junit;
414     }
415
416     public Set<OnapPDPGroup> getGroupsData() {
417         return groupsData;
418     }
419
420     public void setGroupsData(Set<OnapPDPGroup> groupsData) {
421         this.groupsData = groupsData;
422     }
423 }
424
425 @Getter
426 @Setter
427 class PdpData {
428     String id;
429     int jmxPort;
430     String name;
431     String description;
432 }