Merge "Fix audit log to contain ending timestamp"
[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.model.Roles;
42 import org.onap.policy.xacml.api.XACMLErrorConstants;
43 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
44 import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
45 import org.onap.policy.xacml.std.pap.StdPDP;
46 import org.onap.policy.xacml.std.pap.StdPDPGroup;
47 import org.onap.portalsdk.core.controller.RestrictedBaseController;
48 import org.onap.portalsdk.core.web.support.JsonMessage;
49 import org.onap.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                         
199                         String userId = UserUtils.getUserSession(request).getOrgUserId();
200                         policyLogger.info("****************************************Logging UserID for Save PDP Group Function*****************************************");
201                         policyLogger.info("UserId:  " + userId + "PDP Group Data:  "+ root.get("pdpGroupData").toString());
202                         policyLogger.info("***************************************************************************************************************************");
203                         
204                         StdPDPGroup pdpGroupData =  mapper.readValue(root.get("pdpGroupData").toString().replace("groupName", "name"), StdPDPGroup.class);
205                         try {
206                                 if(pdpGroupData.getId() == null){
207                                         this.container.addNewGroup(pdpGroupData.getName(), pdpGroupData.getDescription());
208                                 }else{
209                                         this.container.updateGroup(pdpGroupData);
210                                 }
211
212                         } catch (Exception e) {
213                                 String message = "Unable to create Group.  Reason:\n" + e.getMessage();
214                                 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while creating the PDP Group" + message + e);
215                         }
216
217
218                         response.setCharacterEncoding("UTF-8");
219                         response.setContentType("application / json");
220                         request.setCharacterEncoding("UTF-8");
221
222                         PrintWriter out = response.getWriter();
223                         refreshGroups(request);
224                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
225                         JSONObject j = new JSONObject(msg);
226                         out.write(j.toString());
227                 }
228                 catch (Exception e){
229                         policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Saving the PDP Group" + e);
230                         response.setCharacterEncoding("UTF-8");
231                         PrintWriter out = null;
232                         try {
233                                 request.setCharacterEncoding("UTF-8");
234                                 out = response.getWriter();
235                                 out.write(e.getMessage());
236                         } catch (Exception e1) {
237                                 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Saving the PDP Group" + e1);
238                         }
239                 }
240         }
241
242         @RequestMapping(value={"/pdp_Group/remove_pdp_group"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
243         public void removePDPGroup(HttpServletRequest request, HttpServletResponse response){
244                 try{
245                         ObjectMapper mapper = new ObjectMapper();
246                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
247                         JsonNode root = mapper.readTree(request.getReader());
248                         PolicyController controller = getPolicyControllerInstance();
249                         this.container = new PDPGroupContainer(controller.getPapEngine()); 
250                         
251                         String userId = UserUtils.getUserSession(request).getOrgUserId();
252                         policyLogger.info("****************************************Logging UserID for Remove PDP Group Function*****************************************");
253                         policyLogger.info("UserId:  " + userId + "PDP Group Data:  "+ root.get("pdpGroupData").toString());
254                         policyLogger.info("*****************************************************************************************************************************");
255                         
256                         StdPDPGroup pdpGroupData =  mapper.readValue(root.get("pdpGroupData").toString(), StdPDPGroup.class);
257                         if(pdpGroupData.getName().equals("Default")) {
258                                 throw new UnsupportedOperationException("You can't remove the Default Group.");
259                         }else{
260                                 this.container.removeGroup(pdpGroupData, null);
261                         }
262
263                         response.setCharacterEncoding("UTF-8");
264                         response.setContentType("application / json");
265                         request.setCharacterEncoding("UTF-8");
266
267                         PrintWriter out = response.getWriter();
268
269                         refreshGroups(request);
270                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
271                         JSONObject j = new JSONObject(msg);
272                         out.write(j.toString());
273                 }
274                 catch (Exception e){
275                         policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing the PDP Group" + e);
276                         PrintWriter out;
277                         try {
278                                 response.setCharacterEncoding("UTF-8");
279                                 request.setCharacterEncoding("UTF-8");
280                                 out = response.getWriter();
281                                 out.write(e.getMessage());
282                         } catch (Exception e1) {
283                                 policyLogger.error("Exception Occured"+ e1);
284                         }
285                 }
286         }
287
288         @RequestMapping(value={"/pdp_Group/save_pdpTogroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
289         public void savePDPToGroup(HttpServletRequest request, HttpServletResponse response){
290                 try {
291                         ObjectMapper mapper = new ObjectMapper();
292                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
293                         JsonNode root = mapper.readTree(request.getReader());
294                         PolicyController controller = getPolicyControllerInstance();
295                         this.container = new PDPGroupContainer(controller.getPapEngine()); 
296                         String update = root.get("update").toString();
297                         PdpData pdpGroupData = (PdpData)mapper.readValue(root.get("pdpInGroup").toString(), PdpData.class);
298                         StdPDPGroup activeGroupData =  mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);
299                         
300                         String userId = UserUtils.getUserSession(request).getOrgUserId();
301                         policyLogger.info("****************************************Logging UserID while Saving  pdp in  PDP Group*****************************************");
302                         policyLogger.info("UserId:  " + userId + "PDP Group Data:  "+ root.get("pdpInGroup").toString() + "Active Group Data: "+ root.get("activePDP").toString());
303                         policyLogger.info("*******************************************************************************************************************************");
304                         
305                         try {
306
307                                 if(update.contains("false")){
308                                         this.container.addNewPDP(pdpGroupData.getId(), activeGroupData, pdpGroupData.getName(), pdpGroupData.getDescription(), pdpGroupData.getJmxPort());
309                                 }else{
310                                         this.container.updateGroup(activeGroupData);
311                                 }
312                         } catch (Exception e) {
313                                 String message = "Unable to create Group.  Reason:\n" + e.getMessage();
314                                 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + message + e);
315                         }
316
317
318                         response.setCharacterEncoding("UTF-8");
319                         response.setContentType("application / json");
320                         request.setCharacterEncoding("UTF-8");
321
322                         PrintWriter out = response.getWriter();
323                         refreshGroups(request);
324                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
325                         JSONObject j = new JSONObject(msg);
326                         out.write(j.toString());
327                 }
328                 catch (Exception e){
329                         policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + e);
330                         PrintWriter out;
331                         try {
332                                 response.setCharacterEncoding("UTF-8");
333                                 request.setCharacterEncoding("UTF-8");
334                                 out = response.getWriter();
335                                 out.write(e.getMessage());
336                         } catch (Exception e1) {
337                                 policyLogger.error("Exception Occured"+ e1);
338                         }
339                 }
340         }
341
342         @RequestMapping(value={"/pdp_Group/remove_pdpFromGroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
343         public void removePDPFromGroup(HttpServletRequest request, HttpServletResponse response){
344                 try{
345                         ObjectMapper mapper = new ObjectMapper();
346                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
347                         JsonNode root = mapper.readTree(request.getReader());
348                         PolicyController controller = getPolicyControllerInstance();
349                         this.container = new PDPGroupContainer(controller.getPapEngine()); 
350                         StdPDP deletePdp =  mapper.readValue(root.get("data").toString(), StdPDP.class);
351                         StdPDPGroup activeGroupData =  mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);
352
353                         String userId = UserUtils.getUserSession(request).getOrgUserId();
354                         policyLogger.info("****************************************Logging UserID while Removing  pdp from  PDP Group*****************************************");
355                         policyLogger.info("UserId:  " + userId + "Delete PDP Group Data:  "+ root.get("data").toString() + "Active Group Data: "+ root.get("activePDP").toString());
356                         policyLogger.info("***********************************************************************************************************************************");
357                         
358                         this.container.removePDP(deletePdp, activeGroupData);
359                         response.setCharacterEncoding("UTF-8");
360                         response.setContentType("application / json");
361                         request.setCharacterEncoding("UTF-8");
362
363                         PrintWriter out = response.getWriter();
364                         refreshGroups(request);
365                         String responseString = mapper.writeValueAsString(groups);
366                         JSONObject j = new JSONObject("{pdpEntityDatas: " + responseString + "}");
367                         out.write(j.toString());
368                 }
369                 catch (Exception e){
370                         policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing Pdp from PDP Group" + e);
371                         PrintWriter out;
372                         try {
373                                 response.setCharacterEncoding("UTF-8");
374                                 request.setCharacterEncoding("UTF-8");
375                                 out = response.getWriter();
376                                 out.write(e.getMessage());
377                         } catch (Exception e1) {
378                                 policyLogger.error("Exception Occured"+ e1);
379                         }
380                 }
381         }
382
383         private PolicyController getPolicyControllerInstance(){
384                 return policyController != null ? getPolicyController() : new PolicyController();
385         }
386
387         public boolean isJunit() {
388                 return junit;
389         }
390
391         public void setJunit(boolean junit) {
392                 this.junit = junit;
393         }
394
395         public Set<OnapPDPGroup> getGroupsData() {
396                 return groupsData;
397         }
398
399         public void setGroupsData(Set<OnapPDPGroup> groupsData) {
400                 this.groupsData = groupsData;
401         }
402 }
403
404 class PdpData{
405         String id;
406         int jmxPort;
407         String name;
408         String description;
409         public String getId() {
410                 return id;
411         }
412         public void setId(String id) {
413                 this.id = id;
414         }
415         public int getJmxPort() {
416                 return jmxPort;
417         }
418         public void setJmxPort(int jmxPort) {
419                 this.jmxPort = jmxPort;
420         }
421         public String getName() {
422                 return name;
423         }
424         public void setName(String name) {
425                 this.name = name;
426         }
427         public String getDescription() {
428                 return description;
429         }
430         public void setDescription(String description) {
431                 this.description = description;
432         }
433         
434 }