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