Policy TestSuite Enabled
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / openecomp / policy / controller / PDPController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP 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.openecomp.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.List;
30 import java.util.Set;
31
32 import javax.servlet.http.HttpServletRequest;
33 import javax.servlet.http.HttpServletResponse;
34
35 import org.json.JSONObject;
36 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
37 import org.openecomp.policy.common.logging.flexlogger.Logger;
38 import org.openecomp.policy.model.PDPGroupContainer;
39 import org.openecomp.policy.model.Roles;
40 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
41 import org.openecomp.policy.xacml.api.pap.EcompPDPGroup;
42 import org.openecomp.policy.xacml.std.pap.StdPDP;
43 import org.openecomp.policy.xacml.std.pap.StdPDPGroup;
44 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
45 import org.openecomp.portalsdk.core.web.support.JsonMessage;
46 import org.openecomp.portalsdk.core.web.support.UserUtils;
47 import org.springframework.http.MediaType;
48 import org.springframework.stereotype.Controller;
49 import org.springframework.web.bind.annotation.RequestMapping;
50 import org.springframework.web.servlet.ModelAndView;
51
52 import com.att.research.xacml.api.pap.PAPException;
53 import com.att.research.xacml.api.pap.PDPPolicy;
54 import com.fasterxml.jackson.databind.DeserializationFeature;
55 import com.fasterxml.jackson.databind.JsonNode;
56 import com.fasterxml.jackson.databind.ObjectMapper;
57
58 @Controller
59 @RequestMapping({"/"})
60 public class PDPController extends RestrictedBaseController {
61         private static final  Logger logger = FlexLogger.getLogger(PDPController.class);
62         
63         protected List<EcompPDPGroup> groups = Collections.synchronizedList(new ArrayList<EcompPDPGroup>());
64         private PDPGroupContainer container;
65         
66         private static String SUPERADMIN = "super-admin";
67         private static String SUPEREDITOR = "super-editor";
68         private static String SUPERGUEST = "super-guest";
69         
70         public synchronized void refreshGroups(HttpServletRequest request) {
71                 synchronized(this.groups) { 
72                         this.groups.clear();
73                         try {
74                                 Set<PDPPolicy> filteredPolicies = new HashSet<PDPPolicy>();
75                                 Set<String> scopes = null;
76                                 List<String> roles = null;
77                                 String userId = UserUtils.getUserSession(request).getOrgUserId();
78                                 List<Object> userRoles = PolicyController.getRoles(userId);
79                                 roles = new ArrayList<String>();
80                                 scopes = new HashSet<String>();
81                                 for(Object role: userRoles){
82                                         Roles userRole = (Roles) role;
83                                         roles.add(userRole.getRole());
84                                         if(userRole.getScope() != null){
85                                                 if(userRole.getScope().contains(",")){
86                                                         String[] multipleScopes = userRole.getScope().split(",");
87                                                         for(int i =0; i < multipleScopes.length; i++){
88                                                                 scopes.add(multipleScopes[i]);
89                                                         }
90                                                 }else{
91                                                         scopes.add(userRole.getScope());
92                                                 }
93                                         }       
94                                 }
95                                 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ) {
96                                         this.groups.addAll(PolicyController.getPapEngine().getEcompPDPGroups());
97                                 }else{
98                                         if(!userRoles.isEmpty()){
99                                                 if(!scopes.isEmpty()){
100                                                         this.groups.addAll(PolicyController.getPapEngine().getEcompPDPGroups());
101                                                         if(!groups.isEmpty()){
102                                                                 for(EcompPDPGroup group : groups){
103                                                                         Set<PDPPolicy> policies = group.getPolicies();
104                                                                         for(PDPPolicy policy : policies){
105                                                                                 for(String scope : scopes){
106                                                                                         scope = scope.replace(File.separator, ".");
107                                                                                         String policyName = policy.getId();
108                                                                                         if(policyName.contains(".Config_")){
109                                                                                                 policyName = policyName.substring(0, policyName.lastIndexOf(".Config_"));
110                                                                                         }else if(policyName.contains(".Action_")){
111                                                                                                 policyName = policyName.substring(0, policyName.lastIndexOf(".Action_"));
112                                                                                         }else if(policyName.contains(".Decision_")){
113                                                                                                 policyName = policyName.substring(0, policyName.lastIndexOf(".Decision_"));
114                                                                                         }
115                                                                                         if(policyName.startsWith(scope)){
116                                                                                                 filteredPolicies.add(policy);
117                                                                                         }
118                                                                                 }
119                                                                         }
120                                                                         groups.remove(group);
121                                                                         StdPDPGroup newGroup = (StdPDPGroup) group;
122                                                                         newGroup.setPolicies(filteredPolicies);
123                                                                         groups.add(newGroup);
124                                                                 }       
125                                                         }
126                                                 }
127                                         }
128                                 }
129                         } catch (PAPException e) {
130                                 String message = "Unable to retrieve Groups from server: " + e;
131                                 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Pap Engine is Null" + message);
132                         }
133                 }
134         }
135         
136         @RequestMapping(value={"/get_PDPGroupContainerData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
137         public void getPDPGroupContainerData(HttpServletRequest request, HttpServletResponse response){
138                 try{
139                         ObjectMapper mapper = new ObjectMapper();
140                         refreshGroups(request);
141                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
142                         JSONObject j = new JSONObject(msg);
143                         response.getWriter().write(j.toString());
144                 }
145                 catch (Exception e){
146                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while retrieving the PDP Group Container data" + e);
147                 }
148         }
149         
150         @RequestMapping(value={"/get_PDPGroupData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
151         public void getPDPGroupEntityData(HttpServletRequest request, HttpServletResponse response){
152                 try{
153                         ObjectMapper mapper = new ObjectMapper();
154                         refreshGroups(request);
155                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
156                         JSONObject j = new JSONObject(msg);
157                         response.getWriter().write(j.toString());
158                 }
159                 catch (Exception e){
160                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while retrieving the PDP Group data" + e);
161                 }
162         }
163         
164         @RequestMapping(value={"/pdp_Group/save_pdp_group"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
165           public ModelAndView savePDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception{
166             try {
167               ObjectMapper mapper = new ObjectMapper();
168               mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
169               JsonNode root = mapper.readTree(request.getReader());
170               this.container = new PDPGroupContainer(PolicyController.getPapEngine());
171               StdPDPGroup pdpGroupData =  mapper.readValue(root.get("pdpGroupData").toString().replace("groupName", "name"), StdPDPGroup.class);
172               try {
173                   if(pdpGroupData.getId() == null){
174                           this.container.addNewGroup(pdpGroupData.getName(), pdpGroupData.getDescription());
175                   }else{
176                           this.container.updateGroup(pdpGroupData);
177                   }
178                                 
179                         } catch (Exception e) {
180                                 String message = "Unable to create Group.  Reason:\n" + e.getMessage();
181                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while creating the PDP Group" + message);
182                         }
183                 
184             
185               response.setCharacterEncoding("UTF-8");
186               response.setContentType("application / json");
187               request.setCharacterEncoding("UTF-8");
188               
189               PrintWriter out = response.getWriter();
190               refreshGroups(request);
191               JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
192                   JSONObject j = new JSONObject(msg);
193               out.write(j.toString());
194               
195               return null;
196             }
197             catch (Exception e){
198              logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Saving the PDP Group" + e);
199               response.setCharacterEncoding("UTF-8");
200               request.setCharacterEncoding("UTF-8");
201               PrintWriter out = response.getWriter();
202               out.write(e.getMessage());
203             }
204             return null;
205           }
206           
207           @RequestMapping(value={"/pdp_Group/remove_pdp_group"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
208           public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
209             try{
210               ObjectMapper mapper = new ObjectMapper();
211               mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
212               JsonNode root = mapper.readTree(request.getReader());
213               this.container = new PDPGroupContainer(PolicyController.getPapEngine()); 
214               StdPDPGroup pdpGroupData =  mapper.readValue(root.get("pdpGroupData").toString(), StdPDPGroup.class);
215                 if(pdpGroupData.getName().equals("Default")) {
216                                 throw new UnsupportedOperationException("You can't remove the Default Group.");
217                         }else{
218                                 this.container.removeGroup(pdpGroupData, null);
219                         }
220           
221               response.setCharacterEncoding("UTF-8");
222               response.setContentType("application / json");
223               request.setCharacterEncoding("UTF-8");
224               
225               PrintWriter out = response.getWriter();
226               
227               refreshGroups(request);
228               JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
229                   JSONObject j = new JSONObject(msg);
230               out.write(j.toString());
231               
232               return null;
233             }
234             catch (Exception e){
235               logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing the PDP Group" + e);
236               response.setCharacterEncoding("UTF-8");
237               request.setCharacterEncoding("UTF-8");
238               PrintWriter out = response.getWriter();
239               out.write(e.getMessage());
240             }
241             return null;
242           }
243           
244           @RequestMapping(value={"/pdp_Group/save_pdpTogroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
245           public ModelAndView savePDPToGroup(HttpServletRequest request, HttpServletResponse response) throws Exception{
246             try {
247               ObjectMapper mapper = new ObjectMapper();
248               mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
249               JsonNode root = mapper.readTree(request.getReader());
250               this.container = new PDPGroupContainer(PolicyController.getPapEngine()); 
251               String update = root.get("update").toString();
252               PdpData pdpGroupData = (PdpData)mapper.readValue(root.get("pdpInGroup").toString(), PdpData.class);
253               StdPDPGroup activeGroupData =  mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);
254               try {
255                   
256                   if(update.contains("false")){
257                           this.container.addNewPDP(pdpGroupData.getId(), activeGroupData, pdpGroupData.getName(), pdpGroupData.getDescription(), pdpGroupData.getJmxPort());
258                   }else{
259                           this.container.updateGroup(activeGroupData);
260                   }
261                         } catch (Exception e) {
262                                 String message = "Unable to create Group.  Reason:\n" + e.getMessage();
263                                  logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + message);
264                         }
265                 
266             
267               response.setCharacterEncoding("UTF-8");
268               response.setContentType("application / json");
269               request.setCharacterEncoding("UTF-8");
270               
271               PrintWriter out = response.getWriter();
272               refreshGroups(request);
273               JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
274                   JSONObject j = new JSONObject(msg);
275               out.write(j.toString());
276               
277               return null;
278             }
279             catch (Exception e){
280               logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + e);
281               response.setCharacterEncoding("UTF-8");
282               request.setCharacterEncoding("UTF-8");
283               PrintWriter out = response.getWriter();
284               out.write(e.getMessage());
285             }
286             return null;
287           }
288           
289           @RequestMapping(value={"/pdp_Group/remove_pdpFromGroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
290           public ModelAndView removePDPFromGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
291             try{
292               ObjectMapper mapper = new ObjectMapper();
293               mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
294               JsonNode root = mapper.readTree(request.getReader());
295               this.container = new PDPGroupContainer(PolicyController.getPapEngine()); 
296               StdPDP deletePdp =  mapper.readValue(root.get("data").toString(), StdPDP.class);
297               StdPDPGroup activeGroupData =  mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);
298                 
299               this.container.removePDP(deletePdp, activeGroupData);
300               response.setCharacterEncoding("UTF-8");
301               response.setContentType("application / json");
302               request.setCharacterEncoding("UTF-8");
303               
304               PrintWriter out = response.getWriter();
305               refreshGroups(request);
306               String responseString = mapper.writeValueAsString(groups);
307               JSONObject j = new JSONObject("{pdpEntityDatas: " + responseString + "}");
308               out.write(j.toString());
309               
310               return null;
311             }
312             catch (Exception e){
313               logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing Pdp from PDP Group" + e);
314               response.setCharacterEncoding("UTF-8");
315               request.setCharacterEncoding("UTF-8");
316               PrintWriter out = response.getWriter();
317               out.write(e.getMessage());
318             }
319             return null;
320           }
321 }
322
323 class PdpData{
324         String id;
325         int jmxPort;
326         String name;
327         String description;
328         public String getId() {
329                 return id;
330         }
331         public void setId(String id) {
332                 this.id = id;
333         }
334         public int getJmxPort() {
335                 return jmxPort;
336         }
337         public void setJmxPort(int jmxPort) {
338                 this.jmxPort = jmxPort;
339         }
340         public String getName() {
341                 return name;
342         }
343         public void setName(String name) {
344                 this.name = name;
345         }
346         public String getDescription() {
347                 return description;
348         }
349         public void setDescription(String description) {
350                 this.description = description;
351         }
352         
353 }