Initial OpenECOMP policy/engine commit
[policy/engine.git] / ecomp-sdk-app / src / main / java / org / openecomp / policy / admin / PolicyManagerServlet.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 /*
22  * 
23  * 
24  * 
25  * */
26 package org.openecomp.policy.admin;
27
28
29 import java.io.BufferedOutputStream;
30 import java.io.BufferedReader;
31 import java.io.File;
32 import java.io.FileFilter;
33 import java.io.FileInputStream;
34 import java.io.FileOutputStream;
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.io.OutputStream;
38 import java.io.PrintWriter;
39 import java.nio.file.DirectoryStream;
40 import java.nio.file.Files;
41 import java.nio.file.Path;
42 import java.nio.file.Paths;
43 import java.nio.file.attribute.BasicFileAttributes;
44 import java.text.SimpleDateFormat;
45 import java.util.ArrayList;
46 import java.util.Arrays;
47 import java.util.Date;
48 import java.util.HashMap;
49 import java.util.HashSet;
50 import java.util.List;
51 import java.util.Map;
52 import java.util.Set;
53
54 import javax.servlet.ServletException;
55 import javax.servlet.http.HttpServlet;
56 import javax.servlet.http.HttpServletRequest;
57 import javax.servlet.http.HttpServletResponse;
58
59 import org.apache.commons.compress.utils.IOUtils;
60 import org.apache.commons.fileupload.FileItem;
61 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
62 import org.apache.commons.fileupload.servlet.ServletFileUpload;
63 import org.apache.commons.io.FileUtils;
64 import org.apache.commons.io.FilenameUtils;
65 import org.apache.commons.io.filefilter.WildcardFileFilter;
66 import org.apache.http.HttpStatus;
67 import org.json.JSONException;
68 import org.json.JSONObject;
69 import org.openecomp.policy.adapter.PolicyAdapter;
70 import org.openecomp.policy.components.HumanPolicyComponent;
71 import org.openecomp.policy.controller.ActionPolicyController;
72 import org.openecomp.policy.controller.CreateBRMSParamController;
73 import org.openecomp.policy.controller.CreateBRMSRawController;
74 import org.openecomp.policy.controller.CreateClosedLoopFaultController;
75 import org.openecomp.policy.controller.CreateClosedLoopPMController;
76 import org.openecomp.policy.controller.CreateDcaeMicroServiceController;
77 import org.openecomp.policy.controller.CreateFirewallController;
78 import org.openecomp.policy.controller.CreatePolicyController;
79 import org.openecomp.policy.controller.DecisionPolicyController;
80 import org.openecomp.policy.controller.PolicyController;
81 import org.openecomp.policy.controller.PolicyExportAndImportController;
82 import org.openecomp.policy.elk.client.ElkConnector;
83 import org.openecomp.policy.model.Roles;
84 import org.openecomp.policy.rest.jpa.PolicyEditorScopes;
85 import org.openecomp.policy.rest.jpa.PolicyVersion;
86 import org.openecomp.policy.rest.jpa.UserInfo;
87 import org.openecomp.policy.utils.XACMLPolicyWriterWithPapNotify;
88 import org.openecomp.portalsdk.core.web.support.UserUtils;
89
90 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
91 import org.openecomp.policy.common.logging.flexlogger.Logger;
92
93 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
94 import org.openecomp.policy.xacml.util.XACMLPolicyScanner;
95 import com.fasterxml.jackson.databind.JsonNode;
96 import com.fasterxml.jackson.databind.ObjectMapper;
97
98 public class PolicyManagerServlet extends HttpServlet {
99         private static final Logger LOG = FlexLogger.getLogger(PolicyManagerServlet.class);
100         private static final long serialVersionUID = -8453502699403909016L;
101
102         private enum Mode {
103                 LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT
104         }
105
106         public  static final String REPOSITORY_BASE_PATH = PolicyController.getGitPath().toString();
107         private static String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss";
108         public static final String CONFIG_HOME = PolicyController.getConfigHome();
109         public static final String ACTION_HOME = PolicyController.getActionHome();
110         private static String CONTENTTYPE = "application/json";
111         private File repofilePath;
112         private static String SUPERADMIN = "super-admin";
113         private static String SUPEREDITOR = "super-editor";
114         private static String SUPERGUEST = "super-guest";
115         private static String ADMIN = "admin";
116         private static String EDITOR = "editor";
117         private static String GUEST = "guest";
118         private static String RESULT = "result";
119         private static String REPOSITORY = "repository";
120         
121         private static String CONFIG = "Config_";
122         private static String ACTION = "Action_";
123         private static String DECISION = "Decision_";
124         
125         @Override
126         public void init() throws ServletException {
127                 super.init();
128         }
129
130         @Override
131         public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
132                 String path = request.getParameter("path");
133                 File file = new File(REPOSITORY_BASE_PATH, path);
134
135                 if (!file.isFile()) {
136                         // if not a file, it is a folder, show this error.  
137                         response.sendError(HttpServletResponse.SC_NOT_FOUND, "Resource Not Found");
138                         return;
139                 }
140
141                 response.setHeader("Content-Type", getServletContext().getMimeType(file.getName()));
142                 response.setHeader("Content-Length", String.valueOf(file.length()));
143                 response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
144
145                 FileInputStream input = null;
146                 BufferedOutputStream output = null;
147                 try {
148                         input = new FileInputStream(file);
149                         output = new BufferedOutputStream(response.getOutputStream());
150                         byte[] buffer = new byte[8192];
151                         for (int length = 0; (length = input.read(buffer)) > 0;) {
152                                 output.write(buffer, 0, length);
153                         }
154                 } catch (Exception e) {
155                         LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Reading Imput Stream" + e);
156                 } finally {
157                         if (output != null) {
158                                 try {
159                                         output.close();
160                                 } catch (Exception e) {
161                                         LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Closing Output Stream" + e);
162                                 }
163                         }
164                         if (input != null) {
165                                 try {
166                                         input.close();
167                                 } catch (Exception e) {
168                                         LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Closing Input Stream" + e);
169                                 }
170                         }
171                 }
172
173         }
174
175         @Override
176         protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
177                 LOG.debug("doPost");
178                 try {
179                         // if request contains multipart-form-data
180                         if (ServletFileUpload.isMultipartContent(request)) {
181                                 uploadFile(request, response);
182                         }
183                         // all other post request has json params in body
184                         else {
185                                 fileOperation(request, response);
186                         }
187                 } catch (Exception e) {
188                         setError(e, response);
189                 }
190         }
191
192         //Set Error Message for Exception
193         private void setError(Exception t, HttpServletResponse response) throws IOException {
194                 try {
195                         JSONObject responseJsonObject = error(t.getMessage());
196                         response.setContentType(CONTENTTYPE);
197                         PrintWriter out = response.getWriter();
198                         out.print(responseJsonObject);
199                         out.flush();
200                 } catch (Exception x) {
201                         response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage());
202                 }
203         }
204
205         //Policy Import Functionality
206         private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException {
207                 try {
208                         String newFile;
209                         Map<String, InputStream> files = new HashMap<String, InputStream>();
210
211                         List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
212                         for (FileItem item : items) {
213                                 if (!item.isFormField()) {
214                                         // Process form file field (input type="file").
215                                         files.put(item.getName(), item.getInputStream());
216                                         if(item.getName().endsWith(".tar")){
217                                                 try{
218                                                         File file = new File(item.getName());
219                                                         OutputStream outputStream = new FileOutputStream(file);
220                                                         IOUtils.copy(item.getInputStream(), outputStream);
221                                                         outputStream.close();
222                                                         newFile = file.toString();
223                                                         PolicyExportAndImportController importController = new PolicyExportAndImportController();
224                                                         importController.ImportRepositoryFile(newFile, request);
225                                                 }catch(Exception e){
226                                                         LOG.error("Upload error : " + e);
227                                                 }
228                                         }
229                                 }
230                         }
231
232                         JSONObject responseJsonObject = null;
233                         responseJsonObject = this.success();
234                         response.setContentType("application/json");
235                         PrintWriter out = response.getWriter();
236                         out.print(responseJsonObject);
237                         out.flush();
238                 } catch (Exception e) {
239                         LOG.debug("Cannot write file");
240                         throw new ServletException("Cannot write file", e);
241                 }
242         }
243
244         //File Operation Functionality
245         private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
246                 JSONObject responseJsonObject = null;
247                 try {
248                         StringBuilder sb = new StringBuilder();
249                         BufferedReader br = request.getReader();
250                         String str;
251                         while ((str = br.readLine()) != null) {
252                                 sb.append(str);
253                         }
254                         br.close();
255                         JSONObject jObj = new JSONObject(sb.toString());
256                         JSONObject params = jObj.getJSONObject("params");
257                         Mode mode = Mode.valueOf(params.getString("mode"));
258                         switch (mode) {
259                         case ADDFOLDER:
260                                 responseJsonObject = addFolder(params, request);
261                                 break;
262                         case COPY:
263                                 responseJsonObject = copy(params, request);
264                                 break;
265                         case DELETE:
266                                 responseJsonObject = delete(params, request);
267                                 break;
268                         case EDITFILE: 
269                                 responseJsonObject = editFile(params);
270                                 break;
271                         case VIEWPOLICY: 
272                                 responseJsonObject = editFile(params);
273                                 break;  
274                         case LIST:
275                                 responseJsonObject = list(params, request);
276                                 break;
277                         case RENAME:
278                                 responseJsonObject = rename(params, request);
279                                 break;
280                         case DESCRIBEPOLICYFILE:
281                                 responseJsonObject = describePolicy(params);
282                                 break;
283                         case ADDSUBSCOPE:
284                                 responseJsonObject = addFolder(params, request);
285                                 break;
286                         case SWITCHVERSION:
287                                 responseJsonObject = switchVersion(params, request);
288                                 break;
289                         default:
290                                 throw new ServletException("not implemented");
291                         }
292                         if (responseJsonObject == null) {
293                                 responseJsonObject = error("generic error : responseJsonObject is null");
294                         }
295                 } catch (Exception e) {
296                         LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While doing File Operation" + e);
297                         responseJsonObject = error(e.getMessage());
298                 }
299                 response.setContentType("application/json");
300                 PrintWriter out = response.getWriter();
301                 out.print(responseJsonObject);
302                 out.flush();
303         }
304
305         //Switch Version Functionality
306         private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{
307                 String path = params.getString("path");
308                 String userId = null;
309                 try {
310                         userId = UserUtils.getUserIdFromCookie(request);
311                 } catch (Exception e) {
312                         LOG.error("Exception Occured while reading userid from cookie" +e);
313                 }
314                 if(params.toString().contains("activeVersion")){
315                         String activeVersion = params.getString("activeVersion");
316                         String highestVersion = params.getString("highestVersion");
317                         if(Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)){
318                                 return error("The Version shouldn't be greater than Highest Value");
319                         }else{
320                                 String removeExtension = path.replace(".xml", "");
321                                 String policyName = removeExtension.substring(0, removeExtension.lastIndexOf("."));
322                                 String activePolicy = policyName + "." + activeVersion + ".xml";
323                                 File file = new File(Paths.get(REPOSITORY_BASE_PATH, activePolicy).toString());
324                                 if(!file.exists()){
325                                         return error("The Policy is Not Existing in Workspace");
326                                 }else{
327                                         if(policyName.contains("/")){
328                                                 policyName = policyName.replace("/", File.separator);
329                                         }
330                                         policyName = policyName.substring(policyName.indexOf(File.separator)+1);
331                                         if(policyName.contains("\\")){
332                                                 policyName = policyName.replace(File.separator, "\\");
333                                         }
334                                         String query = "update PolicyVersion set active_version='"+activeVersion+"' where policy_name ='" +policyName+"'  and id >0";
335                                         //query the database
336                                         PolicyController.updatePolicyVersion(query);
337                                         //Policy Notification
338                                         PolicyController controller = new PolicyController();
339                                         PolicyVersion entity = new PolicyVersion();
340                                         entity.setPolicyName(policyName);
341                                         entity.setActiveVersion(Integer.parseInt(activeVersion));
342                                         entity.setModifiedBy(userId);
343                                         controller.WatchPolicyFunction(entity, policyName, "SwitchVersion");
344                                 }
345                         }
346                 }
347                 File policyFile = new File(REPOSITORY_BASE_PATH, path);
348                 PolicyController policyController =  new PolicyController();
349                 return policyController.SwitchVersionPolicyContent(policyFile);
350         }
351
352         //Describe Policy
353         private JSONObject describePolicy(JSONObject params){
354                 String path = params.getString("path");
355                 File policyFile = new File(REPOSITORY_BASE_PATH, path);
356         
357                 return HumanPolicyComponent.DescribePolicy(policyFile);
358         }
359
360         //Get the List of Policies and Scopes for Showing in Editor tab
361         private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException { 
362                 Set<String> scopes = null;
363                 List<String> roles = null;
364                 try {
365                         //Get the Login Id of the User from Request
366                         String userId =  UserUtils.getUserIdFromCookie(request);
367                         //Check if the Role and Scope Size are Null get the values from db. 
368                         List<Roles> userRoles = PolicyController.getRoles(userId);
369                         roles = new ArrayList<String>();
370                         scopes = new HashSet<String>();
371                         for(Roles userRole: userRoles){
372                                 roles.add(userRole.getRole());
373                                 if(userRole.getScope() != null){
374                                         if(userRole.getScope().contains(",")){
375                                                 String[] multipleScopes = userRole.getScope().split(",");
376                                                 for(int i =0; i < multipleScopes.length; i++){
377                                                         scopes.add(multipleScopes[i]);
378                                                 }
379                                         }else{
380                                                 scopes.add(userRole.getScope());
381                                         }               
382                                 }
383                         }
384                         if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
385                                 if(scopes.isEmpty()){
386                                         return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
387                                 }
388                         } 
389
390                         List<JSONObject> resultList = new ArrayList<JSONObject>();
391                         SimpleDateFormat dt = new SimpleDateFormat(DATE_FORMAT);
392                         boolean onlyFolders = params.getBoolean("onlyFolders");
393                         String path = params.getString("path");
394                         if(path.contains("..xml")){
395                                 path = path.replaceAll("..xml", "").trim();
396                         }
397
398
399                         if("/".equals(path)){
400                                 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
401                                         try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(REPOSITORY_BASE_PATH, path))) {
402                                                 for (Path pathObj : directoryStream) {
403                                                         BasicFileAttributes attrs = Files.readAttributes(pathObj, BasicFileAttributes.class);
404                                                         if (onlyFolders && !attrs.isDirectory()) {
405                                                                 continue;
406                                                         }
407                                                         JSONObject el = new JSONObject();
408                                                         String fileName = pathObj.getFileName().toString();
409                                                         if (!(fileName.equals(".DS_Store") || fileName.contains(".git"))) {
410                                                                 if(!fileName.endsWith(".xml")){
411                                                                         el.put("name", fileName);       
412                                                                         el.put("date", dt.format(new Date(attrs.lastModifiedTime().toMillis())));
413                                                                         el.put("size", attrs.size());
414                                                                         el.put("type", attrs.isDirectory() ? "dir" : "file");
415                                                                         resultList.add(el);
416                                                                 }
417                                                         }
418                                                 }
419                                         } catch (IOException ex) {
420                                                 LOG.error("Error Occured While reading Policy Files List"+ex );
421                                         }                       
422                                 }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){
423                                         for(Object scope : scopes){
424                                                 JSONObject el = new JSONObject();
425                                                 Path filePath = Paths.get(REPOSITORY_BASE_PATH + File.separator + scope);
426                                                 if(Files.exists(filePath)){
427                                                         el.put("name", scope);  
428                                                         el.put("date", dt.format(filePath.toFile().lastModified()));
429                                                         el.put("size", "");
430                                                         el.put("type", "dir");
431                                                         resultList.add(el);
432                                                 }
433                                         }
434                                 }
435                         }else{
436                                 try{
437                                         String scopeName = path.substring(path.indexOf("/") +1);
438                                         activePolicyList(scopeName, resultList, roles, scopes, onlyFolders);
439                                 } catch (Exception ex) {
440                                 LOG.error("Error Occured While reading Policy Files List"+ex );
441                         }                       
442                         }
443
444                         return new JSONObject().put(RESULT, resultList);
445                 } catch (Exception e) {
446                         LOG.error("list", e);
447                         return error(e.getMessage());
448                 }
449         }
450         
451         //Get Active Policy List based on Scope Selection form Policy Version table
452         private void activePolicyList(String scopeName, List<JSONObject> resultList, List<String> roles, Set<String> scopes, boolean onlyFolders){
453                 if(scopeName.contains("/")){
454                         scopeName = scopeName.replace("/", File.separator);
455                 }
456                 if(scopeName.contains("\\")){
457                         scopeName = scopeName.replace("\\", "\\\\\\\\");
458                 }
459                 String query = "from PolicyVersion where POLICY_NAME like'" +scopeName+"%'";
460                 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"%'";
461                 List<PolicyVersion> activePolicies = PolicyController.getListOfActivePolicies(query);
462                 List<PolicyEditorScopes> scopesList = PolicyController.getListOfPolicyEditorScopes(scopeNamequery);
463                 for(PolicyEditorScopes scopeById : scopesList){
464                         String scope = scopeById.getScopeName();
465                         if(scope.contains(File.separator)){
466                                 String checkScope = scope.substring(0, scope.lastIndexOf(File.separator));
467                                 if(scopeName.contains("\\\\")){
468                                         scopeName = scopeName.replace("\\\\", File.separator);
469                                 }
470                                 if(scopeName.equalsIgnoreCase(checkScope)){
471                                         JSONObject el = new JSONObject();
472                                         Path filePath = Paths.get(REPOSITORY_BASE_PATH + File.separator + scope);
473                                         if(Files.exists(filePath)){
474                                                 el.put("name", filePath.getFileName()); 
475                                                 el.put("date", scopeById.getModifiedDate());
476                                                 el.put("size", "");
477                                                 el.put("type", "dir");
478                                                 el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
479                                                 el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
480                                                 resultList.add(el);
481                                         }
482                                 }
483                         }               
484                 }
485                 for (PolicyVersion policy : activePolicies) {
486                         String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator));
487                         String activepath = REPOSITORY_BASE_PATH + File.separator + policy.getPolicyName() + "." + policy.getActiveVersion() + ".xml";
488                         Path pathObj = Paths.get(activepath);
489                         if(Files.exists(pathObj)){
490                                 BasicFileAttributes attrs;
491                                 try {
492                                         attrs = Files.readAttributes(pathObj, BasicFileAttributes.class);
493                                         if (onlyFolders && !attrs.isDirectory()) {
494                                                 continue;
495                                         }
496                                         if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){    
497                                                 readPolicies(pathObj, attrs, scopeName, resultList);
498                                         }else if(!scopes.isEmpty()){
499                                                 for(String value : scopes){
500                                                         if(scopeNameValue.startsWith(value)){
501                                                                 readPolicies(pathObj, attrs, scopeName, resultList);
502                                                         }
503                                                 }
504                                         }
505                                 } catch (Exception e) {
506                                         LOG.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Exception occured while reading File Attributes"+e);
507                                 }
508                         }
509                 }       
510         }
511         
512         //Read the Policy File to get Created by and Modified by User Name of Policy 
513         public void readPolicies(Path pathObj, BasicFileAttributes attrs, String scopeName, List<JSONObject> resultList){
514                 JSONObject el = new JSONObject();
515                 String policyName = "";
516                 String version = "";
517                 String scope = "";
518                 if(scopeName.contains("\\\\")){
519                         scopeName = scopeName.replace("\\\\", File.separator);
520                 }
521                 SimpleDateFormat dt = new SimpleDateFormat(DATE_FORMAT);
522                 String fileName = pathObj.getFileName().toString();
523                 if (!(fileName.equals(".DS_Store") || fileName.startsWith(".git"))) {
524                         if(fileName.endsWith(".xml")){
525                                 fileName = fileName.substring(0, fileName.lastIndexOf('.'));
526                                 fileName = fileName.substring(0, fileName.lastIndexOf('.'));
527                                 //Query the database
528                                 String parent = pathObj.toString().substring(pathObj.toString().indexOf(REPOSITORY)+ 11);
529                                 parent = FilenameUtils.removeExtension(parent);
530                                 version = parent.substring(parent.indexOf(".")+1);
531                                 policyName = parent.substring(0, parent.lastIndexOf("."));
532                                 scope = policyName.substring(0, policyName.lastIndexOf(File.separator));
533                                 if(policyName.contains("\\")){
534                                         policyName = scope + "\\" + policyName.substring(policyName.lastIndexOf("\\"));
535                                 }               
536                         }
537                         if(scopeName.equalsIgnoreCase(scope)){
538                                 el.put("name", fileName);
539                                 if(pathObj.toFile().toString().endsWith(".xml")){
540                                         el.put("version", version);
541                                         List<String> createdByModifiedBy;
542                                         try {
543                                                 createdByModifiedBy = XACMLPolicyScanner.getCreatedByModifiedBy(pathObj);
544                                         } catch (IOException e) {
545                                                 LOG.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while Reading the Policy File" + pathObj.toString() + e.getMessage());
546                                                 createdByModifiedBy = Arrays.asList("", "");
547                                         }
548                                         el.put("createdBy", getUserName(createdByModifiedBy.get(0)));
549                                         el.put("modifiedBy", getUserName(createdByModifiedBy.get(1)));
550                                 }               
551                                 el.put("date", dt.format(new Date(attrs.lastModifiedTime().toMillis())));
552                                 el.put("size", attrs.size());
553                                 el.put("type", attrs.isDirectory() ? "dir" : "file");
554                         }
555                 }
556
557                 if(!el.keySet().isEmpty()){
558                         resultList.add(el);
559                 }
560
561         }
562         
563         //Get the User Name based on ID from User Info table
564         public String getUserName(String userId) { 
565                 String userName = "super-admin";
566                 if("".equals(userId)){
567                         return userName;
568                 }
569                 try{
570                         return PolicyController.getUserName(userId);
571                 }catch(Exception e){
572                         LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Retriving User Name from User Info table"+e);
573                         return userName;
574                 }
575         }
576
577         //Rename Policy
578         private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
579                 try {
580                         String userId = null;
581                         try {
582                                 userId = UserUtils.getUserIdFromCookie(request);
583                         } catch (Exception e) {
584                                 LOG.error("Exception Occured while reading userid from cookie" +e);
585                         }
586                         String path = params.getString("path");
587                         String newpath = params.getString("newPath");
588                         LOG.debug("rename from: {} to: {}" +path + newpath);
589
590                         File srcFile = new File(REPOSITORY_BASE_PATH, path);
591                         File destFile = new File(REPOSITORY_BASE_PATH, newpath);
592                         if (srcFile.isFile()) {
593                                 renameXMLandConfig(destFile.getPath().toString(), srcFile.getPath().toString(), userId);
594                         } else {
595                                 FileUtils.moveDirectory(srcFile, destFile);
596                                 String oldScopeName = path.substring(1).replace("/", File.separator);   
597                                 String newScopeName = newpath.substring(1).replace("/", File.separator);
598                                 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +oldScopeName.replace("\\", "\\\\\\\\")+"%'";
599                                 UserInfo userInfo = new UserInfo();
600                                 userInfo.setUserLoginId(userId);
601                                 List<PolicyEditorScopes> scopesList = PolicyController.getListOfPolicyEditorScopes(scopeNamequery);
602                                 for(PolicyEditorScopes scopes : scopesList){
603                                         String scope = scopes.getScopeName();
604                                         String newScope = scope.replace(oldScopeName, newScopeName);
605                                         scopes.setScopeName(newScope);
606                                         scopes.setUserModifiedBy(userInfo);
607                                         PolicyController.updatePolicyScopeEditor(scopes);
608                                 }
609                                 File[] list = destFile.listFiles();
610                                 if(list.length > 0){
611                                         renameXMLandConfig(destFile.getPath().toString(), srcFile.getPath().toString(), userId);
612                                 }       
613                         }
614                         return success();
615                 } catch (Exception e) {
616                         LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
617                         return error(e.getMessage());
618                 }
619         }
620
621         //rename the xml and config files when renaming scope
622         public void renameXMLandConfig(String newPath, String oldPath, String loginId){
623                 if(!newPath.endsWith(".xml")){
624                         File dir = new File(newPath);
625                         File[] listOfFiles = dir.listFiles();
626                         for(File file : listOfFiles){
627                                 if(file.toString().endsWith(".xml")){
628                                         renameFile(file, oldPath, newPath );
629                                 }else if(file.isDirectory()){
630                                         String oldFilePath = oldPath + File.separator +file.getName();
631                                         renameXMLandConfig(file.toString(), oldFilePath, loginId);
632                                 }
633                         }
634                 }else{
635                         Path parent = Paths.get(oldPath.toString().substring(0, oldPath.toString().lastIndexOf(File.separator)));
636                         String policyName = oldPath.toString().substring(oldPath.toString().indexOf(REPOSITORY) +11);
637                         String removeExtension = policyName.replace(".xml", "");
638                         String dbPolicyName = removeExtension.substring(0, removeExtension.lastIndexOf("."));
639                         //Policy Notifcation
640                         PolicyController controller = new PolicyController();
641                         PolicyVersion entity = new PolicyVersion();
642                         entity.setPolicyName(dbPolicyName);
643                         entity.setModifiedBy(loginId);
644                         controller.WatchPolicyFunction(entity, dbPolicyName, "Rename");
645                         String filterPolicyName = dbPolicyName.substring(dbPolicyName.lastIndexOf(File.separator)+1);
646                         FileFilter fileFilter = new WildcardFileFilter(filterPolicyName + "." + "*" + ".xml");
647                         File[] files = parent.toFile().listFiles(fileFilter);
648                         for(File file : files){
649                                 String removeNewPathExtension = newPath.replace(".xml", "");
650                                 String removeNewFileVersion = removeNewPathExtension.substring(0, removeNewPathExtension.lastIndexOf("."));
651                                 String oldFile = file.getPath();
652                                 oldFile = oldFile.replace(".xml", "");
653                                 String version = oldFile.substring(oldFile.lastIndexOf(".")+1);
654                                 String finalPath = removeNewFileVersion + "." + version + ".xml";
655                                 File destFile = new File(finalPath);
656                                 try {
657                                         FileUtils.moveFile(file, destFile);
658                                         renameFile(file, oldFile, finalPath);   
659                                 } catch (IOException e) {
660                                         LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Renaming or Moving Policy"+e);
661                                 }
662                                 
663                         }               
664                 }
665         }
666
667         //Rename File
668         private void renameFile(File file, String oldPath, String newPath){
669                 if(file.toString().contains(CONFIG) || file.toString().contains(ACTION) || file.toString().contains(DECISION)){
670                         File xmlFileName = new File(newPath);
671                         String oldfileWithExtension = null;
672                         String filelocation = null;
673                         String oldfile = null;
674                         String newfile = null;
675                         String extension = null;
676                         if(newPath.endsWith(".xml")){
677                                 extension = XACMLPolicyWriterWithPapNotify.changeFileNameInXmlWhenRenamePolicy(xmlFileName.toPath());
678                         }else{
679                                 extension = XACMLPolicyWriterWithPapNotify.changeFileNameInXmlWhenRenamePolicy(file.toPath());
680                                 String fileName = file.getName();
681                                 oldPath = oldPath + File.separator + fileName;
682                                 newPath = newPath + File.separator + fileName;
683                         }
684                         
685                         try{
686                                 if(file.toString().contains(CONFIG)){
687                                         filelocation = PolicyController.getConfigHome();
688                                 }
689                                 if(file.toString().contains(ACTION)){
690                                         filelocation = PolicyController.getActionHome();
691                                 }
692                                 File  oldFilePath = new File(oldPath);
693                                 String oldFileName = oldFilePath.getName().replace(".xml", "");
694                                 File  newFilePath = new File(newPath);
695                                 String newFileName = newFilePath.getName().replace(".xml", "");
696                                 File target = new File(oldPath);
697                                 File newParentScope = new File(newPath);
698                                 if(newParentScope.toString().endsWith(".xml")){
699                                         String newScope = newParentScope.toString().substring(0, newParentScope.toString().lastIndexOf(File.separator));
700                                         newParentScope = new File(newScope);
701                                 }
702                                 String oldParentScope = target.toString().substring(0, target.toString().lastIndexOf(File.separator));
703                                 String oldDomain = oldParentScope.toString().substring(oldParentScope.toString().indexOf(REPOSITORY) + 11);
704                                 if(oldDomain.endsWith(".xml")){
705                                         oldDomain = oldDomain.substring(0, oldDomain.lastIndexOf(File.separator));
706                                 }
707                                 oldfile = oldDomain + File.separator + oldFileName.substring(0, oldFileName.indexOf("."));
708                                 if(oldDomain.contains(File.separator)){
709                                         oldDomain = oldDomain.replace(File.separator, ".");
710                                 }
711                                 String newDomain = newParentScope.toString().substring(newParentScope.toString().indexOf(REPOSITORY) + 11);
712                                 newfile = newDomain + File.separator +newFileName.substring(0, newFileName.indexOf("."));
713                                 if(newDomain.contains(File.separator)){
714                                         newDomain = newDomain.replace(File.separator, ".");
715                                 }
716                                 if(file.toString().contains(CONFIG) || file.toString().contains(ACTION)){
717                                         oldfileWithExtension = oldDomain + "." + oldFileName + "."+ extension;
718                                         String newfilewithExtension = newDomain + "." + newFileName + "." + extension;
719                                         File file1 = new File(filelocation, oldfileWithExtension);
720                                         file1.renameTo(new File(filelocation , newfilewithExtension));
721                                 }               
722                                 String query = "update PolicyVersion set policy_name='"+newfile.replace("\\", "\\\\")+"' where policy_name ='" +oldfile.replace("\\", "\\\\")+"'  and id >0";
723                                 //query the database
724                                 PolicyController.updatePolicyVersion(query);
725                         }catch(Exception e){
726                                 LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE +"Config file cannot found:" + oldfileWithExtension + e);
727                         }
728                 }
729         }
730
731         //Clone the Policy
732         private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
733                 try {
734                         String path = params.getString("path");
735                         String newpath = params.getString("newPath");
736                         LOG.debug("copy from: {} to: {}" + path +newpath);
737                         File srcFile = new File(REPOSITORY_BASE_PATH, path);
738                         File destFile = new File(REPOSITORY_BASE_PATH, newpath);
739                         if (srcFile.isFile()) {
740                                 FileUtils.copyFile(srcFile, destFile);
741                                 cloneXMLandConfig(destFile, srcFile, request);
742                         } else {
743                                 FileUtils.copyDirectory(srcFile, destFile);
744                         }
745                         return success();
746                 } catch (Exception e) {
747                         LOG.error("copy", e);
748                         return error(e.getMessage());
749                 }
750         }
751
752         public void cloneXMLandConfig(File newPath, File oldPath, HttpServletRequest request){
753                 String userId = null;
754                 try {
755                         userId = UserUtils.getUserIdFromCookie(request);
756                 } catch (Exception e) {
757                         LOG.error("Exception Occured while reading userid from cookie" +e);
758                 }
759                 String newPolicyName = newPath.getPath().toString().substring(newPath.getPath().toString().indexOf(REPOSITORY) + 11);
760                 newPolicyName = newPolicyName.replace(".xml", "");
761                 String version = newPolicyName.substring(newPolicyName.lastIndexOf(".") +1);
762                 String policyName = newPolicyName.substring(0, newPolicyName.indexOf("."));
763                 newPolicyName = newPolicyName.replace(File.separator, ".");
764                 //if the user leaves the name of the policy blank
765                 if (newPolicyName == null) {
766                         return;
767                 }else{
768                         Path newPolicyPath = newPath.toPath();
769                         File dir = null;
770                         File[] listOfFiles = null;
771                         if(newPolicyName.contains(CONFIG)){
772                                 LOG.debug("CONFIG_HOME: "+CONFIG_HOME);
773                                 dir=new File(CONFIG_HOME); 
774                                 listOfFiles = dir.listFiles();
775                         }else if(newPolicyName.contains(ACTION)){
776                                 LOG.debug("ACTION_HOME: "+ACTION_HOME);
777                                 dir=new File(ACTION_HOME); 
778                                 listOfFiles = dir.listFiles();
779                         }
780                         String indexValue = "";
781                         String orignalPolicyName = oldPath.getPath().toString().substring(oldPath.getPath().toString().indexOf(REPOSITORY) + 11);
782                         orignalPolicyName = orignalPolicyName.replace(".xml", "");
783                         orignalPolicyName = orignalPolicyName.replace(File.separator, ".");
784                         if(orignalPolicyName.contains("Config_Fault_")){
785                                 indexValue = "Config_Fault_";
786                         } else if(orignalPolicyName.contains("Config_PM_")){
787                                 indexValue = "Config_PM_";
788                         }else if(orignalPolicyName.contains("Config_FW")){
789                                 indexValue = "Config_FW_";
790                         }else if(orignalPolicyName.contains("Config_BRMS_Param")){
791                                 indexValue = "Config_BRMS_Param_";
792                         }else if(orignalPolicyName.contains("Config_BRMS_Raw")){
793                                 indexValue = "Config_BRMS_Raw_";
794                         } else if(orignalPolicyName.contains("Config_MS")){
795                                 indexValue = "Config_MS_";
796                         }else if(orignalPolicyName.contains(ACTION)){
797                                 indexValue = ACTION;
798                         }else if(orignalPolicyName.contains(DECISION)){
799                                 indexValue = DECISION;
800                         }else{
801                                 indexValue = CONFIG;
802                         }
803                         File newConfigFile = null;
804                         
805                         //making changes to the xml file
806                         if(indexValue.contains(CONFIG) || indexValue.contains(ACTION)){
807                                 for (File file : listOfFiles) {
808                                         if (file.isFile()){
809                                                 String fileName=file.getName();
810                                                 if(fileName.contains(orignalPolicyName)){
811                                                         String newConfigFileName=fileName.replaceAll(orignalPolicyName,newPolicyName);
812                                                         if(dir.toString().contains(File.separator)){
813                                                                 newConfigFile=new File(dir.toString()+ File.separator +newConfigFileName);
814                                                         }
815                                                         try {
816                                                                 Files.copy(file.toPath(), newConfigFile.toPath());
817                                                         } catch (Exception e) {
818                                                                 LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE +"Error while Cloning the config file" + e);
819                                                                 return;
820                                                         }
821                                                 }
822                                         }
823                                 }
824                                 XACMLPolicyWriterWithPapNotify.changeFileNameInXmlWhenRenamePolicy(newPolicyPath);
825                         }
826                         //set the clone policy name into policy version database table
827                         PolicyVersion entityItem = new PolicyVersion();
828                         entityItem.setActiveVersion(Integer.parseInt(version));
829                         entityItem.setHigherVersion(Integer.parseInt(version));
830                         entityItem.setPolicyName(policyName);
831                         entityItem.setCreatedBy(userId);
832                         entityItem.setModifiedBy(userId);
833                         PolicyController.SaveToPolicyVersion(entityItem);
834
835
836                         new Thread(new Runnable() {
837                                 @Override
838                                 public void run() {
839                                         try {
840                                                 ElkConnector.singleton.update(newPolicyPath.toFile());                                                  
841                                                 if (LOG.isInfoEnabled()) {
842                                                         LOG.info("ELK cloning to " +  newPolicyPath);
843                                                 }
844                                         } catch (Exception e) {
845                                                 LOG.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": Internal Error: Unsucessful clone: " + e.getMessage(), e);
846                                         }
847                                 }
848                         }).start();
849
850                         //send to pap
851                         XACMLPolicyWriterWithPapNotify.notifyPapOfCreateUpdate(newPolicyPath.toAbsolutePath().toString());      
852                         LOG.info("Cloned policy "+newPolicyName+" created successfully.");                                              
853                         return;
854                 }
855         }
856
857         //Delete Policy or Scope Functionality
858         private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
859                 try {
860                         String userId = UserUtils.getUserIdFromCookie(request);
861                         String deleteVersion = "";
862                         String path1 = params.getString("path");
863                         LOG.debug("delete {}" +path1);
864                         if(params.has("deleteVersion")){
865                                 deleteVersion  = params.getString("deleteVersion");
866                         }
867                 
868                         this.repofilePath  = new File(REPOSITORY_BASE_PATH, path1);
869                         File policyFile = new File(REPOSITORY_BASE_PATH, path1);
870                         if("ALL".equals(deleteVersion)){
871                                 String removexmlExtension = policyFile.toString().substring(0, policyFile.toString().lastIndexOf("."));
872                                 String removeVersion = removexmlExtension.substring(0, removexmlExtension.lastIndexOf("."));
873                                 String notificationName = removeVersion.substring(removeVersion.lastIndexOf(REPOSITORY)+11);
874                                 //Policy Notifcation
875                                 PolicyController controller = new PolicyController();
876                                 PolicyVersion entity = new PolicyVersion();
877                                 entity.setPolicyName(notificationName);
878                                 entity.setModifiedBy(userId);
879                                 controller.WatchPolicyFunction(entity, notificationName, "DeleteAll");
880                                 File dirXML = new File(policyFile.getParent());
881                                 File[] listOfXMLFiles = dirXML.listFiles();
882                                 for (File file : listOfXMLFiles) {
883                                         //delete the xml files from Repository
884                                         if (file.isFile() && file.toString().contains(removeVersion)) { 
885                                                 if(XACMLPolicyWriterWithPapNotify.notifyPapOfDelete(file.toString())){
886                                                         LOG.info("Policy deleted from database. Continuing with file delete");
887                                                 } else {
888                                                         LOG.error("Failed to delete Policy from database. Aborting file delete");
889                                                 }
890                                                 //Elk Update
891                                                 updateElkOnPolicyDelete(file);
892
893                                                 if (file.delete()) {
894                                                         if (LOG.isDebugEnabled()) {
895                                                                 LOG.debug("Deleted file: " + file.toString());
896                                                         }
897                                                 } else {
898                                                         LOG.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot delete the policy file in specified location: " + file.getAbsolutePath());                                              
899                                                 }
900
901                                                 // Get tomcat home directory for deleting config data
902                                                 String path = getParentPathSubScopeDir();
903                                                 path = path.replace('\\', '.');
904                                                 if(path.contains("/")){
905                                                         path = path.replace('/', '.');
906                                                 }
907                                                 String fileName = FilenameUtils.removeExtension(file.getName());
908                                                 String removeVersionInFileName = fileName.substring(0, fileName.lastIndexOf("."));
909                                                 String fileLocation = null;
910                                                 if (fileName != null && fileName.contains(CONFIG)) {
911                                                         fileLocation = CONFIG_HOME;
912                                                 } else if (fileName != null && fileName.contains(ACTION)) {
913                                                         fileLocation = ACTION_HOME;
914                                                 }
915                                                 if (LOG.isDebugEnabled()) {
916                                                         LOG.debug("Attempting to rename file from the location: "+ fileLocation);
917                                                 }
918                                                 if(!file.toString().contains(DECISION)){
919                                                         // Get the file from the saved location
920                                                         File dir = new File(fileLocation);
921                                                         File[] listOfFiles = dir.listFiles();
922
923                                                         for (File file1 : listOfFiles) {
924                                                                 if (file1.isFile() && file1.getName().contains( path + removeVersionInFileName)) {
925                                                                         try {
926                                                                                 if (file1.delete() == false) {
927                                                                                         throw new Exception("No known error, Delete failed");
928                                                                                 }
929                                                                         } catch (Exception e) {
930                                                                                 LOG.error("Failed to Delete file: "+ e.getLocalizedMessage());
931                                                                         }
932                                                                 }
933                                                         }
934                                                 }
935
936                                                 //Delete the Policy from Database Policy Version table
937                                                 String removeExtension = removeVersion.substring(removeVersion.indexOf(REPOSITORY)+11);
938                                                 String policyVersionQuery = "delete from PolicyVersion  where policy_name ='" +removeExtension.replace("\\", "\\\\")+"' and id >0";
939                                                 if(policyVersionQuery != null){
940                                                         PolicyController.updatePolicyVersion(policyVersionQuery);
941                                                 }
942                                         }
943                                 }
944                                 //If Only Particular version to be deleted 
945                         }else if("CURRENT".equals(deleteVersion)){
946                                 String removexmlExtension = policyFile.toString().substring(0, policyFile.toString().lastIndexOf("."));
947                                 String getVersion = removexmlExtension.substring(removexmlExtension.indexOf(".")+1);
948                                 String removeVersion = removexmlExtension.substring(0, removexmlExtension.lastIndexOf("."));
949                                 String notificationName = removeVersion.substring(removeVersion.lastIndexOf(REPOSITORY)+11);
950                                 //Policy Notifcation
951                                 PolicyController controller = new PolicyController();
952                                 PolicyVersion entity = new PolicyVersion();
953                                 entity.setPolicyName(notificationName);
954                                 entity.setActiveVersion(Integer.parseInt(getVersion));
955                                 entity.setModifiedBy(userId);
956                                 controller.WatchPolicyFunction(entity, notificationName, "DeleteOne");
957                                 if(XACMLPolicyWriterWithPapNotify.notifyPapOfDelete(policyFile.toString())){
958                                         LOG.info("Policy deleted from database. Continuing with file delete");
959                                 } else {
960                                         LOG.error("Failed to delete Policy from database. Aborting file delete");
961                                 }
962                                 //Elk Update
963                                 updateElkOnPolicyDelete(policyFile);
964
965                                 if (policyFile.delete()) {
966                                         LOG.debug("Deleted file: " + policyFile.toString());
967                                 } else {
968                                         LOG.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot delete the policy file in specified location: " +policyFile.getAbsolutePath());                                         
969                                 }
970
971                                 // Get tomcat home directory for storing action body config data
972                                 String path = getParentPathSubScopeDir();
973                                 path = path.replace('\\', '.');
974                                 if(path.contains("/")){
975                                         path = path.replace('/', '.');
976                                         LOG.info("print the path:" +path);
977                                 }
978                                 final String tempPath = path;
979                                 String fileName = FilenameUtils.removeExtension(policyFile.getName());
980                                 String fileLocation = null;
981                                 if (fileName != null && fileName.contains(CONFIG)) {
982                                         fileLocation = CONFIG_HOME;
983                                 } else if (fileName != null && fileName.contains(ACTION)) {
984                                         fileLocation = ACTION_HOME;
985                                 }
986                                 if (LOG.isDebugEnabled()) {
987                                         LOG.debug("Attempting to delete file from the location: "+ fileLocation);
988                                 }
989                                 if(!policyFile.toString().contains(DECISION)){
990                                         // Get the file from the saved location
991                                         File dir = new File(fileLocation);
992                                         File[] listOfFiles = dir.listFiles();
993
994                                         for (File file : listOfFiles) {
995                                                 if (file.isFile() && file.toString().contains( tempPath + fileName)) {
996                                                         try {
997                                                                 if (file.delete() == false) {
998                                                                         throw new Exception("No known error, Delete failed");
999                                                                 }
1000                                                         } catch (Exception e) {
1001                                                                 LOG.error("Failed to Delete file: "+ e.getLocalizedMessage());
1002                                                         }
1003                                                 }
1004                                         }
1005                                 }
1006                                 //Delete the Policy from Database and set Active Version based on the deleted file.
1007                                 int highestVersion = 0;
1008                                 String removeExtension = removeVersion.substring(removeVersion.indexOf(REPOSITORY)+11);
1009                                 PolicyVersion policyVersionEntity = PolicyController.getPolicyEntityFromPolicyVersion(removeExtension);
1010                                 if(policyVersionEntity != null){
1011                                         highestVersion = policyVersionEntity.getHigherVersion();
1012                                 }       
1013                                 int i =0;
1014                                 int version = Integer.parseInt(getVersion);
1015                                 if(version == highestVersion){
1016                                         for(i = highestVersion; i >= 1 ; i--){
1017                                                 highestVersion = highestVersion-1;
1018                                                 path = removeVersion + "."+ highestVersion  +".xml";
1019                                                 File file = new File(path);
1020                                                 if(file.exists()){
1021                                                         break;
1022                                                 }
1023                                         }
1024                                 }
1025                                 String updatequery = "update PolicyVersion set active_version='"+highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +removeExtension.replace("\\", "\\\\")+"'";
1026                                 PolicyController.updatePolicyVersion(updatequery);
1027                         }else{
1028                                 String scopeName = policyFile.getAbsolutePath().substring(policyFile.getAbsolutePath().indexOf(REPOSITORY)+11);
1029                                 String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+scopeName.replace("\\", "\\\\")+"%' and id >0";
1030                                 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+scopeName.replace("\\", "\\\\")+"%' and id >0";
1031                                 PolicyController.updatePolicyVersion(policyVersionQuery);
1032                                 PolicyController.updatePolicyScopeEditorWithQuery(policyScopeQuery);
1033                                 delete(policyFile);
1034                                 //Policy Notifcation
1035                                 PolicyController controller = new PolicyController();
1036                                 PolicyVersion entity = new PolicyVersion();
1037                                 entity.setPolicyName(scopeName);
1038                                 entity.setModifiedBy(userId);
1039                                 controller.WatchPolicyFunction(entity, scopeName, "DeleteScope");
1040                         }
1041                         return success();
1042                 } catch (Exception e) {
1043                         LOG.error("delete", e);
1044                         return error(e.getMessage());
1045                 }
1046         }
1047         
1048         //Notify ELK on File Delete
1049         private void updateElkOnPolicyDelete(File file){
1050                 try {
1051                         ElkConnector.singleton.delete(file);
1052                 } catch (Exception e) {
1053                         LOG.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": Cannot delete: " + file.getName() +
1054                                         " at " + file.getAbsolutePath() + ": " + e.getMessage(), e);
1055                 }
1056         }
1057         //Deletes Files when Scope is Selected to delete
1058         public  void delete(File file) throws IOException{
1059                 if(file.isDirectory()){
1060                         //directory is empty, then delete it
1061                         if(file.list().length==0){      
1062                                 file.delete();
1063                         }else{
1064                                 //list all the directory contents
1065                                 String[] files = file.list();
1066                                 for (String temp : files) {
1067                                         //construct the file structure
1068                                         File fileDelete = new File(file, temp);
1069                                         //delete from Elk first
1070                                         if(fileDelete.getAbsolutePath().toString().endsWith(".xml")){
1071                                                 try {
1072                                                         String deleteFile= fileDelete.getAbsoluteFile().toString().substring(fileDelete.getAbsoluteFile().toString().indexOf("workspace"));
1073                                                         File deletePath= new File(deleteFile);
1074                                                         LOG.debug("Search:"+deletePath);
1075                                                         ElkConnector.singleton.delete(deletePath);
1076                                                 } catch (Exception e) {
1077                                                         LOG.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": Cannot delete: " + fileDelete.getAbsoluteFile().getName() +
1078                                                                         " at " + fileDelete.getAbsoluteFile().getAbsolutePath() + ": " +e.getMessage(), e);
1079                                                 }
1080                                         }
1081
1082                                         //recursive delete
1083                                         delete(fileDelete);
1084
1085                                         //Delete the Configuration files from Config and Action Home Location
1086                                         String fileLocation = null;
1087                                         String policyName = fileDelete.toString().substring(fileDelete.toString().indexOf(REPOSITORY)+11, fileDelete.toString().lastIndexOf("."));
1088                                         if(policyName.contains(CONFIG)){
1089                                                 fileLocation = PolicyController.getConfigHome();
1090                                         }
1091                                         if(policyName.contains(ACTION)){
1092                                                 fileLocation = PolicyController.getActionHome();
1093                                         }
1094                                         if(policyName.contains(File.separator)){
1095                                                 policyName = policyName.replace(File.separator, ".");
1096                                         }
1097                                         if(!fileDelete.toString().contains(DECISION) && fileLocation != null){
1098                                                 // Get the file from the saved location and delete
1099                                                 File dir = new File(fileLocation);
1100                                                 FileFilter fileFilter = new WildcardFileFilter(policyName + ".*");
1101                                                 File[] configFiles = (dir).listFiles(fileFilter);
1102                                                 if(configFiles.length > 0){
1103                                                         configFiles[0].delete();
1104                                                 }
1105                                         }
1106                                         //Notify the PAP and Elk database for deleting the Policies Under Scopes
1107                                         if(fileDelete.getAbsolutePath().toString().endsWith(".xml")){
1108                                                 if(!XACMLPolicyWriterWithPapNotify.notifyPapOfDelete(fileDelete.getAbsolutePath().toString())){
1109                                                         LOG.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Could not delete the policy from the database: "+
1110                                                                         fileDelete.getAbsolutePath().toString());
1111                                                         throw new IOException("Could not delete the policy from the database: "+
1112                                                                         fileDelete.getAbsolutePath().toString());
1113                                                 }
1114                                         } 
1115                                 }    
1116                                 //check the directory again, if empty then delete it
1117                                 if(file.list().length==0){
1118                                         file.delete();
1119                                 }
1120                         }       
1121                 }else{
1122                         //if file, then delete it
1123                         file.delete();
1124                 }
1125         }
1126
1127         //Get the Parent Scope of File
1128         protected String getParentPathSubScopeDir() {
1129                 String domain1 = null;
1130                 final Path gitPath = PolicyController.getGitPath();
1131                 String policyDir = this.repofilePath.getAbsolutePath();
1132                 int startIndex = policyDir.indexOf(gitPath.toString()) + gitPath.toString().length() + 1;
1133                 policyDir = policyDir.substring(startIndex, policyDir.length());
1134                 if(policyDir.contains(CONFIG)){
1135                         domain1 = policyDir.substring(0,policyDir.indexOf(CONFIG));
1136                 }else if(policyDir.contains(ACTION)){
1137                         domain1 = policyDir.substring(0,policyDir.indexOf(ACTION));     
1138                 }else{
1139                         domain1 = policyDir.substring(0,policyDir.indexOf(DECISION));   
1140                 }
1141                 LOG.info("print the main domain value"+policyDir);              
1142                 return domain1;
1143         }
1144
1145         //Edit the Policy
1146         private JSONObject editFile(JSONObject params) throws ServletException {
1147                 // get content
1148                 try {
1149                         String mode = params.getString("mode");
1150                         String path = params.getString("path");
1151                         LOG.debug("editFile path: {}"+ path);
1152
1153                         File policyFile = new File(REPOSITORY_BASE_PATH, path);
1154
1155                         Object policy = XACMLPolicyScanner.readPolicy(new FileInputStream(policyFile));
1156                         Path fullPath = Paths.get(policyFile.getAbsolutePath(), new String[0]);
1157                         PolicyAdapter policyAdapter  = new PolicyAdapter();             
1158                         policyAdapter.setData(policy);
1159                         String dirPath = fullPath.getParent().toString().substring(fullPath.getParent().toString().lastIndexOf(REPOSITORY)+11);
1160                         policyAdapter.setDirPath(dirPath);
1161                         policyAdapter.setParentPath(fullPath.getParent());
1162
1163                         if("viewPolicy".equalsIgnoreCase(mode)){
1164                                 policyAdapter.setReadOnly(true);
1165                                 policyAdapter.setEditPolicy(false);
1166                         }else{
1167                                 policyAdapter.setReadOnly(false);
1168                                 policyAdapter.setEditPolicy(true);
1169                         }
1170
1171                         policyAdapter.setPolicyData(policy);
1172                         policyAdapter.setPolicyName(FilenameUtils.removeExtension(policyFile.getName()));
1173
1174                         String  policyNameValue = null ;
1175                         String  configPolicyName = null ;
1176                         if(policyAdapter.getPolicyName().startsWith("Config_PM")){
1177                                 policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_"));
1178                                 configPolicyName = "ClosedLoop_PM";
1179                         }else if(policyAdapter.getPolicyName().startsWith("Config_Fault")){
1180                                 policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_"));
1181                                 configPolicyName = "ClosedLoop_Fault";
1182                         }else if(policyAdapter.getPolicyName().startsWith("Config_FW")){
1183                                 policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_"));
1184                                 configPolicyName = "Firewall Config";
1185                         }else if(policyAdapter.getPolicyName().startsWith("Config_BRMS_Raw")){
1186                                 policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_"));
1187                                 configPolicyName = "BRMS_Raw";
1188                         }else if(policyAdapter.getPolicyName().startsWith("Config_BRMS_Param")){
1189                                 policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_"));
1190                                 configPolicyName = "BRMS_Param";
1191                         }else if(policyAdapter.getPolicyName().startsWith("Config_MS")){
1192                                 policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_"));
1193                                 configPolicyName = "DCAE Micro Service";
1194                         }else if(policyAdapter.getPolicyName().startsWith("Action") || policyAdapter.getPolicyName().startsWith("Decision") ){
1195                                 policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_"));
1196                         }
1197                         else{
1198                                 policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_"));
1199                                 configPolicyName = "Base";
1200                         }
1201                         if (policyNameValue != null) {
1202                                 policyAdapter.setPolicyType(policyNameValue);
1203                         }
1204                         if (configPolicyName != null) {
1205                                 policyAdapter.setConfigPolicyType(configPolicyName);
1206                         }
1207
1208                         if("Action".equalsIgnoreCase(policyAdapter.getPolicyType())){
1209                                 ActionPolicyController actionController = new ActionPolicyController();
1210                                 actionController.PrePopulateActionPolicyData(policyAdapter);
1211                         }
1212                         if("Decision".equalsIgnoreCase(policyAdapter.getPolicyType())){
1213                                 DecisionPolicyController decisionController = new DecisionPolicyController();
1214                                 decisionController.PrePopulateDecisionPolicyData(policyAdapter);
1215                         }
1216                         if("Config".equalsIgnoreCase(policyAdapter.getPolicyType())){
1217                                 if("Base".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){
1218                                         CreatePolicyController baseController = new CreatePolicyController();
1219                                         baseController.PrePopulateBaseConfigPolicyData(policyAdapter);
1220                                 }
1221                                 else if("BRMS_Raw".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){
1222                                         CreateBRMSRawController brmsController = new CreateBRMSRawController();
1223                                         brmsController.PrePopulateBRMSRawPolicyData(policyAdapter);
1224                                 }
1225                                 else if("BRMS_Param".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){
1226                                         CreateBRMSParamController paramController = new CreateBRMSParamController();
1227                                         paramController.PrePopulateBRMSParamPolicyData(policyAdapter);
1228                                 }
1229                                 else if("ClosedLoop_Fault".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){
1230                                         CreateClosedLoopFaultController newFaultTemplate =  new CreateClosedLoopFaultController();
1231                                         newFaultTemplate.PrePopulateClosedLoopFaultPolicyData(policyAdapter);
1232                                 }
1233                                 else if("ClosedLoop_PM".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){
1234                                         CreateClosedLoopPMController pmController = new CreateClosedLoopPMController();
1235                                         pmController.PrePopulateClosedLoopPMPolicyData(policyAdapter);
1236                                 }
1237                                 else if("DCAE Micro Service".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){
1238                                         CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController();
1239                                         msController.PrePopulateDCAEMSPolicyData(policyAdapter);
1240                                 }
1241                                 else if("Firewall Config".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){
1242                                         CreateFirewallController firewallController = new CreateFirewallController();
1243                                         firewallController.PrePopulateFWPolicyData(policyAdapter);
1244                                 }       
1245                         }
1246
1247
1248                         policyAdapter.setParentPath(null);
1249                         ObjectMapper mapper = new ObjectMapper();
1250                         String json = mapper.writeValueAsString(policyAdapter);
1251                         JsonNode jsonNode = mapper.readTree(json);
1252
1253                         return new JSONObject().put(RESULT, jsonNode);
1254                 } catch (Exception e) {
1255                         LOG.error("editFile", e);
1256                         return error(e.getMessage());
1257                 }
1258         }
1259
1260         //Add Scopes
1261         private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
1262                 String name = "";
1263                 
1264                 try {
1265                         String userId = UserUtils.getUserIdFromCookie(request);
1266                         String path = params.getString("path");
1267                         try{
1268                                 if(params.has("subScopename")){
1269                                         if(!params.getString("subScopename").equals("")){
1270                                                  name = params.getString("path").replace("/", File.separator) + File.separator +params.getString("subScopename");
1271                                         }
1272                                 }else{
1273                                          name = params.getString("name");
1274                                 }       
1275                         }catch(Exception e){
1276                                 name = params.getString("name");
1277                                 LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e);
1278                         }
1279                         
1280                         
1281                         LOG.debug("addFolder path: {} name: {}" + path +name);
1282                         File newDir = new File(REPOSITORY_BASE_PATH, name);
1283                         if(!newDir.exists()){
1284                                 if (!newDir.mkdir()) {
1285                                         throw new Exception("Can't create directory: " + newDir.getAbsolutePath());
1286                                 }
1287                                 UserInfo userInfo = new UserInfo();
1288                                 userInfo.setUserLoginId(userId);
1289                                 PolicyEditorScopes newScope = new PolicyEditorScopes();
1290                                 String scopeName = null;
1291                                 if(name.startsWith(File.separator)){
1292                                         scopeName = name.substring(1);
1293                                 }else{
1294                                         scopeName = name;
1295                                 } 
1296                                 newScope.setScopeName(scopeName);
1297                                 newScope.setUserCreatedBy(userInfo);
1298                                 newScope.setUserModifiedBy(userInfo);
1299                                 PolicyController.SavePolicyScope(newScope);     
1300                         }else{
1301                                 return error("Scope Already Exists");
1302                         }
1303                         
1304                         return success();
1305                 } catch (Exception e) {
1306                         LOG.error("addFolder", e);
1307                         return error(e.getMessage());
1308                 }
1309         }
1310
1311         //Return Error Object
1312         private JSONObject error(String msg) throws ServletException {
1313                 try {
1314                         JSONObject result = new JSONObject();
1315                         result.put("success", false);
1316                         result.put("error", msg);
1317                         return new JSONObject().put(RESULT, result);
1318                 } catch (JSONException e) {
1319                         throw new ServletException(e);
1320                 }
1321         }
1322     
1323         //Return Success Object
1324         private JSONObject success() throws ServletException {
1325                 try {
1326                         JSONObject result = new JSONObject();
1327                         result.put("success", true);
1328                         result.put("error", (Object) null);
1329                         return new JSONObject().put(RESULT, result);
1330                 } catch (JSONException e) {
1331                         throw new ServletException(e);
1332                 }
1333         }
1334 }