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