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