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