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