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