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