Policy TestSuite Enabled
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / openecomp / policy / controller / AutoPushController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.policy.controller;
22
23
24 import java.io.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.servlet.http.HttpServletRequest;
42 import javax.servlet.http.HttpServletResponse;
43
44 import org.json.JSONObject;
45 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
46 import org.openecomp.policy.common.logging.flexlogger.Logger;
47 import org.openecomp.policy.model.PDPGroupContainer;
48 import org.openecomp.policy.model.PDPPolicyContainer;
49 import org.openecomp.policy.model.Roles;
50 import org.openecomp.policy.rest.adapter.AutoPushTabAdapter;
51 import org.openecomp.policy.rest.dao.CommonClassDao;
52 import org.openecomp.policy.rest.jpa.PolicyEntity;
53 import org.openecomp.policy.rest.jpa.PolicyVersion;
54 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
55 import org.openecomp.policy.xacml.api.pap.EcompPDPGroup;
56 import org.openecomp.policy.xacml.std.pap.StdPDPGroup;
57 import org.openecomp.policy.xacml.std.pap.StdPDPPolicy;
58 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
59 import org.openecomp.portalsdk.core.web.support.JsonMessage;
60 import org.openecomp.portalsdk.core.web.support.UserUtils;
61 import org.springframework.beans.factory.annotation.Autowired;
62 import org.springframework.http.MediaType;
63 import org.springframework.stereotype.Controller;
64 import org.springframework.web.bind.annotation.RequestMapping;
65 import org.springframework.web.servlet.ModelAndView;
66
67 import com.att.research.xacml.api.pap.PAPException;
68 import com.att.research.xacml.api.pap.PDPPolicy;
69 import com.fasterxml.jackson.databind.DeserializationFeature;
70 import com.fasterxml.jackson.databind.JsonNode;
71 import com.fasterxml.jackson.databind.ObjectMapper;
72
73
74 @Controller
75 @RequestMapping({"/"})
76 public class AutoPushController extends RestrictedBaseController{
77
78         private static final Logger logger = FlexLogger.getLogger(AutoPushController.class);
79         
80         @Autowired
81         CommonClassDao commonClassDao;
82
83         private PDPGroupContainer container;
84         protected List<EcompPDPGroup> groups = Collections.synchronizedList(new ArrayList<EcompPDPGroup>());
85         
86         private static PDPPolicyContainer policyContainer;
87         Set<PDPPolicy> selectedPolicies;
88
89         private List<Object> data;
90
91         public synchronized void refreshGroups() {
92                 synchronized(this.groups) { 
93                         this.groups.clear();
94                         try {
95                                 this.groups.addAll(PolicyController.getPapEngine().getEcompPDPGroups());
96                         } catch (PAPException e) {
97                                 String message = "Unable to retrieve Groups from server: " + e;
98                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
99                         }
100
101                 }
102         }
103
104         @RequestMapping(value={"/get_AutoPushPoliciesContainerData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
105         public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response){
106                 try{
107                         Set<String> scopes = null;
108                         List<String> roles = null;
109                         data = new ArrayList<Object>();
110                         String userId = UserUtils.getUserSession(request).getOrgUserId();
111                         Map<String, Object> model = new HashMap<String, Object>();
112                         ObjectMapper mapper = new ObjectMapper();
113                         List<Object> userRoles = PolicyController.getRoles(userId);
114                         roles = new ArrayList<String>();
115                         scopes = new HashSet<String>();
116                         for(Object role: userRoles){
117                                 Roles userRole = (Roles) role;
118                                 roles.add(userRole.getRole());
119                                 if(userRole.getScope() != null){
120                                         if(userRole.getScope().contains(",")){
121                                                 String[] multipleScopes = userRole.getScope().split(",");
122                                                 for(int i =0; i < multipleScopes.length; i++){
123                                                         scopes.add(multipleScopes[i]);
124                                                 }
125                                         }else{
126                                                 if(!userRole.getScope().equals("")){
127                                                         scopes.add(userRole.getScope());
128                                                 }
129                                         }               
130                                 }
131                         }
132                         if (roles.contains("super-admin") || roles.contains("super-editor")  || roles.contains("super-guest")) {
133                                 data = commonClassDao.getData(PolicyVersion.class);
134                         }else{
135                                 if(!scopes.isEmpty()){
136                                         for(String scope : scopes){
137                                                 String query = "From PolicyVersion where policy_name like '"+scope+"%' and id > 0";
138                                                 List<Object> filterdatas = commonClassDao.getDataByQuery(query);
139                                                 if(filterdatas != null){
140                                                         for(int i =0; i < filterdatas.size(); i++){
141                                                                 data.add(filterdatas.get(i));
142                                                         }       
143                                                 }
144                                         }
145                                 }else{
146                                         PolicyVersion emptyPolicyName = new PolicyVersion();
147                                         emptyPolicyName.setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you");
148                                         data.add(emptyPolicyName);
149                                 }
150                         }
151                         model.put("policydatas", mapper.writeValueAsString(data));
152                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
153                         JSONObject j = new JSONObject(msg);
154                         response.getWriter().write(j.toString());
155                 }
156                 catch (Exception e){
157                         logger.error("Exception Occured"+e);
158                 }
159         }
160
161         @RequestMapping(value={"/auto_Push/PushPolicyToPDP.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
162         public ModelAndView PushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
163                 try {
164                         ArrayList<Object> selectedPDPS = new ArrayList<Object>();
165                         ArrayList<String> selectedPoliciesInUI = new ArrayList<String>();
166                         this.groups.addAll(PolicyController.getPapEngine().getEcompPDPGroups());
167                         ObjectMapper mapper = new ObjectMapper();
168                         this.container = new PDPGroupContainer(PolicyController.getPapEngine());
169                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
170                         JsonNode root = mapper.readTree(request.getReader());
171                         AutoPushTabAdapter adapter = (AutoPushTabAdapter) mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
172                         for (Object pdpGroupId :  adapter.getPdpDatas()) {
173                                 LinkedHashMap<?, ?> selectedPDP = (LinkedHashMap<?, ?>)pdpGroupId;
174                                 for(EcompPDPGroup pdpGroup : this.groups){
175                                         if(pdpGroup.getId().equals(selectedPDP.get("id"))){
176                                                 selectedPDPS.add(pdpGroup);
177                                         }
178                                 }
179                         }
180
181                         for (Object policyId :  adapter.getPolicyDatas()) {
182                                 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>)policyId;
183                                 String policyName = selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml";
184                                 selectedPoliciesInUI.add(policyName);
185                         }
186
187                         for (Object pdpDestinationGroupId :  selectedPDPS) {
188                                 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<PDPPolicy>();
189                                 Set<PDPPolicy> selectedPolicies = new HashSet<PDPPolicy>();
190                                 for (String policyId : selectedPoliciesInUI) {
191                                         logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId);
192                                         
193                                         //
194                                         // Get the current selection
195                                         String selectedItem = policyId;
196                                         //
197                                         assert (selectedItem != null);
198                                         // create the id of the target file
199                                         // Our standard for file naming is:
200                                         // <domain>.<filename>.<version>.xml
201                                         // since the file name usually has a ".xml", we need to strip
202                                         // that
203                                         // before adding the other parts
204                                         String name = selectedItem.replace(File.separator, ".");
205                                         String id = name;
206                                         if (id.endsWith(".xml")) {
207                                                 id = id.replace(".xml", "");
208                                                 id = id.substring(0, id.lastIndexOf("."));
209                                         }
210                                         
211                                         // Default policy to be Root policy; user can change to deferred
212                                         // later
213                                         
214                                         StdPDPPolicy selectedPolicy = null;
215                                         String dbCheckName = name;
216                                         if(dbCheckName.contains("Config_")){
217                                                 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
218                                         }else if(dbCheckName.contains("Action_")){
219                                                 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
220                                         }else if(dbCheckName.contains("Decision_")){
221                                                 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
222                                         }
223                                         PolicyController controller = new PolicyController();
224                                         String[] split = dbCheckName.split(":");
225                                         String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'";
226                                         System.out.println(query);
227                                         List<Object> queryData = controller.getDataByQuery(query);
228                                         PolicyEntity policyEntity = (PolicyEntity) queryData.get(0);
229                                         File temp = new File(name);
230                                         BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
231                                         bw.write(policyEntity.getPolicyData());
232                                         bw.close();
233                                         URI selectedURI = temp.toURI();
234                                         try {
235                                                 //
236                                                 // Create the policy
237                                                 selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI);
238                                         } catch (IOException e) {
239                                                 logger.error("Unable to create policy '" + name + "': "+ e.getMessage());
240                                                 //AdminNotification.warn("Unable to create policy '" + id + "': " + e.getMessage());
241                                         }
242                                         StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId;
243                                         if (selectedPolicy != null) {
244                                                 // Add Current policies from container
245                                                 for (EcompPDPGroup group : container.getGroups()) {
246                                                         if (group.getId().equals(selectedGroup.getId())) {
247                                                                 currentPoliciesInGroup.addAll(group.getPolicies());
248                                                         }
249                                                 }
250                                                 // copy policy to PAP
251                                                 try {
252                                                         PolicyController.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
253                                                 } catch (PAPException e) {
254                                                         logger.error("Exception Occured"+e);
255                                                         return null;
256                                                 }
257                                                 selectedPolicies.add(selectedPolicy);
258                                         }
259                                         temp.delete();
260                                 }
261                                 StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId;
262                                 StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(), pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory());
263                                 updatedGroupObject.setEcompPdps(pdpGroup.getEcompPdps());
264                                 updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs());
265                                 updatedGroupObject.setStatus(pdpGroup.getStatus());
266
267                                 // replace the original set of Policies with the set from the
268                                 // container (possibly modified by the user)
269                                 // do not allow multiple copies of same policy
270                                 Iterator<PDPPolicy> policyIterator = currentPoliciesInGroup.iterator();
271                                 logger.debug("policyIterator....." + selectedPolicies);
272                                 while (policyIterator.hasNext()) {
273                                         PDPPolicy existingPolicy = policyIterator.next();
274                                         for (PDPPolicy selPolicy : selectedPolicies) {
275                                                 if (selPolicy.getName().equals(existingPolicy.getName())) {
276                                                         if (selPolicy.getVersion().equals(existingPolicy.getVersion())) {
277                                                                 if (selPolicy.getId().equals(existingPolicy.getId())) {
278                                                                         policyIterator.remove();
279                                                                         logger.debug("Removing policy: " + selPolicy);
280                                                                         break;
281                                                                 }
282                                                         } else {
283                                                                 policyIterator.remove();
284                                                                 logger.debug("Removing Old Policy version: "+ selPolicy);
285                                                                 break;
286                                                         }
287                                                 }
288                                         }
289                                 }
290
291                                 currentPoliciesInGroup.addAll(selectedPolicies);
292                                 updatedGroupObject.setPolicies(currentPoliciesInGroup);
293                                 this.container.updateGroup(updatedGroupObject);
294
295                                 response.setCharacterEncoding("UTF-8");
296                                 response.setContentType("application / json");
297                                 request.setCharacterEncoding("UTF-8");
298
299                                 PrintWriter out = response.getWriter();
300                                 refreshGroups();
301                                 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
302                                 JSONObject j = new JSONObject(msg);
303                                 out.write(j.toString());      
304                                 return null;
305                         }
306                 }
307                 catch (Exception e){
308                         response.setCharacterEncoding("UTF-8");
309                         request.setCharacterEncoding("UTF-8");
310                         PrintWriter out = response.getWriter();
311                         out.write(e.getMessage());
312                 }
313                 return null;
314         }
315
316         @SuppressWarnings("unchecked")
317         @RequestMapping(value={"/auto_Push/remove_GroupPolicies.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
318         public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
319                 try {
320                         this.container = new PDPGroupContainer(PolicyController.getPapEngine());
321                         ObjectMapper mapper = new ObjectMapper();
322                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
323                         JsonNode root = mapper.readTree(request.getReader());  
324                         StdPDPGroup group = (StdPDPGroup)mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
325                         JsonNode removePolicyData = root.get("data");
326                         policyContainer = new PDPPolicyContainer(group);
327                         if(removePolicyData.size() > 0){
328                                 for(int i = 0 ; i < removePolicyData.size(); i++){
329                                         String data = removePolicyData.get(i).toString();
330                                         AutoPushController.policyContainer.removeItem(data);
331                                 }
332                                 Set<PDPPolicy> changedPolicies = new HashSet<PDPPolicy>();
333                                 changedPolicies.addAll((Collection<PDPPolicy>) AutoPushController.policyContainer.getItemIds());
334                                 StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(), group.getDescription(),null);
335                                 updatedGroupObject.setPolicies(changedPolicies);
336                                 updatedGroupObject.setEcompPdps(group.getEcompPdps());
337                                 updatedGroupObject.setPipConfigs(group.getPipConfigs());
338                                 updatedGroupObject.setStatus(group.getStatus());
339                                 this.container.updateGroup(updatedGroupObject);
340                         }
341                         
342                         response.setCharacterEncoding("UTF-8");
343                         response.setContentType("application / json");
344                         request.setCharacterEncoding("UTF-8");
345
346                         PrintWriter out = response.getWriter();
347                         refreshGroups();
348                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
349                         JSONObject j = new JSONObject(msg);
350
351                         out.write(j.toString());
352
353                         return null;
354                 }
355                 catch (Exception e){
356                         response.setCharacterEncoding("UTF-8");
357                         request.setCharacterEncoding("UTF-8");
358                         PrintWriter out = response.getWriter();
359                         out.write(e.getMessage());
360                 }
361                 return null;
362         }
363
364 }