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