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