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