Merge "Decision BlackList Guard Enhancements"
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / admin / PolicyManagerServlet.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.admin;
23
24 import java.io.BufferedReader;
25 import java.io.BufferedWriter;
26 import java.io.ByteArrayInputStream;
27 import java.io.File;
28 import java.io.FileInputStream;
29 import java.io.FileOutputStream;
30 import java.io.FileWriter;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.io.OutputStream;
34 import java.io.PrintWriter;
35 import java.nio.charset.StandardCharsets;
36 import java.nio.file.Files;
37 import java.nio.file.Path;
38 import java.nio.file.Paths;
39 import java.util.ArrayList;
40 import java.util.Date;
41 import java.util.HashMap;
42 import java.util.HashSet;
43 import java.util.List;
44 import java.util.Map;
45 import java.util.Set;
46
47 import javax.json.Json;
48 import javax.json.JsonArray;
49 import javax.json.JsonReader;
50 import javax.script.SimpleBindings;
51 import javax.servlet.ServletConfig;
52 import javax.servlet.ServletException;
53 import javax.servlet.annotation.WebInitParam;
54 import javax.servlet.annotation.WebServlet;
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.http.HttpStatus;
64 import org.json.JSONArray;
65 import org.json.JSONException;
66 import org.json.JSONObject;
67 import org.onap.policy.common.logging.flexlogger.FlexLogger;
68 import org.onap.policy.common.logging.flexlogger.Logger;
69 import org.onap.policy.components.HumanPolicyComponent;
70 import org.onap.policy.controller.PolicyController;
71 import org.onap.policy.controller.PolicyExportAndImportController;
72 import org.onap.policy.rest.XACMLRest;
73 import org.onap.policy.rest.XACMLRestProperties;
74 import org.onap.policy.rest.adapter.PolicyRestAdapter;
75 import org.onap.policy.rest.jpa.ActionBodyEntity;
76 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
77 import org.onap.policy.rest.jpa.PolicyEditorScopes;
78 import org.onap.policy.rest.jpa.PolicyEntity;
79 import org.onap.policy.rest.jpa.PolicyVersion;
80 import org.onap.policy.rest.jpa.UserInfo;
81 import org.onap.policy.utils.PolicyUtils;
82 import org.onap.policy.utils.UserUtils.Pair;
83 import org.onap.policy.xacml.api.XACMLErrorConstants;
84 import org.onap.policy.xacml.util.XACMLPolicyScanner;
85 import org.onap.portalsdk.core.web.support.UserUtils;
86
87 import com.att.research.xacml.util.XACMLProperties;
88 import com.fasterxml.jackson.databind.JsonNode;
89 import com.fasterxml.jackson.databind.ObjectMapper;
90
91
92 @WebServlet(value ="/fm/*",  loadOnStartup = 1, initParams = { @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.admin.properties", description = "The location of the properties file holding configuration information.") })
93 public class PolicyManagerServlet extends HttpServlet {
94     private static final Logger LOGGER  = FlexLogger.getLogger(PolicyManagerServlet.class);
95     private static final long serialVersionUID = -8453502699403909016L;
96
97     private enum Mode {
98         LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT, SEARCHLIST
99     }
100
101     private static PolicyController policyController;
102     public synchronized PolicyController getPolicyController() {
103         return policyController;
104     }
105
106     public static synchronized void setPolicyController(PolicyController policyController) {
107         PolicyManagerServlet.policyController = policyController;
108     }
109
110     private static String CONTENTTYPE = "application/json";
111     private static String SUPERADMIN = "super-admin";
112     private static String SUPEREDITOR = "super-editor";
113     private static String SUPERGUEST = "super-guest";
114     private static String ADMIN = "admin";
115     private static String EDITOR = "editor";
116     private static String GUEST = "guest";
117     private static String RESULT = "result";
118
119     private static Path closedLoopJsonLocation;
120     private static JsonArray policyNames;
121     private static String testUserId = null;
122
123     public static JsonArray getPolicyNames() {
124         return policyNames;
125     }
126
127     public static void setPolicyNames(JsonArray policyNames) {
128         PolicyManagerServlet.policyNames = policyNames;
129     }
130
131     private static List<String> serviceTypeNamesList = new ArrayList<>();
132
133     public static List<String> getServiceTypeNamesList() {
134         return serviceTypeNamesList;
135     }
136
137     @Override
138     public void init(ServletConfig servletConfig) throws ServletException {
139         super.init(servletConfig);
140         //
141         // Common initialization
142         //
143         XACMLRest.xacmlInit(servletConfig);
144         //
145         //Initialize ClosedLoop JSON
146         //
147         PolicyManagerServlet.initializeJSONLoad();
148     }
149
150     protected static void initializeJSONLoad() {
151         closedLoopJsonLocation = Paths.get(XACMLProperties
152                 .getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP));
153         String location = closedLoopJsonLocation.toString();
154         if (! location.endsWith("json")) {
155             LOGGER.warn("JSONConfig file does not end with extension .json");
156             return;
157         }
158         try (FileInputStream inputStream = new FileInputStream(location);
159              JsonReader jsonReader = Json.createReader(inputStream)) {
160             policyNames = jsonReader.readArray();
161             serviceTypeNamesList = new ArrayList<>();
162             for (int i = 0; i < policyNames.size(); i++) {
163                 javax.json.JsonObject policyName = policyNames.getJsonObject(i);
164                 String name = policyName.getJsonString("serviceTypePolicyName").getString();
165                 serviceTypeNamesList.add(name);
166             }
167         } catch (IOException e) {
168             LOGGER.error("Exception Occured while initializing the JSONConfig file"+e);
169         }
170     }
171
172     @Override
173     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
174         LOGGER.debug("doPost");
175         try {
176             // if request contains multipart-form-data
177             if (ServletFileUpload.isMultipartContent(request)) {
178                 uploadFile(request, response);
179             }
180             // all other post request has json params in body
181             else {
182                 fileOperation(request, response);
183             }
184         } catch (Exception e) {
185             try {
186                 setError(e, response);
187             }catch(Exception e1){
188                 LOGGER.error("Exception Occured"+e1);
189             }
190         }
191     }
192
193     //Set Error Message for Exception
194     private void setError(Exception t, HttpServletResponse response) throws IOException {
195         try {
196             JSONObject responseJsonObject = error(t.getMessage());
197             response.setContentType(CONTENTTYPE);
198             PrintWriter out = response.getWriter();
199             out.print(responseJsonObject);
200             out.flush();
201         } catch (Exception x) {
202             LOGGER.error("Exception Occured"+x);
203             response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage());
204         }
205     }
206
207     //Policy Import Functionality
208     private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException {
209         try {
210             String newFile;
211             Map<String, InputStream> files = new HashMap<>();
212
213             List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
214             for (FileItem item : items) {
215                 if (!item.isFormField()) {
216                     // Process form file field (input type="file").
217                     files.put(item.getName(), item.getInputStream());
218                     processFormFile(request, item);
219                 }
220             }
221
222             JSONObject responseJsonObject;
223             responseJsonObject = this.success();
224             response.setContentType(CONTENTTYPE);
225             PrintWriter out = response.getWriter();
226             out.print(responseJsonObject);
227             out.flush();
228         } catch (Exception e) {
229             LOGGER.debug("Cannot write file");
230             throw new ServletException("Cannot write file", e);
231         }
232     }
233
234     private void processFormFile(HttpServletRequest request, FileItem item) {
235         String newFile;
236         if(item.getName().endsWith(".xls") && item.getSize() <= PolicyController.getFileSizeLimit()){
237             File file = new File(item.getName());
238             try (OutputStream outputStream = new FileOutputStream(file);)
239             {
240                 IOUtils.copy(item.getInputStream(), outputStream);
241                 newFile = file.toString();
242                 PolicyExportAndImportController importController = new PolicyExportAndImportController();
243                 importController.importRepositoryFile(newFile, request);
244             }catch(Exception e){
245                 LOGGER.error("Upload error : " + e);
246             }
247         }
248         else if (!item.getName().endsWith(".xls")) {
249             LOGGER.error("Non .xls filetype uploaded: " + item.getName());
250         }
251         else { //uploaded file size is greater than allowed
252             LOGGER.error("Upload file size limit exceeded! File size (Bytes) is: " + item.getSize());
253         }
254     }
255
256     //File Operation Functionality
257     private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
258         JSONObject responseJsonObject = null;
259         try {
260             StringBuilder sb = new StringBuilder();
261             BufferedReader br = request.getReader();
262             String str;
263             while ((str = br.readLine()) != null) {
264                 sb.append(str);
265             }
266             br.close();
267             JSONObject jObj = new JSONObject(sb.toString());
268             JSONObject params = jObj.getJSONObject("params");
269             Mode mode = Mode.valueOf(params.getString("mode"));
270
271             String userId = UserUtils.getUserSession(request).getOrgUserId();
272             LOGGER.info("****************************************Logging UserID while doing actions on Editor tab*******************************************");
273             LOGGER.info("UserId:  " + userId + "Action Mode:  "+ mode.toString() + "Action Params: "+params.toString());
274             LOGGER.info("***********************************************************************************************************************************");
275
276             switch (mode) {
277                 case ADDFOLDER:
278                 case ADDSUBSCOPE:
279                     responseJsonObject = addFolder(params, request);
280                     break;
281                 case COPY:
282                     responseJsonObject = copy(params, request);
283                     break;
284                 case DELETE:
285                     responseJsonObject = delete(params, request);
286                     break;
287                 case EDITFILE:
288                 case VIEWPOLICY:
289                     responseJsonObject = editFile(params);
290                     break;
291                 case LIST:
292                     responseJsonObject = list(params, request);
293                     break;
294                 case RENAME:
295                     responseJsonObject = rename(params, request);
296                     break;
297                 case DESCRIBEPOLICYFILE:
298                     responseJsonObject = describePolicy(params);
299                     break;
300                 case SWITCHVERSION:
301                     responseJsonObject = switchVersion(params, request);
302                     break;
303                 case SEARCHLIST:
304                     responseJsonObject = searchPolicyList(params, request);
305                     break;
306                 default:
307                     throw new ServletException("not implemented");
308             }
309             if (responseJsonObject == null) {
310                 responseJsonObject = error("generic error : responseJsonObject is null");
311             }
312         } catch (Exception e) {
313             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While doing File Operation" + e);
314             responseJsonObject = error(e.getMessage());
315         }
316         response.setContentType(CONTENTTYPE);
317         PrintWriter out = response.getWriter();
318         out.print(responseJsonObject);
319         out.flush();
320     }
321
322     private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) {
323         Set<String> scopes;
324         List<String> roles;
325         List<Object> policyData = new ArrayList<>();
326         JSONArray policyList = null;
327         if(params.has("policyList")){
328             policyList = (JSONArray) params.get("policyList");
329         }
330         PolicyController controller = getPolicyControllerInstance();
331         List<JSONObject> resultList = new ArrayList<>();
332         try {
333             //Get the Login Id of the User from Request
334             String userId =  UserUtils.getUserSession(request).getOrgUserId();
335             List<Object> userRoles = controller.getRoles(userId);
336             Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
337             roles = pair.u;
338             scopes = pair.t;
339             if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
340                 if(scopes.isEmpty()){
341                     return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
342                 }
343                 Set<String> tempScopes = scopes;
344                 for(String scope : tempScopes){
345                     addScope(scopes, scope);
346                 }
347             }
348             if(policyList!= null){
349                 for(int i = 0; i < policyList.length(); i++){
350                     String policyName = policyList.get(i).toString().replace(".xml", "");
351                     String version = policyName.substring(policyName.lastIndexOf('.')+1);
352                     policyName = policyName.substring(0, policyName.lastIndexOf('.')).replace(".", File.separator);
353                     parsePolicyList(resultList, controller, policyName, version);
354                 }
355             }else{
356                 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR)   || roles.contains(SUPERGUEST) ){
357                     policyData = controller.getData(PolicyVersion.class);
358                 }else{
359                     List<Object> filterdatas = controller.getData(PolicyVersion.class);
360                     for(Object filter : filterdatas){
361                         PolicyVersion filterdata = (PolicyVersion) filter;
362                         try{
363                             String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator));
364                             if(scopes.contains(scopeName)){
365                                 policyData.add(filterdata);
366                             }
367                         }catch(Exception e){
368                             LOGGER.error("Exception occured while filtering policyversion data"+e);
369                         }
370                     }
371                 }
372
373                 if(!policyData.isEmpty()){
374                     updateResultList(policyData, resultList);
375                 }
376             }
377         }catch(Exception e){
378             LOGGER.error("Exception occured while reading policy Data from Policy Version table for Policy Search Data"+e);
379         }
380
381         return new JSONObject().put(RESULT, resultList);
382     }
383
384     private void updateResultList(List<Object> policyData, List<JSONObject> resultList) {
385         for(int i =0; i < policyData.size(); i++){
386             PolicyVersion policy = (PolicyVersion) policyData.get(i);
387             JSONObject el = new JSONObject();
388             el.put("name", policy.getPolicyName().replace(File.separator, "/"));
389             el.put("date", policy.getModifiedDate());
390             el.put("version", policy.getActiveVersion());
391             el.put("size", "");
392             el.put("type", "file");
393             el.put("createdBy", getUserName(policy.getCreatedBy()));
394             el.put("modifiedBy", getUserName(policy.getModifiedBy()));
395             resultList.add(el);
396         }
397     }
398
399     private void parsePolicyList(List<JSONObject> resultList, PolicyController controller, String policyName, String version) {
400         if(policyName.contains("\\")){
401             policyName = policyName.replace("\\", "\\\\");
402         }
403         String policyVersionQuery = "From PolicyVersion where policy_name = :policyName  and active_version = :version and id >0";
404         SimpleBindings pvParams = new SimpleBindings();
405         pvParams.put("policyName", policyName);
406         pvParams.put("version", version);
407         List<Object> activeData = controller.getDataByQuery(policyVersionQuery, pvParams);
408         if(!activeData.isEmpty()){
409             PolicyVersion policy = (PolicyVersion) activeData.get(0);
410             JSONObject el = new JSONObject();
411             el.put("name", policy.getPolicyName().replace(File.separator, "/"));
412             el.put("date", policy.getModifiedDate());
413             el.put("version", policy.getActiveVersion());
414             el.put("size", "");
415             el.put("type", "file");
416             el.put("createdBy", getUserName(policy.getCreatedBy()));
417             el.put("modifiedBy", getUserName(policy.getModifiedBy()));
418             resultList.add(el);
419         }
420     }
421
422     private void addScope(Set<String> scopes, String scope) {
423         List<Object> scopesList = queryPolicyEditorScopes(scope);
424         if(!scopesList.isEmpty()){
425             for(int i = 0; i < scopesList.size(); i++){
426                 PolicyEditorScopes tempScope = (PolicyEditorScopes) scopesList.get(i);
427                 scopes.add(tempScope.getScopeName());
428             }
429         }
430     }
431
432     //Switch Version Functionality
433     private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{
434         String path = params.getString("path");
435         String userId = null;
436         try {
437             userId = UserUtils.getUserSession(request).getOrgUserId();
438         } catch (Exception e) {
439             LOGGER.error("Exception Occured while reading userid from cookie" +e);
440         }
441         String policyName;
442         String removeExtension = path.replace(".xml", "");
443         if(path.startsWith("/")){
444             policyName = removeExtension.substring(1, removeExtension.lastIndexOf('.'));
445         }else{
446             policyName = removeExtension.substring(0, removeExtension.lastIndexOf('.'));
447         }
448
449         String activePolicy;
450         PolicyController controller = getPolicyControllerInstance();
451         if(! params.toString().contains("activeVersion")){
452             return controller.switchVersionPolicyContent(policyName);
453         }
454         String activeVersion = params.getString("activeVersion");
455         String highestVersion = params.get("highestVersion").toString();
456         if(Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)){
457             return error("The Version shouldn't be greater than Highest Value");
458         }
459         activePolicy = policyName + "." + activeVersion + ".xml";
460         String dbCheckName = activePolicy.replace("/", ".");
461         if(dbCheckName.contains("Config_")){
462             dbCheckName = dbCheckName.replace(".Config_", ":Config_");
463         }else if(dbCheckName.contains("Action_")){
464             dbCheckName = dbCheckName.replace(".Action_", ":Action_");
465         }else if(dbCheckName.contains("Decision_")){
466             dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
467         }
468         String[] splitDBCheckName = dbCheckName.split(":");
469         String peQuery =   "FROM PolicyEntity where policyName = :splitDBCheckName_1 and scope = :splitDBCheckName_0";
470         SimpleBindings policyParams = new SimpleBindings();
471         policyParams.put("splitDBCheckName_1", splitDBCheckName[1]);
472         policyParams.put("splitDBCheckName_0", splitDBCheckName[0]);
473         List<Object> policyEntity = controller.getDataByQuery(peQuery, policyParams);
474         PolicyEntity pentity = (PolicyEntity) policyEntity.get(0);
475         if(pentity.isDeleted()){
476             return error("The Policy is Not Existing in Workspace");
477         }
478         if(policyName.contains("/")){
479             policyName = policyName.replace("/", File.separator);
480         }
481         policyName = policyName.substring(policyName.indexOf(File.separator)+1);
482         if(policyName.contains("\\")){
483             policyName = policyName.replace(File.separator, "\\");
484         }
485         policyName = splitDBCheckName[0].replace(".", File.separator)+File.separator+policyName;
486         String watchPolicyName = policyName;
487         if(policyName.contains("/")){
488             policyName = policyName.replace("/", File.separator);
489         }
490         if(policyName.contains("\\")){
491             policyName = policyName.replace("\\", "\\\\");
492         }
493         String query = "update PolicyVersion set active_version='"+activeVersion+"' where policy_name ='"+policyName+"'  and id >0";
494         //query the database
495         controller.executeQuery(query);
496         //Policy Notification
497         PolicyVersion entity = new PolicyVersion();
498         entity.setPolicyName(watchPolicyName);
499         entity.setActiveVersion(Integer.parseInt(activeVersion));
500         entity.setModifiedBy(userId);
501         controller.watchPolicyFunction(entity, activePolicy, "SwitchVersion");
502         return success();
503     }
504
505     //Describe Policy
506     private JSONObject describePolicy(JSONObject params) throws ServletException{
507         JSONObject object = null;
508         String path = params.getString("path");
509         String policyName = null;
510         if(path.startsWith("/")){
511             path = path.substring(1);
512             policyName = path.substring(path.lastIndexOf('/') +1);
513             path = path.replace("/", ".");
514         }else{
515             path = path.replace("/", ".");
516             policyName = path;
517         }
518         if(path.contains("Config_")){
519             path = path.replace(".Config_", ":Config_");
520         }else if(path.contains("Action_")){
521             path = path.replace(".Action_", ":Action_");
522         }else if(path.contains("Decision_")){
523             path = path.replace(".Decision_", ":Decision_");
524         }
525         PolicyController controller = getPolicyControllerInstance();
526         String[] split = path.split(":");
527         String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
528         SimpleBindings peParams = new SimpleBindings();
529         peParams.put("split_1", split[1]);
530         peParams.put("split_0", split[0]);
531         List<Object> queryData = null;
532         if(PolicyController.isjUnit()){
533             queryData = controller.getDataByQuery(query, null);
534         }else{
535             queryData = controller.getDataByQuery(query, peParams);
536         }
537         if(queryData.isEmpty()){
538             return error("Error Occured while Describing the Policy - query is empty");
539         }
540         PolicyEntity entity = (PolicyEntity) queryData.get(0);
541         File temp = null;
542         try {
543             temp = File.createTempFile(policyName, ".tmp");
544         } catch (IOException e) {
545             String message = "Failed to create temp file " + policyName + ".tmp";
546             LOGGER.error(message + e);
547             return error(message);
548         }
549         try (BufferedWriter bw = new BufferedWriter(new FileWriter(temp))) {
550             bw.write(entity.getPolicyData());
551         } catch (IOException e) {
552             LOGGER.error("Exception Occured while Describing the Policy"+e);
553         }
554         object = HumanPolicyComponent.DescribePolicy(temp);
555         if(temp != null){
556             try {
557                 Files.delete(temp.toPath());
558             } catch (IOException e) {
559                 LOGGER.warn("Failed to delete " + temp.getName() + e);
560             }
561         }
562         return object;
563     }
564
565     //Get the List of Policies and Scopes for Showing in Editor tab
566     private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException {
567         Set<String> scopes = null;
568         List<String> roles = null;
569         try {
570             PolicyController controller = getPolicyControllerInstance();
571             //Get the Login Id of the User from Request
572             String testUserID = getTestUserId();
573             String userId =  testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId();
574             List<Object> userRoles = controller.getRoles(userId);
575             Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
576             roles = pair.u;
577             scopes = pair.t;
578
579             List<JSONObject> resultList = new ArrayList<>();
580             boolean onlyFolders = params.getBoolean("onlyFolders");
581             String path = params.getString("path");
582             if(path.contains("..xml")){
583                 path = path.replaceAll("..xml", "").trim();
584             }
585
586             if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
587                 if(scopes.isEmpty()){
588                     return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
589                 }else{
590                     if(!"/".equals(path)){
591                         String tempScope = path.substring(1, path.length());
592                         tempScope = tempScope.replace("/", File.separator);
593                         scopes.add(tempScope);
594                     }
595                 }
596             }
597
598             if("/".equals(path)){
599                 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
600                     List<Object> scopesList = queryPolicyEditorScopes(null);
601                     for(Object list : scopesList){
602                         PolicyEditorScopes scope = (PolicyEditorScopes) list;
603                         if(!(scope.getScopeName().contains(File.separator))){
604                             JSONObject el = new JSONObject();
605                             el.put("name", scope.getScopeName());
606                             el.put("date", scope.getModifiedDate());
607                             el.put("size", "");
608                             el.put("type", "dir");
609                             el.put("createdBy", scope.getUserCreatedBy().getUserName());
610                             el.put("modifiedBy", scope.getUserModifiedBy().getUserName());
611                             resultList.add(el);
612                         }
613                     }
614                 }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){
615                     for(Object scope : scopes){
616                         JSONObject el = new JSONObject();
617                         List<Object> scopesList = queryPolicyEditorScopes(scope.toString());
618                         if(!scopesList.isEmpty()){
619                             PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
620                             el.put("name", scopeById.getScopeName());
621                             el.put("date", scopeById.getModifiedDate());
622                             el.put("size", "");
623                             el.put("type", "dir");
624                             el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
625                             el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
626                             resultList.add(el);
627                         }
628                     }
629                 }
630             }else{
631                 try{
632                     String scopeName = path.substring(path.indexOf('/') +1);
633                     activePolicyList(scopeName, resultList, roles, scopes, onlyFolders);
634                 } catch (Exception ex) {
635                     LOGGER.error("Error Occured While reading Policy Files List"+ex );
636                 }
637             }
638
639             return new JSONObject().put(RESULT, resultList);
640         } catch (Exception e) {
641             LOGGER.error("list", e);
642             return error(e.getMessage());
643         }
644     }
645
646     private List<Object> queryPolicyEditorScopes(String scopeName){
647         String scopeNamequery;
648         SimpleBindings params = new SimpleBindings();
649         if(scopeName == null){
650             scopeNamequery = "from PolicyEditorScopes";
651         }else{
652             scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
653             params.put("scopeName", scopeName + "%");
654         }
655         PolicyController controller = getPolicyControllerInstance();
656         List<Object> scopesList;
657         if(PolicyController.isjUnit()){
658             scopesList = controller.getDataByQuery(scopeNamequery, null);
659         }else{
660             scopesList = controller.getDataByQuery(scopeNamequery, params);
661         }
662         return  scopesList;
663     }
664
665     //Get Active Policy List based on Scope Selection form Policy Version table
666     private void activePolicyList(String inScopeName, List<JSONObject> resultList, List<String> roles, Set<String> scopes, boolean onlyFolders){
667         PolicyController controller = getPolicyControllerInstance();
668         String scopeName = inScopeName;
669         if(scopeName.contains("/")){
670             scopeName = scopeName.replace("/", File.separator);
671         }
672         if(scopeName.contains("\\")){
673             scopeName = scopeName.replace("\\", "\\\\");
674         }
675         String query = "from PolicyVersion where POLICY_NAME like :scopeName";
676         String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
677
678         SimpleBindings params = new SimpleBindings();
679         params.put("scopeName", scopeName + "%");
680
681         List<Object> activePolicies;
682         List<Object> scopesList;
683         if(PolicyController.isjUnit()){
684             activePolicies = controller.getDataByQuery(query, null);
685             scopesList = controller.getDataByQuery(scopeNamequery, null);
686         }else{
687             activePolicies = controller.getDataByQuery(query, params);
688             scopesList = controller.getDataByQuery(scopeNamequery, params);
689         }
690         for(Object list : scopesList){
691             PolicyEditorScopes scopeById = (PolicyEditorScopes) list;
692             String scope = scopeById.getScopeName();
693             if(scope.contains(File.separator)){
694                 String checkScope = scope.substring(0, scope.lastIndexOf(File.separator));
695                 if(scopeName.contains("\\\\")){
696                     scopeName = scopeName.replace("\\\\", File.separator);
697                 }
698                 if(scope.contains(File.separator)){
699                     scope = scope.substring(checkScope.length()+1);
700                     if(scope.contains(File.separator)){
701                         scope = scope.substring(0, scope.indexOf(File.separator));
702                     }
703                 }
704                 if(scopeName.equalsIgnoreCase(checkScope)){
705                     JSONObject el = new JSONObject();
706                     el.put("name", scope);
707                     el.put("date", scopeById.getModifiedDate());
708                     el.put("size", "");
709                     el.put("type", "dir");
710                     el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
711                     el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
712                     resultList.add(el);
713                 }
714             }
715         }
716         String scopeNameCheck;
717         for (Object list : activePolicies) {
718             PolicyVersion policy = (PolicyVersion) list;
719             String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator));
720             if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
721                 if(scopeName.contains("\\\\")){
722                     scopeNameCheck = scopeName.replace("\\\\", File.separator);
723                 }else{
724                     scopeNameCheck = scopeName;
725                 }
726                 if(scopeNameValue.equals(scopeNameCheck)){
727                     JSONObject el = new JSONObject();
728                     el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
729                     el.put("date", policy.getModifiedDate());
730                     el.put("version", policy.getActiveVersion());
731                     el.put("size", "");
732                     el.put("type", "file");
733                     el.put("createdBy", getUserName(policy.getCreatedBy()));
734                     el.put("modifiedBy", getUserName(policy.getModifiedBy()));
735                     resultList.add(el);
736                 }
737             }else if(!scopes.isEmpty() && scopes.contains(scopeNameValue)){
738                 JSONObject el = new JSONObject();
739                 el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
740                 el.put("date", policy.getModifiedDate());
741                 el.put("version", policy.getActiveVersion());
742                 el.put("size", "");
743                 el.put("type", "file");
744                 el.put("createdBy", getUserName(policy.getCreatedBy()));
745                 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
746                 resultList.add(el);
747             }
748         }
749     }
750
751     private String getUserName(String loginId){
752         PolicyController controller = getPolicyControllerInstance();
753         UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
754         if(userInfo == null){
755             return SUPERADMIN;
756         }
757         return userInfo.getUserName();
758     }
759
760     //Rename Policy
761     private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
762         try {
763             boolean isActive = false;
764             List<String> policyActiveInPDP = new ArrayList<>();
765             Set<String>  scopeOfPolicyActiveInPDP = new HashSet<>();
766             String userId = UserUtils.getUserSession(request).getOrgUserId();
767             String oldPath = params.getString("path");
768             String newPath = params.getString("newPath");
769             oldPath = oldPath.substring(oldPath.indexOf('/')+1);
770             newPath = newPath.substring(newPath.indexOf('/')+1);
771             String checkValidation = null;
772             if(oldPath.endsWith(".xml")){
773                 checkValidation = newPath.replace(".xml", "");
774                 checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf("."));
775                 checkValidation = checkValidation.substring(checkValidation.lastIndexOf("/")+1);
776                 if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains("success")){
777                     return error("Policy Rename Failed. The Name contains special characters.");
778                 }
779                 JSONObject result = policyRename(oldPath, newPath, userId);
780                 if(!(Boolean)(result.getJSONObject("result").get("success"))){
781                     return result;
782                 }
783             }else{
784                 String scopeName = oldPath;
785                 String newScopeName = newPath;
786                 if(scopeName.contains("/")){
787                     scopeName = scopeName.replace("/", File.separator);
788                     newScopeName = newScopeName.replace("/", File.separator);
789                 }
790                 checkValidation = newScopeName.substring(newScopeName.lastIndexOf(File.separator)+1);
791                 if(scopeName.contains("\\")){
792                     scopeName = scopeName.replace("\\", "\\\\\\\\");
793                     newScopeName = newScopeName.replace("\\", "\\\\\\\\");
794                 }
795                 if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains("success")){
796                     return error("Scope Rename Failed. The Name contains special characters.");
797                 }
798                 PolicyController controller = getPolicyControllerInstance();
799                 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
800                 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
801                 SimpleBindings pvParams = new SimpleBindings();
802                 pvParams.put("scopeName", scopeName + "%");
803                 List<Object> activePolicies = controller.getDataByQuery(query, pvParams);
804                 List<Object> scopesList = controller.getDataByQuery(scopeNamequery, pvParams);
805                 for(Object object : activePolicies){
806                     PolicyVersion activeVersion = (PolicyVersion) object;
807                     String policyOldPath = activeVersion.getPolicyName().replace(File.separator, "/") + "." + activeVersion.getActiveVersion() + ".xml";
808                     String policyNewPath = policyOldPath.replace(oldPath, newPath);
809                     JSONObject result = policyRename(policyOldPath, policyNewPath, userId);
810                     if(!(Boolean)(result.getJSONObject("result").get("success"))){
811                         isActive = true;
812                         policyActiveInPDP.add(policyOldPath);
813                         String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf('/'));
814                         scopeOfPolicyActiveInPDP.add(scope.replace("/", File.separator));
815                     }
816                 }
817                 boolean rename = false;
818                 if(activePolicies.size() != policyActiveInPDP.size()){
819                     rename = true;
820                 }
821
822                 UserInfo userInfo = new UserInfo();
823                 userInfo.setUserLoginId(userId);
824                 if(policyActiveInPDP.isEmpty()){
825                     renameScope(scopesList, scopeName, newScopeName, controller);
826                 }else if(rename){
827                     renameScope(scopesList, scopeName, newScopeName, controller);
828                     for(String scope : scopeOfPolicyActiveInPDP){
829                         PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes();
830                         editorScopeEntity.setScopeName(scope.replace("\\", "\\\\\\\\"));
831                         editorScopeEntity.setUserCreatedBy(userInfo);
832                         editorScopeEntity.setUserModifiedBy(userInfo);
833                         controller.saveData(editorScopeEntity);
834                     }
835                 }
836                 if(isActive){
837                     return error("The Following policies rename failed. Since they are active in PDP Groups" +policyActiveInPDP);
838                 }
839             }
840             return success();
841         } catch (Exception e) {
842             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
843             return error(e.getMessage());
844         }
845     }
846
847     private void renameScope(List<Object> scopesList, String inScopeName, String newScopeName, PolicyController controller){
848         for(Object object : scopesList){
849             PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object;
850             String scopeName = inScopeName;
851             if(scopeName.contains("\\\\\\\\")){
852                 scopeName = scopeName.replace("\\\\\\\\", File.separator);
853                 newScopeName = newScopeName.replace("\\\\\\\\", File.separator);
854             }
855             String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName);
856             editorScopeEntity.setScopeName(scope);
857             controller.updateData(editorScopeEntity);
858         }
859     }
860
861     private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
862         try {
863             PolicyEntity entity;
864             PolicyController controller = getPolicyControllerInstance();
865
866             String policyVersionName = newPath.replace(".xml", "");
867             String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')).replace("/", File.separator);
868
869             String oldpolicyVersionName = oldPath.replace(".xml", "");
870             String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf('.')).replace("/", File.separator);
871
872             String newpolicyName = newPath.replace("/", ".");
873             String newPolicyCheck = newpolicyName;
874             if(newPolicyCheck.contains("Config_")){
875                 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
876             }else if(newPolicyCheck.contains("Action_")){
877                 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
878             }else if(newPolicyCheck.contains("Decision_")){
879                 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
880             }
881             String[] newPolicySplit = newPolicyCheck.split(":");
882
883             String orignalPolicyName = oldPath.replace("/", ".");
884             String oldPolicyCheck = orignalPolicyName;
885             if(oldPolicyCheck.contains("Config_")){
886                 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
887             }else if(oldPolicyCheck.contains("Action_")){
888                 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
889             }else if(oldPolicyCheck.contains("Decision_")){
890                 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
891             }
892             String[] oldPolicySplit = oldPolicyCheck.split(":");
893
894             //Check PolicyEntity table with newPolicy Name
895             String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
896             SimpleBindings policyParams = new SimpleBindings();
897             policyParams.put("newPolicySplit_1", newPolicySplit[1]);
898             policyParams.put("newPolicySplit_0", newPolicySplit[0]);
899             List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
900             if(!queryData.isEmpty()){
901                 return error("Policy rename failed. Since, the policy with same name already exists.");
902             }
903
904             //Query the Policy Entity with oldPolicy Name
905             String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf('.'));
906             String oldpolicyEntityquery = "FROM PolicyEntity where policyName like :policyEntityCheck and scope = :oldPolicySplit_0";
907             SimpleBindings params = new SimpleBindings();
908             params.put("policyEntityCheck", policyEntityCheck + "%");
909             params.put("oldPolicySplit_0", oldPolicySplit[0]);
910             List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery, params);
911             if(!oldEntityData.isEmpty()){
912                 StringBuilder groupQuery = new StringBuilder();
913                 groupQuery.append("FROM PolicyGroupEntity where (");
914                 SimpleBindings geParams = new SimpleBindings();
915                 for(int i=0; i<oldEntityData.size(); i++){
916                     entity = (PolicyEntity) oldEntityData.get(i);
917                     if(i == 0){
918                         groupQuery.append("policyid = :policyId");
919                         geParams.put("policyId", entity.getPolicyId());
920                     }else{
921                         groupQuery.append(" or policyid = :policyId" + i);
922                         geParams.put("policyId" + i, entity.getPolicyId());
923                     }
924                 }
925                 groupQuery.append(")");
926                 List<Object> groupEntityData = controller.getDataByQuery(groupQuery.toString(), geParams);
927                 if(! groupEntityData.isEmpty()){
928                     return error("Policy rename failed. Since the policy or its version is active in PDP Groups.");
929                 }
930                 for(int i=0; i<oldEntityData.size(); i++){
931                     entity = (PolicyEntity) oldEntityData.get(i);
932                     String checkEntityName = entity.getPolicyName().replace(".xml", "");
933                     checkEntityName = checkEntityName.substring(0, checkEntityName.lastIndexOf('.'));
934                     String originalPolicyName = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
935                     if(checkEntityName.equals(originalPolicyName)){
936                         checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0] , newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
937                     }
938                 }
939             }else{
940                 return error("Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin.");
941             }
942
943             return success();
944         } catch (Exception e) {
945             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
946             return error(e.getMessage());
947         }
948     }
949
950     private JSONObject checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, String oldScope, String removeoldPolicyExtension,
951                                                     String policyName, String  newpolicyName, String oldpolicyName, String userId) throws ServletException{
952         try {
953             ConfigurationDataEntity configEntity = entity.getConfigurationData();
954             ActionBodyEntity actionEntity = entity.getActionBodyEntity();
955             PolicyController controller = getPolicyControllerInstance();
956
957             String oldPolicyNameWithoutExtension = removeoldPolicyExtension;
958             String newPolicyNameWithoutExtension = removenewPolicyExtension;
959             if(removeoldPolicyExtension.endsWith(".xml")){
960                 oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf('.'));
961                 newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf('.'));
962             }
963             entity.setPolicyName(entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
964             entity.setPolicyData(entity.getPolicyData().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
965             entity.setScope(newScope);
966             entity.setModifiedBy(userId);
967
968             String oldConfigurationName = null;
969             String newConfigurationName = null;
970             if(newpolicyName.contains("Config_")){
971                 oldConfigurationName = configEntity.getConfigurationName();
972                 configEntity.setConfigurationName(configEntity.getConfigurationName().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
973                 controller.updateData(configEntity);
974                 newConfigurationName = configEntity.getConfigurationName();
975                 File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName);
976                 if(file.exists()){
977                     File renamefile = new File(PolicyController.getConfigHome() + File.separator + newConfigurationName);
978                     file.renameTo(renamefile);
979                 }
980             }else if(newpolicyName.contains("Action_")){
981                 oldConfigurationName = actionEntity.getActionBodyName();
982                 actionEntity.setActionBody(actionEntity.getActionBody().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
983                 controller.updateData(actionEntity);
984                 newConfigurationName = actionEntity.getActionBodyName();
985                 File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName);
986                 if(file.exists()){
987                     File renamefile = new File(PolicyController.getActionHome() + File.separator + newConfigurationName);
988                     file.renameTo(renamefile);
989                 }
990             }
991             controller.updateData(entity);
992
993             PolicyRestController restController = new PolicyRestController();
994             restController.notifyOtherPAPSToUpdateConfigurations("rename", newConfigurationName, oldConfigurationName);
995             PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldpolicyName);
996             versionEntity.setPolicyName(policyName);
997             versionEntity.setModifiedBy(userId);
998             controller.updateData(versionEntity);
999             String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator)+1);
1000             String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
1001             if(movePolicyCheck.equals(moveOldPolicyCheck)){
1002                 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move");
1003             }else{
1004                 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename");
1005             }
1006             return success();
1007         } catch (Exception e) {
1008             LOGGER.error("Exception Occured"+e);
1009             return error(e.getMessage());
1010         }
1011     }
1012
1013     private JSONObject cloneRecord(String newpolicyName, String oldScope, String inRemoveoldPolicyExtension, String newScope, String inRemovenewPolicyExtension, PolicyEntity entity, String userId) throws ServletException{
1014         String queryEntityName;
1015         PolicyController controller = getPolicyControllerInstance();
1016         PolicyEntity cloneEntity = new PolicyEntity();
1017         cloneEntity.setPolicyName(newpolicyName);
1018         String removeoldPolicyExtension = inRemoveoldPolicyExtension;
1019         String removenewPolicyExtension = inRemovenewPolicyExtension;
1020         removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
1021         removenewPolicyExtension = removenewPolicyExtension.replace(".xml", "");
1022         cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope+"."+removeoldPolicyExtension, newScope+"."+removenewPolicyExtension));
1023         cloneEntity.setScope(entity.getScope());
1024         String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
1025         String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
1026         String newConfigurationName = null;
1027         if(newpolicyName.contains("Config_")){
1028             ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
1029             configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1030             queryEntityName = configurationDataEntity.getConfigurationName();
1031             configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody());
1032             configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType());
1033             configurationDataEntity.setDeleted(false);
1034             configurationDataEntity.setCreatedBy(userId);
1035             configurationDataEntity.setModifiedBy(userId);
1036             controller.saveData(configurationDataEntity);
1037             ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
1038             cloneEntity.setConfigurationData(configEntiy);
1039             newConfigurationName = configEntiy.getConfigurationName();
1040             try (FileWriter fw = new FileWriter(PolicyController.getConfigHome() + File.separator + newConfigurationName);
1041                  BufferedWriter bw = new BufferedWriter(fw)){
1042                 bw.write(configEntiy.getConfigBody());
1043             } catch (IOException e) {
1044                 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1045             }
1046         }else if(newpolicyName.contains("Action_")){
1047             ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
1048             actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1049             queryEntityName = actionBodyEntity.getActionBodyName();
1050             actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody());
1051             actionBodyEntity.setDeleted(false);
1052             actionBodyEntity.setCreatedBy(userId);
1053             actionBodyEntity.setModifiedBy(userId);
1054             controller.saveData(actionBodyEntity);
1055             ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class, "actionBodyName", queryEntityName);
1056             cloneEntity.setActionBodyEntity(actionEntiy);
1057             newConfigurationName = actionEntiy.getActionBodyName();
1058             try (FileWriter fw = new FileWriter(PolicyController.getActionHome() + File.separator + newConfigurationName);
1059                  BufferedWriter bw = new BufferedWriter(fw)){
1060                 bw.write(actionEntiy.getActionBody());
1061             } catch (IOException e) {
1062                 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1063             }
1064         }
1065
1066         cloneEntity.setDeleted(entity.isDeleted());
1067         cloneEntity.setCreatedBy(userId);
1068         cloneEntity.setModifiedBy(userId);
1069         controller.saveData(cloneEntity);
1070
1071         //Notify others paps regarding clone policy.
1072         PolicyRestController restController = new PolicyRestController();
1073         restController.notifyOtherPAPSToUpdateConfigurations("clonePolicy", newConfigurationName, null);
1074         return success();
1075     }
1076
1077     //Clone the Policy
1078     private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
1079         try {
1080             String userId = UserUtils.getUserSession(request).getOrgUserId();
1081             String oldPath = params.getString("path");
1082             String newPath = params.getString("newPath");
1083             oldPath = oldPath.substring(oldPath.indexOf('/')+1);
1084             newPath = newPath.substring(newPath.indexOf('/')+1);
1085
1086             String policyVersionName = newPath.replace(".xml", "");
1087             String version = policyVersionName.substring(policyVersionName.indexOf('.')+1);
1088             String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')).replace("/", File.separator);
1089
1090             String newpolicyName = newPath.replace("/", ".");
1091
1092             String orignalPolicyName = oldPath.replace("/", ".");
1093
1094             String newPolicyCheck = newpolicyName;
1095             if(newPolicyCheck.contains("Config_")){
1096                 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
1097             }else if(newPolicyCheck.contains("Action_")){
1098                 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
1099             }else if(newPolicyCheck.contains("Decision_")){
1100                 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
1101             }
1102             if(!newPolicyCheck.contains(":")){
1103                 return error("Policy Clone Failed. The Name contains special characters.");
1104             }
1105             String[] newPolicySplit = newPolicyCheck.split(":");
1106
1107             String checkValidation = newPolicySplit[1].replace(".xml", "");
1108             checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf("."));
1109             if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains("success")){
1110                 return error("Policy Clone Failed. The Name contains special characters.");
1111             }
1112
1113             String oldPolicyCheck = orignalPolicyName;
1114             if(oldPolicyCheck.contains("Config_")){
1115                 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
1116             }else if(oldPolicyCheck.contains("Action_")){
1117                 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
1118             }else if(oldPolicyCheck.contains("Decision_")){
1119                 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
1120             }
1121             String[] oldPolicySplit = oldPolicyCheck.split(":");
1122
1123             PolicyController controller = getPolicyControllerInstance();
1124
1125             PolicyEntity entity = null;
1126             boolean success = false;
1127
1128             //Check PolicyEntity table with newPolicy Name
1129             String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
1130             SimpleBindings policyParams = new SimpleBindings();
1131             policyParams.put("newPolicySplit_1", newPolicySplit[1]);
1132             policyParams.put("newPolicySplit_0", newPolicySplit[0]);
1133             List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
1134             if(!queryData.isEmpty()){
1135                 return error("Policy already exists with same name");
1136             }
1137
1138             //Query the Policy Entity with oldPolicy Name
1139             policyEntityquery = "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0";
1140             SimpleBindings peParams = new SimpleBindings();
1141             peParams.put("oldPolicySplit_1", oldPolicySplit[1]);
1142             peParams.put("oldPolicySplit_0", oldPolicySplit[0]);
1143             if(PolicyController.isjUnit()){
1144                 queryData = controller.getDataByQuery(policyEntityquery, null);
1145             }else{
1146                 queryData = controller.getDataByQuery(policyEntityquery, peParams);
1147             }
1148             if(!queryData.isEmpty()){
1149                 entity = (PolicyEntity) queryData.get(0);
1150             }
1151             if(entity != null){
1152                 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1],  newPolicySplit[0], newPolicySplit[1], entity, userId);
1153                 success = true;
1154             }
1155
1156             if(success){
1157                 PolicyVersion entityItem = new PolicyVersion();
1158                 entityItem.setActiveVersion(Integer.parseInt(version));
1159                 entityItem.setHigherVersion(Integer.parseInt(version));
1160                 entityItem.setPolicyName(policyName);
1161                 entityItem.setCreatedBy(userId);
1162                 entityItem.setModifiedBy(userId);
1163                 entityItem.setModifiedDate(new Date());
1164                 controller.saveData(entityItem);
1165             }
1166
1167             LOGGER.debug("copy from: {} to: {}" + oldPath +newPath);
1168
1169             return success();
1170         } catch (Exception e) {
1171             LOGGER.error("copy", e);
1172             return error(e.getMessage());
1173         }
1174     }
1175
1176     //Delete Policy or Scope Functionality
1177     private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
1178         PolicyController controller = getPolicyControllerInstance();
1179         PolicyRestController restController = new PolicyRestController();
1180         PolicyEntity policyEntity = null;
1181         String policyNamewithoutExtension;
1182         try {
1183             String userId = UserUtils.getUserSession(request).getOrgUserId();
1184             String deleteVersion = "";
1185             String path = params.getString("path");
1186             LOGGER.debug("delete {}" +path);
1187             if(params.has("deleteVersion")){
1188                 deleteVersion  = params.getString("deleteVersion");
1189             }
1190             path = path.substring(path.indexOf('/')+1);
1191             String policyNamewithExtension = path.replace("/", File.separator);
1192             String policyVersionName = policyNamewithExtension.replace(".xml", "");
1193             String query;
1194             SimpleBindings policyParams = new SimpleBindings();
1195             if(path.endsWith(".xml")){
1196                 policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf('.'));
1197                 policyNamewithoutExtension = policyNamewithoutExtension.replace(File.separator, ".");
1198                 String splitPolicyName = null;
1199                 if(policyNamewithoutExtension.contains("Config_")){
1200                     splitPolicyName = policyNamewithoutExtension.replace(".Config_", ":Config_");
1201                 }else if(policyNamewithoutExtension.contains("Action_")){
1202                     splitPolicyName = policyNamewithoutExtension.replace(".Action_", ":Action_");
1203                 }else if(policyNamewithoutExtension.contains("Decision_")){
1204                     splitPolicyName = policyNamewithoutExtension.replace(".Decision_", ":Decision_");
1205                 }
1206                 String[] split = splitPolicyName.split(":");
1207
1208                 query = "FROM PolicyEntity where policyName like :split_1 and scope = :split_0";
1209                 policyParams.put("split_1", split[1] + "%");
1210                 policyParams.put("split_0", split[0]);
1211             }else{
1212                 policyNamewithoutExtension = path.replace(File.separator, ".");
1213                 query = "FROM PolicyEntity where scope like :policyNamewithoutExtension";
1214                 policyParams.put("policyNamewithoutExtension", policyNamewithoutExtension + "%");
1215             }
1216
1217             List<Object> policyEntityobjects = controller.getDataByQuery(query, policyParams);
1218             String activePolicyName = null;
1219             boolean pdpCheck = false;
1220             if(path.endsWith(".xml")){
1221                 policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator);
1222                 int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf('.')+1));
1223                 if("ALL".equals(deleteVersion)){
1224                     if(!policyEntityobjects.isEmpty()){
1225                         for(Object object : policyEntityobjects){
1226                             policyEntity = (PolicyEntity) object;
1227                             String groupEntityquery = "from PolicyGroupEntity where policyid ='"+policyEntity.getPolicyId()+"'";
1228                             SimpleBindings pgeParams = new SimpleBindings();
1229                             List<Object> groupobject = controller.getDataByQuery(groupEntityquery, pgeParams);
1230                             if(!groupobject.isEmpty()){
1231                                 pdpCheck = true;
1232                                 activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName();
1233                             }else{
1234                                 //Delete the entity from Elastic Search Database
1235                                 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1236                                 restController.deleteElasticData(searchFileName);
1237                                 //Delete the entity from Policy Entity table
1238                                 controller.deleteData(policyEntity);
1239                                 if(policyNamewithoutExtension.contains("Config_")){
1240                                     Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1241                                     controller.deleteData(policyEntity.getConfigurationData());
1242                                     restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getConfigurationData().getConfigurationName());
1243                                 }else if(policyNamewithoutExtension.contains("Action_")){
1244                                     Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1245                                     controller.deleteData(policyEntity.getActionBodyEntity());
1246                                     restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getActionBodyEntity().getActionBodyName());
1247                                 }
1248                             }
1249                         }
1250                     }
1251                     //Policy Notification
1252                     PolicyVersion versionEntity = new PolicyVersion();
1253                     versionEntity.setPolicyName(policyNamewithoutExtension);
1254                     versionEntity.setModifiedBy(userId);
1255                     controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll");
1256                     if(pdpCheck){
1257                         //Delete from policyVersion table
1258                         String getActivePDPPolicyVersion = activePolicyName.replace(".xml", "");
1259                         getActivePDPPolicyVersion = getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf('.')+1);
1260                         String policyVersionQuery = "update PolicyVersion set active_version='"+getActivePDPPolicyVersion+"' , highest_version='"+getActivePDPPolicyVersion+"'  where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1261                         if(policyVersionQuery != null){
1262                             controller.executeQuery(policyVersionQuery);
1263                         }
1264                         return error("Policies with Same name has been deleted. Except the Active Policy in PDP.     PolicyName: "+activePolicyName);
1265                     }else{
1266                         //No Active Policy in PDP. So, deleting all entries from policyVersion table
1267                         String policyVersionQuery = "delete from PolicyVersion  where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1268                         if(policyVersionQuery != null){
1269                             controller.executeQuery(policyVersionQuery);
1270                         }
1271                     }
1272                 }else if("CURRENT".equals(deleteVersion)){
1273                     String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1);
1274                     String currentVersionScope = policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator)).replace(File.separator, ".");
1275                     query = "FROM PolicyEntity where policyName = :currentVersionPolicyName and scope = :currentVersionScope";
1276
1277                     SimpleBindings peParams = new SimpleBindings();
1278                     peParams.put("currentVersionPolicyName", currentVersionPolicyName);
1279                     peParams.put("currentVersionScope", currentVersionScope);
1280
1281                     List<Object> policyEntitys = controller.getDataByQuery(query, peParams);
1282                     if(!policyEntitys.isEmpty()){
1283                         policyEntity = (PolicyEntity) policyEntitys.get(0);
1284                     }
1285                     if(policyEntity != null){
1286                         String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId and policyid > 0";
1287                         SimpleBindings geParams = new SimpleBindings();
1288                         geParams.put("policyEntityId", policyEntity.getPolicyId());
1289                         List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1290                         if(groupobject.isEmpty()){
1291                             //Delete the entity from Elastic Search Database
1292                             String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1293                             restController.deleteElasticData(searchFileName);
1294                             //Delete the entity from Policy Entity table
1295                             controller.deleteData(policyEntity);
1296                             if(policyNamewithoutExtension.contains("Config_")){
1297                                 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1298                                 controller.deleteData(policyEntity.getConfigurationData());
1299                                 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getConfigurationData().getConfigurationName());
1300                             }else if(policyNamewithoutExtension.contains("Action_")){
1301                                 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1302                                 controller.deleteData(policyEntity.getActionBodyEntity());
1303                                 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getActionBodyEntity().getActionBodyName());
1304                             }
1305
1306                             if(version > 1){
1307                                 int highestVersion = 0;
1308                                 if(!policyEntityobjects.isEmpty()){
1309                                     for(Object object : policyEntityobjects){
1310                                         policyEntity = (PolicyEntity) object;
1311                                         String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
1312                                         int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf('.')+1));
1313                                         if(policyEntityVersion > highestVersion && policyEntityVersion != version){
1314                                             highestVersion = policyEntityVersion;
1315                                         }
1316                                     }
1317                                 }
1318
1319                                 //Policy Notification
1320                                 PolicyVersion entity = new PolicyVersion();
1321                                 entity.setPolicyName(policyNamewithoutExtension);
1322                                 entity.setActiveVersion(highestVersion);
1323                                 entity.setModifiedBy(userId);
1324                                 controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne");
1325
1326                                 String updatequery = "";
1327                                 if(highestVersion != 0){
1328                                     updatequery = "update PolicyVersion set active_version='"+highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"'";
1329                                 }else{
1330                                     updatequery = "delete from PolicyVersion  where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1331                                 }
1332                                 controller.executeQuery(updatequery);
1333                             }else{
1334                                 String policyVersionQuery = "delete from PolicyVersion  where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1335                                 if(policyVersionQuery != null){
1336                                     controller.executeQuery(policyVersionQuery);
1337                                 }
1338                             }
1339                         }else{
1340                             return error("Policy can't be deleted, it is active in PDP Groups.     PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'");
1341                         }
1342                     }
1343                 }
1344             }else{
1345                 List<String> activePoliciesInPDP = new ArrayList<>();
1346                 if(!policyEntityobjects.isEmpty()){
1347                     for(Object object : policyEntityobjects){
1348                         policyEntity = (PolicyEntity) object;
1349                         String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId";
1350                         SimpleBindings geParams = new SimpleBindings();
1351                         geParams.put("policyEntityId", policyEntity.getPolicyId());
1352                         List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1353                         if(!groupobject.isEmpty()){
1354                             pdpCheck = true;
1355                             activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName());
1356                         }else{
1357                             //Delete the entity from Elastic Search Database
1358                             String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1359                             restController.deleteElasticData(searchFileName);
1360                             //Delete the entity from Policy Entity table
1361                             controller.deleteData(policyEntity);
1362                             policyNamewithoutExtension = policyEntity.getPolicyName();
1363                             if(policyNamewithoutExtension.contains("Config_")){
1364                                 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1365                                 controller.deleteData(policyEntity.getConfigurationData());
1366                                 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getConfigurationData().getConfigurationName());
1367                             }else if(policyNamewithoutExtension.contains("Action_")){
1368                                 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1369                                 controller.deleteData(policyEntity.getActionBodyEntity());
1370                                 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getActionBodyEntity().getActionBodyName());
1371                             }
1372                         }
1373                     }
1374                     //Delete from policyVersion and policyEditor Scope table
1375                     String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1376                     controller.executeQuery(policyVersionQuery);
1377
1378                     //Policy Notification
1379                     PolicyVersion entity = new PolicyVersion();
1380                     entity.setPolicyName(path);
1381                     entity.setModifiedBy(userId);
1382                     controller.watchPolicyFunction(entity, path, "DeleteScope");
1383                     if(pdpCheck){
1384                         //Add Active Policies List to PolicyVersionTable
1385                         for(int i =0; i < activePoliciesInPDP.size(); i++){
1386                             String activePDPPolicyName = activePoliciesInPDP.get(i).replace(".xml", "");
1387                             int activePDPPolicyVersion = Integer.parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf('.')+1));
1388                             activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf('.')).replace(".", File.separator);
1389                             PolicyVersion insertactivePDPVersion = new PolicyVersion();
1390                             insertactivePDPVersion.setPolicyName(activePDPPolicyName);
1391                             insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion);
1392                             insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion);
1393                             insertactivePDPVersion.setCreatedBy(userId);
1394                             insertactivePDPVersion.setModifiedBy(userId);
1395                             controller.saveData(insertactivePDPVersion);
1396                         }
1397
1398                         return error("All the Policies has been deleted in Scope. Except the following list of Policies:"+activePoliciesInPDP);
1399                     }else{
1400                         String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1401                         controller.executeQuery(policyScopeQuery);
1402                     }
1403                 }else{
1404                     String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1405                     controller.executeQuery(policyScopeQuery);
1406                 }
1407             }
1408             return success();
1409         } catch (Exception e) {
1410             LOGGER.error("delete", e);
1411             return error(e.getMessage());
1412         }
1413     }
1414
1415     //Edit the Policy
1416     private JSONObject editFile(JSONObject params) throws ServletException {
1417         // get content
1418         try {
1419             PolicyController controller = getPolicyControllerInstance();
1420             String mode = params.getString("mode");
1421             String path = params.getString("path");
1422             LOGGER.debug("editFile path: {}"+ path);
1423
1424             String domain = path.substring(1, path.lastIndexOf('/'));
1425             domain = domain.replace("/", ".");
1426
1427             path = path.substring(1);
1428             path = path.replace("/", ".");
1429             String dbCheckName = path;
1430             if(dbCheckName.contains("Config_")){
1431                 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
1432             }else if(dbCheckName.contains("Action_")){
1433                 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
1434             }else if(dbCheckName.contains("Decision_")){
1435                 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
1436             }
1437
1438             String[] split = dbCheckName.split(":");
1439             String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
1440             SimpleBindings peParams = new SimpleBindings();
1441             peParams.put("split_1", split[1]);
1442             peParams.put("split_0", split[0]);
1443             List<Object> queryData;
1444             if(PolicyController.isjUnit()){
1445                 queryData = controller.getDataByQuery(query, null);
1446             }else{
1447                 queryData = controller.getDataByQuery(query, peParams);
1448             }
1449             PolicyEntity entity = (PolicyEntity) queryData.get(0);
1450             InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
1451
1452
1453             Object policy = XACMLPolicyScanner.readPolicy(stream);
1454             PolicyRestAdapter policyAdapter  = new PolicyRestAdapter();
1455             policyAdapter.setData(policy);
1456
1457             if("viewPolicy".equalsIgnoreCase(mode)){
1458                 policyAdapter.setReadOnly(true);
1459                 policyAdapter.setEditPolicy(false);
1460             }else{
1461                 policyAdapter.setReadOnly(false);
1462                 policyAdapter.setEditPolicy(true);
1463             }
1464
1465             policyAdapter.setDomainDir(domain);
1466             policyAdapter.setPolicyData(policy);
1467             String policyName = path.replace(".xml", "");
1468             policyName = policyName.substring(0, policyName.lastIndexOf('.'));
1469             policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf('.')+1));
1470
1471             PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance();
1472             setpolicyAdapter.configure(policyAdapter,entity);
1473
1474             policyAdapter.setParentPath(null);
1475             ObjectMapper mapper = new ObjectMapper();
1476             String json = mapper.writeValueAsString(policyAdapter);
1477             JsonNode jsonNode = mapper.readTree(json);
1478
1479             return new JSONObject().put(RESULT, jsonNode);
1480         } catch (Exception e) {
1481             LOGGER.error("editFile", e);
1482             return error(e.getMessage());
1483         }
1484     }
1485
1486     //Add Scopes
1487     private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
1488         PolicyController controller = getPolicyControllerInstance();
1489         String name = "";
1490         try {
1491             String userId = UserUtils.getUserSession(request).getOrgUserId();
1492             String path = params.getString("path");
1493             try{
1494                 if(params.has("subScopename")){
1495                     if(! "".equals(params.getString("subScopename"))) {
1496                         name = params.getString("path").replace("/", File.separator) + File.separator +params.getString("subScopename");
1497                     }
1498                 }else{
1499                     name = params.getString("name");
1500                 }
1501             }catch(Exception e){
1502                 name = params.getString("name");
1503                 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e);
1504             }
1505             String validateName;
1506             if(name.contains(File.separator)){
1507                 validateName = name.substring(name.lastIndexOf(File.separator)+1);
1508             }else{
1509                 validateName = name;
1510             }
1511             if(!name.isEmpty()){
1512                 String validate = PolicyUtils.policySpecialCharValidator(validateName);
1513                 if(!validate.contains("success")){
1514                     return error(validate);
1515                 }
1516             }
1517             LOGGER.debug("addFolder path: {} name: {}" + path +name);
1518             if(! "".equals(name)){
1519                 if(name.startsWith(File.separator)){
1520                     name = name.substring(1);
1521                 }
1522                 PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, "scopeName", name);
1523                 if(entity == null){
1524                     UserInfo userInfo = new UserInfo();
1525                     userInfo.setUserLoginId(userId);
1526                     PolicyEditorScopes newScope = new PolicyEditorScopes();
1527                     newScope.setScopeName(name);
1528                     newScope.setUserCreatedBy(userInfo);
1529                     newScope.setUserModifiedBy(userInfo);
1530                     controller.saveData(newScope);
1531                 }else{
1532                     return error("Scope Already Exists");
1533                 }
1534             }
1535             return success();
1536         } catch (Exception e) {
1537             LOGGER.error("addFolder", e);
1538             return error(e.getMessage());
1539         }
1540     }
1541
1542     //Return Error Object
1543     private JSONObject error(String msg) throws ServletException {
1544         try {
1545             JSONObject result = new JSONObject();
1546             result.put("success", false);
1547             result.put("error", msg);
1548             return new JSONObject().put(RESULT, result);
1549         } catch (JSONException e) {
1550             throw new ServletException(e);
1551         }
1552     }
1553
1554     //Return Success Object
1555     private JSONObject success() throws ServletException {
1556         try {
1557             JSONObject result = new JSONObject();
1558             result.put("success", true);
1559             result.put("error", (Object) null);
1560             return new JSONObject().put(RESULT, result);
1561         } catch (JSONException e) {
1562             throw new ServletException(e);
1563         }
1564     }
1565
1566     private PolicyController getPolicyControllerInstance(){
1567         return policyController != null ? getPolicyController() : new PolicyController();
1568     }
1569
1570     public String getTestUserId() {
1571         return testUserId;
1572     }
1573
1574     public static void setTestUserId(String testUserId) {
1575         PolicyManagerServlet.testUserId = testUserId;
1576     }
1577 }