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