[Policy-17] Removed the sql scripts from sdk app
[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         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                                 logger.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                         logger.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 ModelAndView savePDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception{
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                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while creating the PDP Group" + message);
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                         return null;
207                 }
208                 catch (Exception e){
209                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Saving the PDP Group" + e);
210                         response.setCharacterEncoding("UTF-8");
211                         request.setCharacterEncoding("UTF-8");
212                         PrintWriter out = response.getWriter();
213                         out.write(e.getMessage());
214                 }
215                 return null;
216         }
217
218         @RequestMapping(value={"/pdp_Group/remove_pdp_group"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
219         public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
220                 try{
221                         ObjectMapper mapper = new ObjectMapper();
222                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
223                         JsonNode root = mapper.readTree(request.getReader());
224                         PolicyController controller = getPolicyControllerInstance();
225                         this.container = new PDPGroupContainer(controller.getPapEngine()); 
226                         StdPDPGroup pdpGroupData =  mapper.readValue(root.get("pdpGroupData").toString(), StdPDPGroup.class);
227                         if(pdpGroupData.getName().equals("Default")) {
228                                 throw new UnsupportedOperationException("You can't remove the Default Group.");
229                         }else{
230                                 this.container.removeGroup(pdpGroupData, null);
231                         }
232
233                         response.setCharacterEncoding("UTF-8");
234                         response.setContentType("application / json");
235                         request.setCharacterEncoding("UTF-8");
236
237                         PrintWriter out = response.getWriter();
238
239                         refreshGroups(request);
240                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
241                         JSONObject j = new JSONObject(msg);
242                         out.write(j.toString());
243
244                         return null;
245                 }
246                 catch (Exception e){
247                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing the PDP Group" + e);
248                         response.setCharacterEncoding("UTF-8");
249                         request.setCharacterEncoding("UTF-8");
250                         PrintWriter out = response.getWriter();
251                         out.write(e.getMessage());
252                 }
253                 return null;
254         }
255
256         @RequestMapping(value={"/pdp_Group/save_pdpTogroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
257         public ModelAndView savePDPToGroup(HttpServletRequest request, HttpServletResponse response) throws Exception{
258                 try {
259                         ObjectMapper mapper = new ObjectMapper();
260                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
261                         JsonNode root = mapper.readTree(request.getReader());
262                         PolicyController controller = getPolicyControllerInstance();
263                         this.container = new PDPGroupContainer(controller.getPapEngine()); 
264                         String update = root.get("update").toString();
265                         PdpData pdpGroupData = (PdpData)mapper.readValue(root.get("pdpInGroup").toString(), PdpData.class);
266                         StdPDPGroup activeGroupData =  mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);
267                         try {
268
269                                 if(update.contains("false")){
270                                         this.container.addNewPDP(pdpGroupData.getId(), activeGroupData, pdpGroupData.getName(), pdpGroupData.getDescription(), pdpGroupData.getJmxPort());
271                                 }else{
272                                         this.container.updateGroup(activeGroupData);
273                                 }
274                         } catch (Exception e) {
275                                 String message = "Unable to create Group.  Reason:\n" + e.getMessage();
276                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + message);
277                         }
278
279
280                         response.setCharacterEncoding("UTF-8");
281                         response.setContentType("application / json");
282                         request.setCharacterEncoding("UTF-8");
283
284                         PrintWriter out = response.getWriter();
285                         refreshGroups(request);
286                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
287                         JSONObject j = new JSONObject(msg);
288                         out.write(j.toString());
289
290                         return null;
291                 }
292                 catch (Exception e){
293                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + e);
294                         response.setCharacterEncoding("UTF-8");
295                         request.setCharacterEncoding("UTF-8");
296                         PrintWriter out = response.getWriter();
297                         out.write(e.getMessage());
298                 }
299                 return null;
300         }
301
302         @RequestMapping(value={"/pdp_Group/remove_pdpFromGroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
303         public ModelAndView removePDPFromGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
304                 try{
305                         ObjectMapper mapper = new ObjectMapper();
306                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
307                         JsonNode root = mapper.readTree(request.getReader());
308                         PolicyController controller = getPolicyControllerInstance();
309                         this.container = new PDPGroupContainer(controller.getPapEngine()); 
310                         StdPDP deletePdp =  mapper.readValue(root.get("data").toString(), StdPDP.class);
311                         StdPDPGroup activeGroupData =  mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);
312
313                         this.container.removePDP(deletePdp, activeGroupData);
314                         response.setCharacterEncoding("UTF-8");
315                         response.setContentType("application / json");
316                         request.setCharacterEncoding("UTF-8");
317
318                         PrintWriter out = response.getWriter();
319                         refreshGroups(request);
320                         String responseString = mapper.writeValueAsString(groups);
321                         JSONObject j = new JSONObject("{pdpEntityDatas: " + responseString + "}");
322                         out.write(j.toString());
323
324                         return null;
325                 }
326                 catch (Exception e){
327                         logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing Pdp from PDP Group" + e);
328                         response.setCharacterEncoding("UTF-8");
329                         request.setCharacterEncoding("UTF-8");
330                         PrintWriter out = response.getWriter();
331                         out.write(e.getMessage());
332                 }
333                 return null;
334         }
335
336         private PolicyController getPolicyControllerInstance(){
337                 return policyController != null ? getPolicyController() : new PolicyController();
338         }
339
340         public boolean isJunit() {
341                 return junit;
342         }
343
344         public void setJunit(boolean junit) {
345                 this.junit = junit;
346         }
347
348         public Set<EcompPDPGroup> getGroupsData() {
349                 return groupsData;
350         }
351
352         public void setGroupsData(Set<EcompPDPGroup> groupsData) {
353                 this.groupsData = groupsData;
354         }
355 }
356
357 class PdpData{
358         String id;
359         int jmxPort;
360         String name;
361         String description;
362         public String getId() {
363                 return id;
364         }
365         public void setId(String id) {
366                 this.id = id;
367         }
368         public int getJmxPort() {
369                 return jmxPort;
370         }
371         public void setJmxPort(int jmxPort) {
372                 this.jmxPort = jmxPort;
373         }
374         public String getName() {
375                 return name;
376         }
377         public void setName(String name) {
378                 this.name = name;
379         }
380         public String getDescription() {
381                 return description;
382         }
383         public void setDescription(String description) {
384                 this.description = description;
385         }
386         
387 }