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