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