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