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