Sonar cleanup in controllers etc
[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.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             ObjectMapper mapper = new ObjectMapper();
199             PolicyController controller = getPolicyControllerInstance();
200             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
201             JsonNode root = mapper.readTree(request.getReader());
202             this.container = new PDPGroupContainer(controller.getPapEngine());
203
204             String userId = UserUtils.getUserSession(request).getOrgUserId();
205             policyLogger.info(
206                     "*******************Logging UserID for Save PDP Group Function*******************************");
207             policyLogger.info("UserId:  " + userId + "PDP Group Data:  " + root.get("pdpGroupData").toString());
208             policyLogger.info(
209                     "********************************************************************************************");
210
211             StdPDPGroup pdpGroupData = mapper
212                     .readValue(root.get("pdpGroupData").toString().replace("groupName", "name"), StdPDPGroup.class);
213             try {
214                 if (pdpGroupData.getId() == null) {
215                     this.container.addNewGroup(pdpGroupData.getName(), pdpGroupData.getDescription());
216                 } else {
217                     this.container.updateGroup(pdpGroupData);
218                 }
219
220             } catch (Exception e) {
221                 String message = "Unable to create Group.  Reason:\n" + e.getMessage();
222                 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while creating the PDP Group"
223                         + message + e);
224             }
225
226             response.setCharacterEncoding("UTF-8");
227             response.setContentType("application / json");
228             request.setCharacterEncoding("UTF-8");
229
230             refreshGroups(request);
231             response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
232         } catch (Exception e) {
233             policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Saving the PDP Group" + e);
234             response.setCharacterEncoding("UTF-8");
235             PrintWriter out = null;
236             try {
237                 request.setCharacterEncoding("UTF-8");
238                 out = response.getWriter();
239                 out.write(e.getMessage());
240             } catch (Exception e1) {
241                 policyLogger
242                         .error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Saving the PDP Group" + e1);
243             }
244         }
245     }
246
247     /**
248      * removePDPGroup.
249      *
250      * @param request HttpServletRequest
251      * @param response HttpServletResponse
252      */
253     @RequestMapping(
254             value = {"/pdp_Group/remove_pdp_group"},
255             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
256     public void removePDPGroup(HttpServletRequest request, HttpServletResponse response) {
257         try {
258             ObjectMapper mapper = new ObjectMapper();
259             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
260             JsonNode root = mapper.readTree(request.getReader());
261             PolicyController controller = getPolicyControllerInstance();
262             this.container = new PDPGroupContainer(controller.getPapEngine());
263
264             String userId = UserUtils.getUserSession(request).getOrgUserId();
265             policyLogger.info(
266                     "*********************Logging UserID for Remove PDP Group Function*******************************");
267             policyLogger.info("UserId:  " + userId + "PDP Group Data:  " + root.get("pdpGroupData").toString());
268             policyLogger.info(
269                     "************************************************************************************************");
270
271             StdPDPGroup pdpGroupData = mapper.readValue(root.get("pdpGroupData").toString(), StdPDPGroup.class);
272             if ("Default".equals(pdpGroupData.getName())) {
273                 throw new UnsupportedOperationException("You can't remove the Default Group.");
274             } else {
275                 this.container.removeGroup(pdpGroupData, null);
276             }
277
278             response.setCharacterEncoding("UTF-8");
279             response.setContentType("application / json");
280             request.setCharacterEncoding("UTF-8");
281             refreshGroups(request);
282             response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
283         } catch (Exception e) {
284             policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Removing the PDP Group" + e);
285             PrintWriter out;
286             try {
287                 response.setCharacterEncoding("UTF-8");
288                 request.setCharacterEncoding("UTF-8");
289                 out = response.getWriter();
290                 out.write(e.getMessage());
291             } catch (Exception e1) {
292                 policyLogger.error("Exception Occured" + e1);
293             }
294         }
295     }
296
297     /**
298      * savePDPToGroup.
299      *
300      * @param request HttpServletRequest
301      * @param response HttpServletResponse
302      */
303     @RequestMapping(
304             value = {"/pdp_Group/save_pdpTogroup"},
305             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
306     public void savePDPToGroup(HttpServletRequest request, HttpServletResponse response) {
307         try {
308             ObjectMapper mapper = new ObjectMapper();
309             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
310             JsonNode root = mapper.readTree(request.getReader());
311             PolicyController controller = getPolicyControllerInstance();
312             this.container = new PDPGroupContainer(controller.getPapEngine());
313             String update = root.get("update").toString();
314             PdpData pdpGroupData = mapper.readValue(root.get("pdpInGroup").toString(), PdpData.class);
315             StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);
316
317             String userId = UserUtils.getUserSession(request).getOrgUserId();
318             policyLogger.info(
319                     "*************Logging UserID while Saving  pdp in  PDP Group***********************************");
320             policyLogger.info("UserId:  " + userId + "PDP Group Data:  " + root.get("pdpInGroup").toString()
321                     + "Active Group Data: " + root.get("activePDP").toString());
322             policyLogger.info(
323                     "**********************************************************************************************");
324
325             try {
326
327                 if (update.contains("false")) {
328                     this.container.addNewPDP(pdpGroupData.getId(), activeGroupData, pdpGroupData.getName(),
329                             pdpGroupData.getDescription(), pdpGroupData.getJmxPort());
330                 } else {
331                     this.container.updateGroup(activeGroupData);
332                 }
333             } catch (Exception e) {
334                 String message = "Unable to create Group.  Reason:\n" + e.getMessage();
335                 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE
336                         + "Error Occured while Creating Pdp in PDP Group" + message + e);
337             }
338
339             response.setCharacterEncoding("UTF-8");
340             response.setContentType("application / json");
341             request.setCharacterEncoding("UTF-8");
342             refreshGroups(request);
343             response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
344         } catch (Exception e) {
345             policyLogger
346                     .error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Creating Pdp in PDP Group" + e);
347             PrintWriter out;
348             try {
349                 response.setCharacterEncoding("UTF-8");
350                 request.setCharacterEncoding("UTF-8");
351                 out = response.getWriter();
352                 out.write(e.getMessage());
353             } catch (Exception e1) {
354                 policyLogger.error("Exception Occured" + e1);
355             }
356         }
357     }
358
359     /**
360      * removePDPFromGroup.
361      *
362      * @param request HttpServletRequest
363      * @param response HttpServletResponse
364      */
365     @RequestMapping(
366             value = {"/pdp_Group/remove_pdpFromGroup"},
367             method = {org.springframework.web.bind.annotation.RequestMethod.POST})
368     public void removePDPFromGroup(HttpServletRequest request, HttpServletResponse response) {
369         try {
370             ObjectMapper mapper = new ObjectMapper();
371             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
372             JsonNode root = mapper.readTree(request.getReader());
373             PolicyController controller = getPolicyControllerInstance();
374             this.container = new PDPGroupContainer(controller.getPapEngine());
375
376             String userId = UserUtils.getUserSession(request).getOrgUserId();
377             policyLogger.info(
378                     "********************Logging UserID while Removing  pdp from  PDP Group**************************");
379             policyLogger.info("UserId:  " + userId + "Delete PDP Group Data:  " + root.get("data").toString()
380                     + "Active Group Data: " + root.get("activePDP").toString());
381             policyLogger.info(
382                     "************************************************************************************************");
383
384             StdPDP deletePdp = mapper.readValue(root.get("data").toString(), StdPDP.class);
385             StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);
386             this.container.removePDP(deletePdp, activeGroupData);
387             response.setCharacterEncoding("UTF-8");
388             response.setContentType("application / json");
389             request.setCharacterEncoding("UTF-8");
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.setCharacterEncoding("UTF-8");
398                 request.setCharacterEncoding("UTF-8");
399                 response.getWriter().write(e.getMessage());
400             } catch (Exception e1) {
401                 policyLogger.error("Exception Occured" + e1);
402             }
403         }
404     }
405
406     private PolicyController getPolicyControllerInstance() {
407         return policyController != null ? getPolicyController() : new PolicyController();
408     }
409
410     public boolean isJunit() {
411         return junit;
412     }
413
414     public void setJunit(boolean junit) {
415         this.junit = junit;
416     }
417
418     public Set<OnapPDPGroup> getGroupsData() {
419         return groupsData;
420     }
421
422     public void setGroupsData(Set<OnapPDPGroup> groupsData) {
423         this.groupsData = groupsData;
424     }
425 }
426
427 @Getter
428 @Setter
429 class PdpData {
430     String id;
431     int jmxPort;
432     String name;
433     String description;
434 }