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