Included Policy GUI Enhancements and validations
[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 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
24 import java.io.File;
25 import java.io.PrintWriter;
26 import java.util.ArrayList;
27 import java.util.Collections;
28 import java.util.HashSet;
29 import java.util.Iterator;
30 import java.util.List;
31 import java.util.Set;
32
33 import javax.servlet.http.HttpServletRequest;
34 import javax.servlet.http.HttpServletResponse;
35
36 import org.json.JSONObject;
37 import org.onap.policy.admin.RESTfulPAPEngine;
38 import org.onap.policy.common.logging.flexlogger.FlexLogger;
39 import org.onap.policy.common.logging.flexlogger.Logger;
40 import org.onap.policy.model.PDPGroupContainer;
41 import org.onap.policy.utils.UserUtils.Pair;
42 import org.onap.policy.xacml.api.XACMLErrorConstants;
43 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
44 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
45 import org.onap.policy.xacml.std.pap.StdPDP;
46 import org.onap.policy.xacml.std.pap.StdPDPGroup;
47 import org.onap.portalsdk.core.controller.RestrictedBaseController;
48 import org.onap.portalsdk.core.web.support.JsonMessage;
49 import org.onap.portalsdk.core.web.support.UserUtils;
50 import org.springframework.http.MediaType;
51 import org.springframework.stereotype.Controller;
52 import org.springframework.web.bind.annotation.RequestMapping;
53
54 import com.att.research.xacml.api.pap.PAPException;
55 import com.att.research.xacml.api.pap.PDPPolicy;
56 import com.fasterxml.jackson.databind.DeserializationFeature;
57 import com.fasterxml.jackson.databind.JsonNode;
58 import com.fasterxml.jackson.databind.ObjectMapper;
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         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(value={"/get_PDPGroupData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
163         public void getPDPGroupEntityData(HttpServletRequest request, HttpServletResponse response){
164                 try{
165                         ObjectMapper mapper = new ObjectMapper();
166                         refreshGroups(request);
167                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
168                         JSONObject j = new JSONObject(msg);
169                         response.getWriter().write(j.toString());
170                 }
171                 catch (Exception e){
172                         policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while retrieving the PDP Group data" + e);
173                 }
174         }
175
176         @RequestMapping(value={"/pdp_Group/save_pdp_group"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
177         public void savePDPGroup(HttpServletRequest request, HttpServletResponse response){
178                 try {
179                         ObjectMapper mapper = new ObjectMapper();
180                         PolicyController controller = getPolicyControllerInstance();
181                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
182                         JsonNode root = mapper.readTree(request.getReader());
183                         this.container = new PDPGroupContainer(controller.getPapEngine());
184                         
185                         String userId = UserUtils.getUserSession(request).getOrgUserId();
186                         policyLogger.info("****************************************Logging UserID for Save PDP Group Function*****************************************");
187                         policyLogger.info("UserId:  " + userId + "PDP Group Data:  "+ root.get("pdpGroupData").toString());
188                         policyLogger.info("***************************************************************************************************************************");
189                         
190                         StdPDPGroup pdpGroupData =  mapper.readValue(root.get("pdpGroupData").toString().replace("groupName", "name"), StdPDPGroup.class);
191                         try {
192                                 if(pdpGroupData.getId() == null){
193                                         this.container.addNewGroup(pdpGroupData.getName(), pdpGroupData.getDescription());
194                                 }else{
195                                         this.container.updateGroup(pdpGroupData);
196                                 }
197
198                         } catch (Exception e) {
199                                 String message = "Unable to create Group.  Reason:\n" + e.getMessage();
200                                 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while creating the PDP Group" + message + e);
201                         }
202
203
204                         response.setCharacterEncoding("UTF-8");
205                         response.setContentType("application / json");
206                         request.setCharacterEncoding("UTF-8");
207
208                         PrintWriter out = response.getWriter();
209                         refreshGroups(request);
210                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
211                         JSONObject j = new JSONObject(msg);
212                         out.write(j.toString());
213                 }
214                 catch (Exception e){
215                         policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Saving the PDP Group" + e);
216                         response.setCharacterEncoding("UTF-8");
217                         PrintWriter out = null;
218                         try {
219                                 request.setCharacterEncoding("UTF-8");
220                                 out = response.getWriter();
221                                 out.write(e.getMessage());
222                         } catch (Exception e1) {
223                                 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Saving the PDP Group" + e1);
224                         }
225                 }
226         }
227
228         @RequestMapping(value={"/pdp_Group/remove_pdp_group"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
229         public void removePDPGroup(HttpServletRequest request, HttpServletResponse response){
230                 try{
231                         ObjectMapper mapper = new ObjectMapper();
232                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
233                         JsonNode root = mapper.readTree(request.getReader());
234                         PolicyController controller = getPolicyControllerInstance();
235                         this.container = new PDPGroupContainer(controller.getPapEngine()); 
236                         
237                         String userId = UserUtils.getUserSession(request).getOrgUserId();
238                         policyLogger.info("****************************************Logging UserID for Remove PDP Group Function*****************************************");
239                         policyLogger.info("UserId:  " + userId + "PDP Group Data:  "+ root.get("pdpGroupData").toString());
240                         policyLogger.info("*****************************************************************************************************************************");
241                         
242                         StdPDPGroup pdpGroupData =  mapper.readValue(root.get("pdpGroupData").toString(), StdPDPGroup.class);
243                         if("Default".equals(pdpGroupData.getName())) {
244                                 throw new UnsupportedOperationException("You can't remove the Default Group.");
245                         }else{
246                                 this.container.removeGroup(pdpGroupData, null);
247                         }
248
249                         response.setCharacterEncoding("UTF-8");
250                         response.setContentType("application / json");
251                         request.setCharacterEncoding("UTF-8");
252
253                         PrintWriter out = response.getWriter();
254
255                         refreshGroups(request);
256                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
257                         JSONObject j = new JSONObject(msg);
258                         out.write(j.toString());
259                 }
260                 catch (Exception e){
261                         policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing the PDP Group" + e);
262                         PrintWriter out;
263                         try {
264                                 response.setCharacterEncoding("UTF-8");
265                                 request.setCharacterEncoding("UTF-8");
266                                 out = response.getWriter();
267                                 out.write(e.getMessage());
268                         } catch (Exception e1) {
269                                 policyLogger.error("Exception Occured"+ e1);
270                         }
271                 }
272         }
273
274         @RequestMapping(value={"/pdp_Group/save_pdpTogroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
275         public void savePDPToGroup(HttpServletRequest request, HttpServletResponse response){
276                 try {
277                         ObjectMapper mapper = new ObjectMapper();
278                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
279                         JsonNode root = mapper.readTree(request.getReader());
280                         PolicyController controller = getPolicyControllerInstance();
281                         this.container = new PDPGroupContainer(controller.getPapEngine()); 
282                         String update = root.get("update").toString();
283                         PdpData pdpGroupData = mapper.readValue(root.get("pdpInGroup").toString(), PdpData.class);
284                         StdPDPGroup activeGroupData =  mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);
285                         
286                         String userId = UserUtils.getUserSession(request).getOrgUserId();
287                         policyLogger.info("****************************************Logging UserID while Saving  pdp in  PDP Group*****************************************");
288                         policyLogger.info("UserId:  " + userId + "PDP Group Data:  "+ root.get("pdpInGroup").toString() + "Active Group Data: "+ root.get("activePDP").toString());
289                         policyLogger.info("*******************************************************************************************************************************");
290                         
291                         try {
292
293                                 if(update.contains("false")){
294                                         this.container.addNewPDP(pdpGroupData.getId(), activeGroupData, pdpGroupData.getName(), pdpGroupData.getDescription(), pdpGroupData.getJmxPort());
295                                 }else{
296                                         this.container.updateGroup(activeGroupData);
297                                 }
298                         } catch (Exception e) {
299                                 String message = "Unable to create Group.  Reason:\n" + e.getMessage();
300                                 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + message + e);
301                         }
302
303
304                         response.setCharacterEncoding("UTF-8");
305                         response.setContentType("application / json");
306                         request.setCharacterEncoding("UTF-8");
307
308                         PrintWriter out = response.getWriter();
309                         refreshGroups(request);
310                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
311                         JSONObject j = new JSONObject(msg);
312                         out.write(j.toString());
313                 }
314                 catch (Exception e){
315                         policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + e);
316                         PrintWriter out;
317                         try {
318                                 response.setCharacterEncoding("UTF-8");
319                                 request.setCharacterEncoding("UTF-8");
320                                 out = response.getWriter();
321                                 out.write(e.getMessage());
322                         } catch (Exception e1) {
323                                 policyLogger.error("Exception Occured"+ e1);
324                         }
325                 }
326         }
327
328         @RequestMapping(value={"/pdp_Group/remove_pdpFromGroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
329         public void removePDPFromGroup(HttpServletRequest request, HttpServletResponse response){
330                 try{
331                         ObjectMapper mapper = new ObjectMapper();
332                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
333                         JsonNode root = mapper.readTree(request.getReader());
334                         PolicyController controller = getPolicyControllerInstance();
335                         this.container = new PDPGroupContainer(controller.getPapEngine()); 
336                         StdPDP deletePdp =  mapper.readValue(root.get("data").toString(), StdPDP.class);
337                         StdPDPGroup activeGroupData =  mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);
338
339                         String userId = UserUtils.getUserSession(request).getOrgUserId();
340                         policyLogger.info("****************************************Logging UserID while Removing  pdp from  PDP Group*****************************************");
341                         policyLogger.info("UserId:  " + userId + "Delete PDP Group Data:  "+ root.get("data").toString() + "Active Group Data: "+ root.get("activePDP").toString());
342                         policyLogger.info("***********************************************************************************************************************************");
343                         
344                         this.container.removePDP(deletePdp, activeGroupData);
345                         response.setCharacterEncoding("UTF-8");
346                         response.setContentType("application / json");
347                         request.setCharacterEncoding("UTF-8");
348
349                         PrintWriter out = response.getWriter();
350                         refreshGroups(request);
351                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
352                         JSONObject j = new JSONObject(msg);
353                         out.write(j.toString());
354                 }
355                 catch (Exception e){
356                         policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing Pdp from PDP Group" + e);
357                         PrintWriter out;
358                         try {
359                                 response.setCharacterEncoding("UTF-8");
360                                 request.setCharacterEncoding("UTF-8");
361                                 out = response.getWriter();
362                                 out.write(e.getMessage());
363                         } catch (Exception e1) {
364                                 policyLogger.error("Exception Occured"+ e1);
365                         }
366                 }
367         }
368
369         private PolicyController getPolicyControllerInstance(){
370                 return policyController != null ? getPolicyController() : new PolicyController();
371         }
372
373         public boolean isJunit() {
374                 return junit;
375         }
376
377         public void setJunit(boolean junit) {
378                 this.junit = junit;
379         }
380
381         public Set<OnapPDPGroup> getGroupsData() {
382                 return groupsData;
383         }
384
385         public void setGroupsData(Set<OnapPDPGroup> groupsData) {
386                 this.groupsData = groupsData;
387         }
388 }
389
390 class PdpData{
391         String id;
392         int jmxPort;
393         String name;
394         String description;
395         public String getId() {
396                 return id;
397         }
398         public void setId(String id) {
399                 this.id = id;
400         }
401         public int getJmxPort() {
402                 return jmxPort;
403         }
404         public void setJmxPort(int jmxPort) {
405                 this.jmxPort = jmxPort;
406         }
407         public String getName() {
408                 return name;
409         }
410         public void setName(String name) {
411                 this.name = name;
412         }
413         public String getDescription() {
414                 return description;
415         }
416         public void setDescription(String description) {
417                 this.description = description;
418         }
419         
420 }