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