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