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