Policy 1707 commit to LF
[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 = null;
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                                                 scopes.add(userRole.getScope());
127                                         }               
128                                 }
129                         }
130                         if (roles.contains("super-admin") || roles.contains("super-editor")   || roles.contains("super-guest") ) {
131                                 data = commonClassDao.getData(PolicyVersion.class);
132                         }else{
133                                 List<Object> filterdatas = commonClassDao.getData(PolicyVersion.class);
134                                 for(Object filter : filterdatas){
135                                         PolicyVersion filterdata = (PolicyVersion) filter;
136                                         String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator));
137                                         if(scopes.contains(scopeName)){ 
138                                                 data.add(filterdata);
139                                         }
140                                 }
141                         }
142                         model.put("policydatas", mapper.writeValueAsString(data));
143                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
144                         JSONObject j = new JSONObject(msg);
145                         response.getWriter().write(j.toString());
146                 }
147                 catch (Exception e){
148                         e.printStackTrace();
149                 }
150         }
151
152         @RequestMapping(value={"/auto_Push/PushPolicyToPDP.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
153         public ModelAndView PushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
154                 try {
155                         ArrayList<Object> selectedPDPS = new ArrayList<Object>();
156                         ArrayList<String> selectedPoliciesInUI = new ArrayList<String>();
157                         this.groups.addAll(PolicyController.getPapEngine().getEcompPDPGroups());
158                         ObjectMapper mapper = new ObjectMapper();
159                         this.container = new PDPGroupContainer(PolicyController.getPapEngine());
160                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
161                         JsonNode root = mapper.readTree(request.getReader());
162                         AutoPushTabAdapter adapter = (AutoPushTabAdapter) mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
163                         for (Object pdpGroupId :  adapter.getPdpDatas()) {
164                                 LinkedHashMap<?, ?> selectedPDP = (LinkedHashMap<?, ?>)pdpGroupId;
165                                 for(EcompPDPGroup pdpGroup : this.groups){
166                                         if(pdpGroup.getId().equals(selectedPDP.get("id"))){
167                                                 selectedPDPS.add(pdpGroup);
168                                         }
169                                 }
170                         }
171
172                         for (Object policyId :  adapter.getPolicyDatas()) {
173                                 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>)policyId;
174                                 String policyName = selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml";
175                                 selectedPoliciesInUI.add(policyName);
176                         }
177
178                         for (Object pdpDestinationGroupId :  selectedPDPS) {
179                                 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<PDPPolicy>();
180                                 Set<PDPPolicy> selectedPolicies = new HashSet<PDPPolicy>();
181                                 for (String policyId : selectedPoliciesInUI) {
182                                         logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId);
183                                         
184                                         //
185                                         // Get the current selection
186                                         String selectedItem = policyId;
187                                         //
188                                         assert (selectedItem != null);
189                                         // create the id of the target file
190                                         // Our standard for file naming is:
191                                         // <domain>.<filename>.<version>.xml
192                                         // since the file name usually has a ".xml", we need to strip
193                                         // that
194                                         // before adding the other parts
195                                         String name = selectedItem.replace(File.separator, ".");
196                                         String id = name;
197                                         if (id.endsWith(".xml")) {
198                                                 id = id.replace(".xml", "");
199                                                 id = id.substring(0, id.lastIndexOf("."));
200                                         }
201                                         
202                                         // Default policy to be Root policy; user can change to deferred
203                                         // later
204                                         
205                                         StdPDPPolicy selectedPolicy = null;
206                                         String dbCheckName = name;
207                                         if(dbCheckName.contains("Config_")){
208                                                 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
209                                         }else if(dbCheckName.contains("Action_")){
210                                                 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
211                                         }else if(dbCheckName.contains("Decision_")){
212                                                 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
213                                         }
214                                         PolicyController controller = new PolicyController();
215                                         String[] split = dbCheckName.split(":");
216                                         String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'";
217                                         System.out.println(query);
218                                         List<Object> queryData = controller.getDataByQuery(query);
219                                         PolicyEntity policyEntity = (PolicyEntity) queryData.get(0);
220                                         File temp = new File(name);
221                                         BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
222                                         bw.write(policyEntity.getPolicyData());
223                                         bw.close();
224                                         URI selectedURI = temp.toURI();
225                                         try {
226                                                 //
227                                                 // Create the policy
228                                                 selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI);
229                                         } catch (IOException e) {
230                                                 logger.error("Unable to create policy '" + name + "': "+ e.getMessage());
231                                                 //AdminNotification.warn("Unable to create policy '" + id + "': " + e.getMessage());
232                                         }
233                                         StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId;
234                                         if (selectedPolicy != null) {
235                                                 // Add Current policies from container
236                                                 for (EcompPDPGroup group : container.getGroups()) {
237                                                         if (group.getId().equals(selectedGroup.getId())) {
238                                                                 currentPoliciesInGroup.addAll(group.getPolicies());
239                                                         }
240                                                 }
241                                                 // copy policy to PAP
242                                                 try {
243                                                         PolicyController.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
244                                                 } catch (PAPException e) {
245                                                         e.printStackTrace();
246                                                         return null;
247                                                 }
248                                                 selectedPolicies.add(selectedPolicy);
249                                         }
250                                         temp.delete();
251                                 }
252                                 StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId;
253                                 StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(), pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory());
254                                 updatedGroupObject.setEcompPdps(pdpGroup.getEcompPdps());
255                                 updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs());
256                                 updatedGroupObject.setStatus(pdpGroup.getStatus());
257
258                                 // replace the original set of Policies with the set from the
259                                 // container (possibly modified by the user)
260                                 // do not allow multiple copies of same policy
261                                 Iterator<PDPPolicy> policyIterator = currentPoliciesInGroup.iterator();
262                                 logger.debug("policyIterator....." + selectedPolicies);
263                                 while (policyIterator.hasNext()) {
264                                         PDPPolicy existingPolicy = policyIterator.next();
265                                         for (PDPPolicy selPolicy : selectedPolicies) {
266                                                 if (selPolicy.getName().equals(existingPolicy.getName())) {
267                                                         if (selPolicy.getVersion().equals(existingPolicy.getVersion())) {
268                                                                 if (selPolicy.getId().equals(existingPolicy.getId())) {
269                                                                         policyIterator.remove();
270                                                                         logger.debug("Removing policy: " + selPolicy);
271                                                                         break;
272                                                                 }
273                                                         } else {
274                                                                 policyIterator.remove();
275                                                                 logger.debug("Removing Old Policy version: "+ selPolicy);
276                                                                 break;
277                                                         }
278                                                 }
279                                         }
280                                 }
281
282                                 currentPoliciesInGroup.addAll(selectedPolicies);
283                                 updatedGroupObject.setPolicies(currentPoliciesInGroup);
284                                 this.container.updateGroup(updatedGroupObject);
285
286                                 response.setCharacterEncoding("UTF-8");
287                                 response.setContentType("application / json");
288                                 request.setCharacterEncoding("UTF-8");
289
290                                 PrintWriter out = response.getWriter();
291                                 refreshGroups();
292                                 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
293                                 JSONObject j = new JSONObject(msg);
294                                 out.write(j.toString());      
295                                 return null;
296                         }
297                 }
298                 catch (Exception e){
299                         response.setCharacterEncoding("UTF-8");
300                         request.setCharacterEncoding("UTF-8");
301                         PrintWriter out = response.getWriter();
302                         out.write(e.getMessage());
303                 }
304                 return null;
305         }
306
307         @SuppressWarnings("unchecked")
308         @RequestMapping(value={"/auto_Push/remove_GroupPolicies.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
309         public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
310                 try {
311                         this.container = new PDPGroupContainer(PolicyController.getPapEngine());
312                         ObjectMapper mapper = new ObjectMapper();
313                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
314                         JsonNode root = mapper.readTree(request.getReader());  
315                         StdPDPGroup group = (StdPDPGroup)mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
316                         JsonNode removePolicyData = root.get("data");
317                         policyContainer = new PDPPolicyContainer(group);
318                         if(removePolicyData.size() > 0){
319                                 for(int i = 0 ; i < removePolicyData.size(); i++){
320                                         String data = removePolicyData.get(i).toString();
321                                         AutoPushController.policyContainer.removeItem(data);
322                                 }
323                                 Set<PDPPolicy> changedPolicies = new HashSet<PDPPolicy>();
324                                 changedPolicies.addAll((Collection<PDPPolicy>) AutoPushController.policyContainer.getItemIds());
325                                 StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(), group.getDescription(),null);
326                                 updatedGroupObject.setPolicies(changedPolicies);
327                                 updatedGroupObject.setEcompPdps(group.getEcompPdps());
328                                 updatedGroupObject.setPipConfigs(group.getPipConfigs());
329                                 updatedGroupObject.setStatus(group.getStatus());
330                                 this.container.updateGroup(updatedGroupObject);
331                         }
332                         
333                         response.setCharacterEncoding("UTF-8");
334                         response.setContentType("application / json");
335                         request.setCharacterEncoding("UTF-8");
336
337                         PrintWriter out = response.getWriter();
338                         refreshGroups();
339                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
340                         JSONObject j = new JSONObject(msg);
341
342                         out.write(j.toString());
343
344                         return null;
345                 }
346                 catch (Exception e){
347                         response.setCharacterEncoding("UTF-8");
348                         request.setCharacterEncoding("UTF-8");
349                         PrintWriter out = response.getWriter();
350                         out.write(e.getMessage());
351                 }
352                 return null;
353         }
354
355 }