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