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