Initial OpenECOMP policy/engine commit
[policy/engine.git] / ecomp-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.File;
25 import java.io.IOException;
26 import java.io.PrintWriter;
27 import java.net.URI;
28 import java.nio.file.Path;
29 import java.nio.file.Paths;
30 import java.util.ArrayList;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.Date;
34 import java.util.HashSet;
35 import java.util.Iterator;
36 import java.util.LinkedHashMap;
37 import java.util.List;
38 import java.util.Set;
39
40 import javax.servlet.http.HttpServletRequest;
41 import javax.servlet.http.HttpServletResponse;
42
43 import org.apache.commons.io.FilenameUtils;
44 import org.json.JSONArray;
45 import org.json.JSONObject;
46 import org.openecomp.policy.adapter.AutoPushTabAdapter;
47 import org.openecomp.policy.dao.PolicyVersionDao;
48 import org.openecomp.policy.model.PDPGroupContainer;
49 import org.openecomp.policy.model.PDPPolicyContainer;
50 import org.openecomp.policy.model.Roles;
51 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
52 import org.openecomp.portalsdk.core.web.support.JsonMessage;
53 import org.openecomp.portalsdk.core.web.support.UserUtils;
54 import org.springframework.beans.factory.annotation.Autowired;
55 import org.springframework.http.MediaType;
56 import org.springframework.stereotype.Controller;
57 import org.springframework.web.bind.annotation.RequestMapping;
58 import org.springframework.web.servlet.ModelAndView;
59
60 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
61 import org.openecomp.policy.xacml.api.pap.EcompPDPGroup;
62
63 import com.att.research.xacml.api.pap.PAPException;
64 //import com.att.research.xacml.api.pap.PDPGroup;
65 import com.att.research.xacml.api.pap.PDPPolicy;
66 import org.openecomp.policy.xacml.std.pap.StdPDPGroup;
67 import org.openecomp.policy.xacml.std.pap.StdPDPPolicy;
68 import org.openecomp.policy.xacml.util.XACMLPolicyScanner;
69 import com.fasterxml.jackson.databind.DeserializationFeature;
70 import com.fasterxml.jackson.databind.JsonNode;
71 import com.fasterxml.jackson.databind.ObjectMapper;
72
73
74 import org.openecomp.policy.common.logging.flexlogger.FlexLogger; 
75 import org.openecomp.policy.common.logging.flexlogger.Logger;
76
77
78 @Controller
79 @RequestMapping({"/"})
80 public class AutoPushController extends RestrictedBaseController{
81
82         private static final Logger logger = FlexLogger.getLogger(AutoPushController.class);
83
84         private PDPGroupContainer container;
85         protected List<EcompPDPGroup> groups = Collections.synchronizedList(new ArrayList<EcompPDPGroup>());
86         
87         private static PDPPolicyContainer policyContainer;
88         Set<PDPPolicy> selectedPolicies;
89
90         @Autowired
91         PolicyVersionDao policyVersionDao;
92
93         public synchronized void refreshGroups() {
94                 synchronized(this.groups) { 
95                         this.groups.clear();
96                         try {
97                                 this.groups.addAll(PolicyController.getPapEngine().getEcompPDPGroups());
98                         } catch (PAPException e) {
99                                 String message = "Unable to retrieve Groups from server: " + e;
100                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
101                         }
102
103                 }
104         }
105
106         @RequestMapping(value={"/get_AutoPushPoliciesContainerData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
107         public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response){
108                 try{
109                         Path gitPath = PolicyController.getGitPath().toAbsolutePath();
110                         PrintWriter out = response.getWriter();
111                         JSONObject j = new JSONObject("{data: " + readFileRepository(gitPath,0,0,request).toString() + "}");
112                         out.write(j.toString());
113                 }
114                 catch (Exception e){
115                         e.printStackTrace();
116                 }
117         }
118
119         @SuppressWarnings("rawtypes")
120         public JSONArray readFileRepository(Path path, int id, int parentid, HttpServletRequest request){
121                 Set<String> scopes = null;
122                 List<String> roles = null;
123                 String userId = null;
124                 try {
125                         userId = UserUtils.getUserIdFromCookie(request);
126                 } catch (Exception e) {
127                         logger.error("Exception Occured while reading userid from cookie" +e);
128                 }
129                 JSONArray fileJSONArray = new JSONArray();
130                 File root = new File(path.toString());
131                 if(parentid==0 ){
132                         parentid = 1;
133                 }
134                 List<Roles> userRoles = PolicyController.getRoles(userId);
135                 roles = new ArrayList<String>();
136                 scopes = new HashSet<String>();
137                 for(Roles userRole: userRoles){
138                         roles.add(userRole.getRole());
139                         scopes.add(userRole.getScope());
140                 }
141
142                 for ( File file : root.listFiles()){
143                         if (!(file.toString().contains(".git") || file.equals(".DS_Store"))) {
144                                 if(file.isDirectory()){
145                                         JSONObject el = new JSONObject();
146                                         String fileName = file.getName().toString();
147                                         el.put("categoryId", id+1);
148                                         el.put("name", fileName);
149                                         el.put("dateModified", lastModified(file));
150                                         el.put("filePath", file.getPath());
151                                         el.put("parentCategoryId", parentid);
152                                         el.put("files",readFileRepository(file.toPath(),id+1, id+1, request));
153                                         if (roles.contains("super-admin") || roles.contains("super-editor")   || roles.contains("super-guest") ) {
154                                                 fileJSONArray.put(el);
155                                         }else{
156                                                 String filePath =  file.getPath().toString();
157                                                 int startIndex = filePath.indexOf("repository") + 11;
158                                                 filePath = filePath.substring(startIndex, filePath.length());
159                                                 if (scopes.contains(filePath)) {
160                                                         fileJSONArray.put(el);
161                                                 } 
162                                         }
163                                 }else{
164                                         JSONObject el = new JSONObject();
165                                         String policyName = "";
166                                         String version = "";
167                                         String fileName = file.getName().toString();
168                                         if(fileName.endsWith(".xml")){
169                                                 fileName = fileName.substring(0, fileName.lastIndexOf('.'));
170                                                 fileName = fileName.substring(0, fileName.lastIndexOf('.'));
171                                                 //Query the database
172                                                 String parent = file.toString().substring(file.toString().indexOf("repository")+ 11);
173                                                 parent = FilenameUtils.removeExtension(parent);
174                                                 version = parent.substring(parent.indexOf(".")+1);
175                                                 policyName = parent.substring(0, parent.lastIndexOf("."));
176                                                 if(policyName.contains("\\")){
177                                                         String scope = policyName.substring(0, policyName.lastIndexOf("\\"));
178                                                         policyName = scope + "\\" + policyName.substring(policyName.lastIndexOf("\\"));
179                                                 }               
180                                         }
181                                         el.put("categoryId", id+1);
182                                         el.put("name", fileName);
183                                         el.put("parentCategoryId", parentid);
184                                         el.put("dateModified", lastModified(file));
185                                         el.put("version", version);
186                                         el.put("filePath", file.getPath());
187                                         el.put("files",new ArrayList());
188                                         String query = "from PolicyVersion where POLICY_NAME ='" +policyName+"' and ACTIVE_VERSION ='"+version+"'";
189                                         Boolean active = PolicyController.getActivePolicy(query);
190                                         if(active){
191                                                 if (roles.contains("super-admin") || roles.contains("super-editor")   || roles.contains("super-guest") ) {
192                                                         fileJSONArray.put(el);
193                                                 }else{
194                                                         String filePath =  file.getPath().toString();
195                                                         int startIndex = filePath.indexOf("repository") + 11;
196                                                         filePath = filePath.substring(startIndex, filePath.length());
197                                                         filePath = filePath.substring(0, filePath.lastIndexOf(File.separator));
198                                                         if (scopes.contains(filePath)) {
199                                                                 fileJSONArray.put(el);
200                                                         } 
201                                                 }
202                                         }
203                                 }
204                         }
205                 }
206                 return fileJSONArray;
207         }
208
209         public Date lastModified(File file) {
210                 return new Date(file.lastModified());
211         }
212
213         public String getVersion(File file) {
214                 try {
215                         return XACMLPolicyScanner.getVersion(Paths.get(file.getAbsolutePath()));
216                 } catch (IOException e) {
217                         return "";
218                 }
219         }
220
221         public String getDomain(File file) {
222                 String filePath = file.getAbsolutePath();
223                 int startIndex = filePath.indexOf("repository")  + 11;
224                 return filePath.substring(startIndex, filePath.length());
225         }
226
227
228         @RequestMapping(value={"/auto_Push/PushPolicyToPDP.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
229         public ModelAndView PushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
230                 try {
231                         ArrayList<Object> selectedPDPS = new ArrayList<Object>();
232                         ArrayList<File> selectedPoliciesInUI = new ArrayList<File>();
233                         this.groups.addAll(PolicyController.getPapEngine().getEcompPDPGroups());
234                         ObjectMapper mapper = new ObjectMapper();
235                         this.container = new PDPGroupContainer(PolicyController.getPapEngine());
236                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
237                         JsonNode root = mapper.readTree(request.getReader());
238                         AutoPushTabAdapter adapter = (AutoPushTabAdapter) mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
239                         for (Object pdpGroupId :  adapter.getPdpDatas()) {
240                                 LinkedHashMap<?, ?> selectedPDP = (LinkedHashMap<?, ?>)pdpGroupId;
241                                 for(EcompPDPGroup pdpGroup : this.groups){
242                                         if(pdpGroup.getId().equals(selectedPDP.get("id"))){
243                                                 selectedPDPS.add(pdpGroup);
244                                         }
245                                 }
246                         }
247
248                         for (Object policyId :  adapter.getPolicyDatas()) {
249                                 LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>)policyId;
250                                 Path file =  Paths.get(selected.get("filePath").toString());
251                                 selectedPoliciesInUI.add(file.toFile());
252                         }
253
254                         for (Object pdpDestinationGroupId :  selectedPDPS) {
255                                 Set<PDPPolicy> currentPoliciesInGroup = new HashSet<PDPPolicy>();
256                                 Set<PDPPolicy> selectedPolicies = new HashSet<PDPPolicy>();
257                                 for (File policyId : selectedPoliciesInUI) {
258                                         logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId);
259                                         //
260                                         // Get the current selection
261                                         File selectedItem = policyId;
262                                         //
263                                         assert (selectedItem != null);
264                                         if (selectedItem.isDirectory()) {
265                                                 //AdminNotification.warn("Select only the Policy");
266                                                 return null;
267                                         }
268                                         // create the id of the target file
269                                         // Our standard for file naming is:
270                                         // <domain>.<filename>.<version>.xml
271                                         // since the file name usually has a ".xml", we need to strip
272                                         // that
273                                         // before adding the other parts
274                                         String name = selectedItem.getName();
275                                         if(name.endsWith(".xml")){
276                                                 name = name.substring(0, name.length() - 4);
277                                                 name = name.substring(0, name.lastIndexOf("."));
278                                         }
279                                         String id = name;
280                                         if (id.endsWith(".xml")) {
281                                                 id = id.substring(0, id.length() - 4);
282                                                 id = id.substring(0, id.lastIndexOf("."));
283                                         }
284                                         // add on the version string
285                                         String version = getVersion(selectedItem);
286                                         id += "." + version;
287                                         // put the .xml on the end
288                                         id += ".xml";
289                                         // track on the domain in front. Do this one level at a time
290                                         // until we
291                                         // reach one of the roots
292                                         String domain = getDomain(selectedItem);
293                                         String mainDomain = domain.substring(0, domain.lastIndexOf(File.separator) );
294                                         logger.info("print the main domain value"+mainDomain);
295                                         String path = mainDomain.replace('\\', '.');
296                                         if(path.contains("/")){
297                                                 path = mainDomain.replace('/', '.');
298                                                 logger.info("print the path:" +path);
299                                         }
300                                         id = path + "." + id;
301                                         // Default policy to be Root policy; user can change to deferred
302                                         // later
303                                         URI selectedURI = selectedItem.toURI();
304                                         StdPDPPolicy selectedPolicy = null;
305                                         try {
306                                                 //
307                                                 // Create the policy
308                                                 selectedPolicy = new StdPDPPolicy(id, true, name, selectedURI);
309                                         } catch (IOException e) {
310                                                 logger.error("Unable to create policy '" + id + "': "+ e.getMessage());
311                                                 //AdminNotification.warn("Unable to create policy '" + id + "': " + e.getMessage());
312                                         }
313                                         StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId;
314                                         if (selectedPolicy != null) {
315                                                 // Add Current policies from container
316                                                 for (EcompPDPGroup group : container.getGroups()) {
317                                                         if (group.getId().equals(selectedGroup.getId())) {
318                                                                 currentPoliciesInGroup.addAll(group.getPolicies());
319                                                         }
320                                                 }
321                                                 // copy policy to PAP
322                                                 try {
323                                                         PolicyController.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
324                                                 } catch (PAPException e) {
325                                                         e.printStackTrace();
326                                                         return null;
327                                                 }
328                                                 selectedPolicies.add(selectedPolicy);
329                                         }
330                                 }
331                                 StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId;
332                                 StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(), pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory());
333                                 updatedGroupObject.setEcompPdps(pdpGroup.getEcompPdps());
334                                 updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs());
335                                 updatedGroupObject.setStatus(pdpGroup.getStatus());
336
337                                 // replace the original set of Policies with the set from the
338                                 // container (possibly modified by the user)
339                                 // do not allow multiple copies of same policy
340                                 Iterator<PDPPolicy> policyIterator = currentPoliciesInGroup.iterator();
341                                 logger.debug("policyIterator....." + selectedPolicies);
342                                 while (policyIterator.hasNext()) {
343                                         PDPPolicy existingPolicy = policyIterator.next();
344                                         for (PDPPolicy selPolicy : selectedPolicies) {
345                                                 if (selPolicy.getName().equals(existingPolicy.getName())) {
346                                                         if (selPolicy.getVersion().equals(existingPolicy.getVersion())) {
347                                                                 if (selPolicy.getId().equals(existingPolicy.getId())) {
348                                                                         policyIterator.remove();
349                                                                         logger.debug("Removing policy: " + selPolicy);
350                                                                         break;
351                                                                 }
352                                                         } else {
353                                                                 policyIterator.remove();
354                                                                 logger.debug("Removing Old Policy version: "+ selPolicy);
355                                                                 break;
356                                                         }
357                                                 }
358                                         }
359                                 }
360
361                                 currentPoliciesInGroup.addAll(selectedPolicies);
362                                 updatedGroupObject.setPolicies(currentPoliciesInGroup);
363                                 this.container.updateGroup(updatedGroupObject);
364
365                                 response.setCharacterEncoding("UTF-8");
366                                 response.setContentType("application / json");
367                                 request.setCharacterEncoding("UTF-8");
368
369                                 PrintWriter out = response.getWriter();
370                                 refreshGroups();
371                                 JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
372                                 JSONObject j = new JSONObject(msg);
373                                 out.write(j.toString());      
374                                 return null;
375                         }
376                 }
377                 catch (Exception e){
378                         response.setCharacterEncoding("UTF-8");
379                         request.setCharacterEncoding("UTF-8");
380                         PrintWriter out = response.getWriter();
381                         out.write(e.getMessage());
382                 }
383                 return null;
384         }
385
386         @RequestMapping(value={"/auto_Push/remove_GroupPolicies.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
387         public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
388                 try {
389                         this.container = new PDPGroupContainer(PolicyController.getPapEngine());
390                         ObjectMapper mapper = new ObjectMapper();
391                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
392                         JsonNode root = mapper.readTree(request.getReader());  
393                         StdPDPGroup group = (StdPDPGroup)mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
394                         JsonNode removePolicyData = root.get("data");
395                         policyContainer = new PDPPolicyContainer(group);
396                         if(removePolicyData.size() > 0){
397                                 for(int i = 0 ; i < removePolicyData.size(); i++){
398                                         String data = removePolicyData.get(i).toString();
399                                         AutoPushController.policyContainer.removeItem(data);
400                                 }
401                                 Set<PDPPolicy> changedPolicies = new HashSet<PDPPolicy>();
402                                 changedPolicies.addAll((Collection<PDPPolicy>) AutoPushController.policyContainer.getItemIds());
403                                 StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(), group.getDescription(),null);
404                                 updatedGroupObject.setPolicies(changedPolicies);
405                                 updatedGroupObject.setEcompPdps(group.getEcompPdps());
406                                 updatedGroupObject.setPipConfigs(group.getPipConfigs());
407                                 updatedGroupObject.setStatus(group.getStatus());
408                                 this.container.updateGroup(updatedGroupObject);
409                         }
410                         
411                         response.setCharacterEncoding("UTF-8");
412                         response.setContentType("application / json");
413                         request.setCharacterEncoding("UTF-8");
414
415                         PrintWriter out = response.getWriter();
416                         refreshGroups();
417                         JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
418                         JSONObject j = new JSONObject(msg);
419
420                         out.write(j.toString());
421
422                         return null;
423                 }
424                 catch (Exception e){
425                         response.setCharacterEncoding("UTF-8");
426                         request.setCharacterEncoding("UTF-8");
427                         PrintWriter out = response.getWriter();
428                         out.write(e.getMessage());
429                 }
430                 return null;
431         }
432
433 }