Merge "JUnit test for policy/engine PolicyEngineAPI"
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / controller / AutoPushController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017-2018 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.BufferedWriter;
25 import java.io.File;
26 import java.io.FileWriter;
27 import java.io.IOException;
28 import java.io.PrintWriter;
29 import java.net.URI;
30 import java.util.ArrayList;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.HashMap;
34 import java.util.HashSet;
35 import java.util.Iterator;
36 import java.util.LinkedHashMap;
37 import java.util.List;
38 import java.util.Map;
39 import java.util.Set;
40
41 import javax.script.SimpleBindings;
42 import javax.servlet.http.HttpServletRequest;
43 import javax.servlet.http.HttpServletResponse;
44
45 import org.json.JSONObject;
46 import org.onap.policy.common.logging.flexlogger.FlexLogger;
47 import org.onap.policy.common.logging.flexlogger.Logger;
48 import org.onap.policy.model.PDPGroupContainer;
49 import org.onap.policy.model.Roles;
50 import org.onap.policy.rest.adapter.AutoPushTabAdapter;
51 import org.onap.policy.rest.dao.CommonClassDao;
52 import org.onap.policy.rest.jpa.PolicyEntity;
53 import org.onap.policy.rest.jpa.PolicyVersion;
54 import org.onap.policy.rest.util.PDPPolicyContainer;
55 import org.onap.policy.utils.PolicyUtils;
56 import org.onap.policy.xacml.api.XACMLErrorConstants;
57 import org.onap.policy.xacml.api.pap.OnapPDPGroup;
58 import org.onap.policy.xacml.std.pap.StdPDPGroup;
59 import org.onap.policy.xacml.std.pap.StdPDPPolicy;
60 import org.onap.portalsdk.core.controller.RestrictedBaseController;
61 import org.onap.portalsdk.core.web.support.JsonMessage;
62 import org.onap.portalsdk.core.web.support.UserUtils;
63 import org.springframework.beans.factory.annotation.Autowired;
64 import org.springframework.http.MediaType;
65 import org.springframework.stereotype.Controller;
66 import org.springframework.web.bind.annotation.RequestMapping;
67 import org.springframework.web.servlet.ModelAndView;
68
69 import com.att.research.xacml.api.pap.PAPException;
70 import com.att.research.xacml.api.pap.PDPPolicy;
71 import com.fasterxml.jackson.databind.DeserializationFeature;
72 import com.fasterxml.jackson.databind.JsonNode;
73 import com.fasterxml.jackson.databind.ObjectMapper;
74
75
76 @Controller
77 @RequestMapping({"/"})
78 public class AutoPushController extends RestrictedBaseController{
79
80         private static final Logger logger = FlexLogger.getLogger(AutoPushController.class);
81     private static final String UTF8 = "UTF-8";
82
83         
84         @Autowired
85         CommonClassDao commonClassDao;
86
87         private PDPGroupContainer container;
88         protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<OnapPDPGroup>());
89         
90         private PDPPolicyContainer policyContainer;
91
92         private PolicyController policyController;
93         public PolicyController getPolicyController() {
94                 return policyController;
95         }
96
97         public void setPolicyController(PolicyController policyController) {
98                 this.policyController = policyController;
99         }
100
101         private List<Object> data;
102
103         public synchronized void refreshGroups() {
104                 synchronized(this.groups) { 
105                         this.groups.clear();
106                         try {
107                                 PolicyController controller = getPolicyControllerInstance();
108                                 this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
109                         } catch (PAPException e) {
110                                 String message = "Unable to retrieve Groups from server: " + e;
111                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
112                         }
113
114                 }
115         }
116
117         private PolicyController getPolicyControllerInstance(){
118                 return policyController != null ? getPolicyController() : new PolicyController();
119         }
120         
121         @RequestMapping(value={"/get_AutoPushPoliciesContainerData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
122         public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response){
123                 try{
124                         Set<String> scopes;
125                         List<String> roles;
126                         data = new ArrayList<>();
127                         String userId = UserUtils.getUserSession(request).getOrgUserId();
128                         Map<String, Object> model = new HashMap<>();
129                         ObjectMapper mapper = new ObjectMapper();
130                         PolicyController controller = policyController != null ? getPolicyController() : new PolicyController();
131                         List<Object> userRoles = controller.getRoles(userId);
132                         roles = new ArrayList<>();
133                         scopes = new HashSet<>();
134                         for(Object role: userRoles){
135                                 Roles userRole = (Roles) role;
136                                 roles.add(userRole.getRole());
137                                 if(userRole.getScope() != null){
138                                         if(userRole.getScope().contains(",")){
139                                                 String[] multipleScopes = userRole.getScope().split(",");
140                                                 for(int i =0; i < multipleScopes.length; i++){
141                                                         scopes.add(multipleScopes[i]);
142                                                 }
143                                         }else{
144                                                 if(!"".equals(userRole.getScope())){
145                                                         scopes.add(userRole.getScope());
146                                                 }
147                                         }               
148                                 }
149                         }
150                         if (roles.contains("super-admin") || roles.contains("super-editor")  || roles.contains("super-guest")) {
151                                 data = commonClassDao.getData(PolicyVersion.class);
152                         }else{
153                                 if(!scopes.isEmpty()){
154                                         for(String scope : scopes){
155                                                 scope += "%";
156                                                 String query = "From PolicyVersion where policy_name like :scope and id > 0";
157                                                 SimpleBindings params = new SimpleBindings();
158                                                 params.put("scope", scope);
159                                                 List<Object> filterdatas = commonClassDao.getDataByQuery(query, params);
160                                                 if(filterdatas != null){
161                                                         for(int i =0; i < filterdatas.size(); i++){
162                                                                 data.add(filterdatas.get(i));
163                                                         }       
164                                                 }
165                                         }
166                                 }else{
167                                         PolicyVersion emptyPolicyName = new PolicyVersion();
168                                         emptyPolicyName.setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you");
169                                         data.add(emptyPolicyName);
170                                 }
171                         }
172                         model.put("policydatas", mapper.writeValueAsString(data));
173                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
174                         JSONObject j = new JSONObject(msg);
175                         response.getWriter().write(j.toString());
176                 }
177                 catch (Exception e){
178                         logger.error("Exception Occured"+e);
179                 }
180         }
181
182         @RequestMapping(value={"/auto_Push/PushPolicyToPDP.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
183         public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
184                 try {
185                         ArrayList<Object> selectedPDPS = new ArrayList<>();
186                         ArrayList<String> selectedPoliciesInUI = new ArrayList<>();
187                         PolicyController controller = getPolicyControllerInstance();
188                         this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
189                         ObjectMapper mapper = new ObjectMapper();
190                         this.container = new PDPGroupContainer(controller.getPapEngine());
191                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
192                         JsonNode root = mapper.readTree(request.getReader());
193                         
194                         String userId = UserUtils.getUserSession(request).getOrgUserId();
195                         logger.info("****************************************Logging UserID while Pushing  Policy to PDP Group*****************************************");
196                         logger.info("UserId:  " + userId + "Push Policy Data:  "+ root.get("pushTabData").toString());
197                         logger.info("***********************************************************************************************************************************");
198                         
199                         AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
200                         for (Object pdpGroupId :  adapter.getPdpDatas()) {
201                                 LinkedHashMap<?, ?> selectedPDP = (LinkedHashMap<?, ?>)pdpGroupId;
202                                 for(OnapPDPGroup pdpGroup : this.groups){
203                                         if(pdpGroup.getId().equals(selectedPDP.get("id"))){
204                                                 selectedPDPS.add(pdpGroup);
205                                         }
206                                 }
207                         }
208
209                         for (Object policyId :  adapter.getPolicyDatas()) {
210                                 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>)policyId;
211                                 String policyName = selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml";
212                                 selectedPoliciesInUI.add(policyName);
213                         }
214
215                         for (Object pdpDestinationGroupId :  selectedPDPS) {
216                                 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
217                                 Set<PDPPolicy> selectedPolicies = new HashSet<>();
218                                 for (String policyId : selectedPoliciesInUI) {
219                                         logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId);
220                                         
221                                         //
222                                         // Get the current selection
223                                         String selectedItem = policyId;
224                                         //
225                                         assert selectedItem != null;
226                                         // create the id of the target file
227                                         // Our standard for file naming is:
228                                         // <domain>.<filename>.<version>.xml
229                                         // since the file name usually has a ".xml", we need to strip
230                                         // that
231                                         // before adding the other parts
232                                         String name = selectedItem.replace(File.separator, ".");
233                                         String id = name;
234                                         if (id.endsWith(".xml")) {
235                                                 id = id.replace(".xml", "");
236                                                 id = id.substring(0, id.lastIndexOf('.'));
237                                         }
238                                         
239                                         // Default policy to be Root policy; user can change to deferred
240                                         // later
241                                         
242                                         StdPDPPolicy selectedPolicy = null;
243                                         String dbCheckName = name;
244                                         if(dbCheckName.contains("Config_")){
245                                                 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
246                                         }else if(dbCheckName.contains("Action_")){
247                                                 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
248                                         }else if(dbCheckName.contains("Decision_")){
249                                                 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
250                                         }
251                                         String[] split = dbCheckName.split(":");
252                                         String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
253                                         SimpleBindings policyParams = new SimpleBindings();
254                                         policyParams.put("split_1", split[1]);
255                                         policyParams.put("split_0", split[0]);
256                                         List<Object> queryData = controller.getDataByQuery(query, policyParams);
257                                         PolicyEntity policyEntity = (PolicyEntity) queryData.get(0);
258                                         File temp = new File(name);
259                                         BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
260                                         bw.write(policyEntity.getPolicyData());
261                                         bw.close();
262                                         URI selectedURI = temp.toURI();
263                                         try {
264                                                 //
265                                                 // Create the policy
266                                                 selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI);
267                                         } catch (IOException e) {
268                                                 logger.error("Unable to create policy '" + name + "': "+ e.getMessage(), e);
269                                         }
270                                         StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId;
271                                         if (selectedPolicy != null) {
272                                                 // Add Current policies from container
273                                                 for (OnapPDPGroup group : container.getGroups()) {
274                                                         if (group.getId().equals(selectedGroup.getId())) {
275                                                                 currentPoliciesInGroup.addAll(group.getPolicies());
276                                                         }
277                                                 }
278                                                 // copy policy to PAP
279                                                 try {
280                                                         controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
281                                                 } catch (PAPException e) {
282                                                         logger.error("Exception Occured"+e);
283                                                         return null;
284                                                 }
285                                                 selectedPolicies.add(selectedPolicy);
286                                         }
287                                         temp.delete();
288                                 }
289                                 StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId;
290                                 StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(), pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory());
291                                 updatedGroupObject.setOnapPdps(pdpGroup.getOnapPdps());
292                                 updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs());
293                                 updatedGroupObject.setStatus(pdpGroup.getStatus());
294                                 updatedGroupObject.setOperation("push");
295
296                                 // replace the original set of Policies with the set from the
297                                 // container (possibly modified by the user)
298                                 // do not allow multiple copies of same policy
299                                 Iterator<PDPPolicy> policyIterator = currentPoliciesInGroup.iterator();
300                                 logger.debug("policyIterator....." + selectedPolicies);
301                                 while (policyIterator.hasNext()) {
302                                         PDPPolicy existingPolicy = policyIterator.next();
303                                         for (PDPPolicy selPolicy : selectedPolicies) {
304                                                 if (selPolicy.getName().equals(existingPolicy.getName())) {
305                                                         if (selPolicy.getVersion().equals(existingPolicy.getVersion())) {
306                                                                 if (selPolicy.getId().equals(existingPolicy.getId())) {
307                                                                         policyIterator.remove();
308                                                                         logger.debug("Removing policy: " + selPolicy);
309                                                                         break;
310                                                                 }
311                                                         } else {
312                                                                 policyIterator.remove();
313                                                                 logger.debug("Removing Old Policy version: "+ selPolicy);
314                                                                 break;
315                                                         }
316                                                 }
317                                         }
318                                 }
319
320                                 currentPoliciesInGroup.addAll(selectedPolicies);
321                                 updatedGroupObject.setPolicies(currentPoliciesInGroup);
322                                 this.container.updateGroup(updatedGroupObject);
323
324                                 response.setCharacterEncoding(UTF8);
325                                 response.setContentType("application / json");
326                                 request.setCharacterEncoding(UTF8);
327
328                                 PrintWriter out = response.getWriter();
329                                 refreshGroups();
330                                 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
331                                 JSONObject j = new JSONObject(msg);
332                                 out.write(j.toString());
333                                 //
334                                 // Why is this here? This defeats the purpose of the loop??
335                                 // Sonar says to remove it or make it conditional
336                                 //
337                                 return null;
338                         }
339                 }
340                 catch (Exception e){
341                         response.setCharacterEncoding(UTF8);
342                         request.setCharacterEncoding(UTF8);
343                         PrintWriter out = response.getWriter();
344                         logger.error(e);
345                         out.write(PolicyUtils.CATCH_EXCEPTION);
346                 }
347                 return null;
348         }
349
350         @SuppressWarnings("unchecked")
351         @RequestMapping(value={"/auto_Push/remove_GroupPolicies.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
352         public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
353                 try {
354                         PolicyController controller = getPolicyControllerInstance();
355                         this.container = new PDPGroupContainer(controller.getPapEngine());
356                         ObjectMapper mapper = new ObjectMapper();
357                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
358                         JsonNode root = mapper.readTree(request.getReader());  
359                         StdPDPGroup group = mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
360                         JsonNode removePolicyData = root.get("data");
361                         
362                         String userId = UserUtils.getUserSession(request).getOrgUserId();
363                         logger.info("****************************************Logging UserID while Removing Policy from PDP Group*****************************************");
364                         logger.info("UserId:  " + userId + "PDP Group Data:  "+ root.get("activePdpGroup").toString() + "Remove Policy Data: "+root.get("data"));
365                         logger.info("***********************************************************************************************************************************");
366                         
367                         policyContainer = new PDPPolicyContainer(group);
368                         if(removePolicyData.size() > 0){
369                                 for(int i = 0 ; i < removePolicyData.size(); i++){
370                                         String polData = removePolicyData.get(i).toString();
371                                         this.policyContainer.removeItem(polData);
372                                 }
373                                 Set<PDPPolicy> changedPolicies = new HashSet<>();
374                                 changedPolicies.addAll((Collection<PDPPolicy>) this.policyContainer.getItemIds());
375                                 StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(), group.getDescription(),null);
376                                 updatedGroupObject.setPolicies(changedPolicies);
377                                 updatedGroupObject.setOnapPdps(group.getOnapPdps());
378                                 updatedGroupObject.setPipConfigs(group.getPipConfigs());
379                                 updatedGroupObject.setStatus(group.getStatus());
380                                 updatedGroupObject.setOperation("delete");
381                                 this.container.updateGroup(updatedGroupObject);
382                         }
383                         
384                         response.setCharacterEncoding(UTF8);
385                         response.setContentType("application / json");
386                         request.setCharacterEncoding(UTF8);
387
388                         PrintWriter out = response.getWriter();
389                         refreshGroups();
390                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
391                         JSONObject j = new JSONObject(msg);
392
393                         out.write(j.toString());
394
395                         return null;
396                 }
397                 catch (Exception e){
398                         response.setCharacterEncoding(UTF8);
399                         request.setCharacterEncoding(UTF8);
400                         PrintWriter out = response.getWriter();
401                         logger.error(e);
402                         out.write(PolicyUtils.CATCH_EXCEPTION);
403                 }
404                 return null;
405         }
406
407 }