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