Merge "Fixes for eclipse warnings unused variables"
[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()){
740                                 if(scopes.contains(scopeNameValue)){
741                                         JSONObject el = new JSONObject();
742                                         el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1)); 
743                                         el.put("date", policy.getModifiedDate());
744                                         el.put("version", policy.getActiveVersion());
745                                         el.put("size", "");
746                                         el.put("type", "file");
747                                         el.put("createdBy", getUserName(policy.getCreatedBy()));
748                                         el.put("modifiedBy", getUserName(policy.getModifiedBy()));
749                                         resultList.add(el);
750                                 }
751                         }
752                 }       
753         }
754
755         private String getUserName(String loginId){
756                 PolicyController controller = getPolicyControllerInstance();
757                 UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
758                 if(userInfo == null){
759                         return SUPERADMIN;
760                 }
761                 return userInfo.getUserName();
762         }
763
764         //Rename Policy
765         private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
766                 try {
767                         boolean isActive = false;
768                         List<String> policyActiveInPDP = new ArrayList<>();
769                         Set<String>  scopeOfPolicyActiveInPDP = new HashSet<>();
770                         String userId = UserUtils.getUserSession(request).getOrgUserId();
771                         String oldPath = params.getString("path");
772                         String newPath = params.getString("newPath");
773                         oldPath = oldPath.substring(oldPath.indexOf("/")+1);
774                         newPath = newPath.substring(newPath.indexOf("/")+1);
775                         if(oldPath.endsWith(".xml")){
776                                 JSONObject result = policyRename(oldPath, newPath, userId);
777                                 if(!(Boolean)(result.getJSONObject("result").get("success"))){
778                                         return result;
779                                 }
780                         }else{
781                                 String scopeName = oldPath;
782                                 String newScopeName = newPath;
783                                 if(scopeName.contains("/")){
784                                         scopeName = scopeName.replace("/", File.separator);
785                                         newScopeName = newScopeName.replace("/", File.separator);
786                                 }
787                                 if(scopeName.contains("\\")){
788                                         scopeName = scopeName.replace("\\", "\\\\\\\\");
789                                         newScopeName = newScopeName.replace("\\", "\\\\\\\\");
790                                 }
791                                 PolicyController controller = getPolicyControllerInstance();
792                                 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
793                                 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
794                                 SimpleBindings pvParams = new SimpleBindings();
795                                 pvParams.put("scopeName", scopeName + "%");
796                                 List<Object> activePolicies = controller.getDataByQuery(query, pvParams);
797                                 List<Object> scopesList = controller.getDataByQuery(scopeNamequery, pvParams);
798                                 for(Object object : activePolicies){
799                                         PolicyVersion activeVersion = (PolicyVersion) object;
800                                         String policyOldPath = activeVersion.getPolicyName().replace(File.separator, "/") + "." + activeVersion.getActiveVersion() + ".xml";
801                                         String policyNewPath = policyOldPath.replace(oldPath, newPath);
802                                         JSONObject result = policyRename(policyOldPath, policyNewPath, userId);
803                                         if(!(Boolean)(result.getJSONObject("result").get("success"))){
804                                                 isActive = true;
805                                                 policyActiveInPDP.add(policyOldPath);
806                                                 String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf("/"));
807                                                 scopeOfPolicyActiveInPDP.add(scope.replace("/", File.separator));
808                                         }
809                                 }
810                                 boolean rename = false;
811                                 if(activePolicies.size() != policyActiveInPDP.size()){
812                                         rename = true;
813                                 }
814         
815                                 UserInfo userInfo = new UserInfo();
816                                 userInfo.setUserLoginId(userId);
817                                 if(policyActiveInPDP.size() == 0){
818                                         renameScope(scopesList, scopeName, newScopeName, controller);   
819                                 }else if(rename){
820                                         renameScope(scopesList, scopeName, newScopeName, controller);
821                                         for(String scope : scopeOfPolicyActiveInPDP){
822                                                 PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes();
823                                                 editorScopeEntity.setScopeName(scope.replace("\\", "\\\\\\\\"));
824                                                 editorScopeEntity.setUserCreatedBy(userInfo);
825                                                 editorScopeEntity.setUserModifiedBy(userInfo);
826                                                 controller.saveData(editorScopeEntity);
827                                         }
828                                 }
829                                 if(isActive){
830                                         return error("The Following policies rename failed. Since they are active in PDP Groups" +policyActiveInPDP);
831                                 }       
832                         }
833                         return success();
834                 } catch (Exception e) {
835                         LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
836                         return error(e.getMessage());
837                 }
838         }
839         
840         private void renameScope(List<Object> scopesList, String scopeName, String newScopeName, PolicyController controller){
841                 for(Object object : scopesList){
842                         PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object;
843                         if(scopeName.contains("\\\\\\\\")){
844                                 scopeName = scopeName.replace("\\\\\\\\", File.separator);
845                                 newScopeName = newScopeName.replace("\\\\\\\\", File.separator);
846                         }
847                         String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName);
848                         editorScopeEntity.setScopeName(scope);
849                         controller.updateData(editorScopeEntity);
850                 }
851         }
852         
853         private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
854                 try {
855                         PolicyEntity entity = null;
856                         PolicyController controller = getPolicyControllerInstance();
857
858                         String policyVersionName = newPath.replace(".xml", "");
859                         String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")).replace("/", File.separator);
860
861                         String oldpolicyVersionName = oldPath.replace(".xml", "");
862                         String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf(".")).replace("/", File.separator);
863
864                         String newpolicyName = newPath.replace("/", ".");
865                         String newPolicyCheck = newpolicyName;
866                         if(newPolicyCheck.contains("Config_")){
867                                 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
868                         }else if(newPolicyCheck.contains("Action_")){
869                                 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
870                         }else if(newPolicyCheck.contains("Decision_")){
871                                 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
872                         }
873                         String[] newPolicySplit = newPolicyCheck.split(":");
874
875                         String orignalPolicyName = oldPath.replace("/", ".");
876                         String oldPolicyCheck = orignalPolicyName;
877                         if(oldPolicyCheck.contains("Config_")){
878                                 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
879                         }else if(oldPolicyCheck.contains("Action_")){
880                                 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
881                         }else if(oldPolicyCheck.contains("Decision_")){
882                                 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
883                         }
884                         String[] oldPolicySplit = oldPolicyCheck.split(":");
885
886                         //Check PolicyEntity table with newPolicy Name
887                         String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_1";
888                         SimpleBindings policyParams = new SimpleBindings();
889                         policyParams.put("newPolicySplit_1", newPolicySplit[1]);
890                         policyParams.put("newPolicySplit_0", newPolicySplit[0]);
891                         List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
892                         if(!queryData.isEmpty()){
893                                 entity = (PolicyEntity) queryData.get(0);
894                                 return error("Policy rename failed. Since, the policy with same name already exists.");
895                         }
896
897                         //Query the Policy Entity with oldPolicy Name
898                         String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf("."));
899                         String oldpolicyEntityquery = "FROM PolicyEntity where policyName like :policyEntityCheck and scope = :oldPolicySplit_0";
900                         SimpleBindings params = new SimpleBindings();
901                         params.put("policyEntityCheck", policyEntityCheck + "%");
902                         params.put("oldPolicySplit_0", oldPolicySplit[0]);
903                         List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery, params);
904                         if(!oldEntityData.isEmpty()){
905                                 String groupQuery = "FROM PolicyGroupEntity where (";
906                                 SimpleBindings geParams = new SimpleBindings();
907                                 for(int i=0; i<oldEntityData.size(); i++){
908                                         entity = (PolicyEntity) oldEntityData.get(i);
909                                         if(i == 0){
910                                                 groupQuery = groupQuery +  "policyid = :policyId";
911                                                 geParams.put("policyId", entity.getPolicyId());
912                                         }else{
913                                                 groupQuery = groupQuery +  " or policyid = :policyId" + i;
914                                                 geParams.put("policyId" + i, entity.getPolicyId());
915                                         }
916                                 }
917                                 groupQuery = groupQuery + ")";
918                                 List<Object> groupEntityData = controller.getDataByQuery(groupQuery, geParams);
919                                 if(groupEntityData.size() > 0){
920                                         return error("Policy rename failed. Since the policy or its version is active in PDP Groups.");
921                                 }
922                                 for(int i=0; i<oldEntityData.size(); i++){
923                                         entity = (PolicyEntity) oldEntityData.get(i);
924                                         checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0] , newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
925                                 }
926                         }else{
927                                 return error("Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin.");
928                         }
929                         
930                         return success();
931                 } catch (Exception e) {
932                         LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
933                         return error(e.getMessage());
934                 }
935         }
936
937         private JSONObject checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, String oldScope, String removeoldPolicyExtension, 
938                         String policyName, String  newpolicyName, String oldpolicyName, String userId) throws ServletException{
939                 try {
940                         ConfigurationDataEntity configEntity = entity.getConfigurationData();
941                         ActionBodyEntity actionEntity = entity.getActionBodyEntity();
942                         PolicyController controller = getPolicyControllerInstance();
943
944                         String oldPolicyNameWithoutExtension = removeoldPolicyExtension;
945                         String newPolicyNameWithoutExtension = removenewPolicyExtension;
946                         if(removeoldPolicyExtension.endsWith(".xml")){
947                                 oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf("."));
948                                 newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf("."));
949                         }
950                         entity.setPolicyName(entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
951                         entity.setPolicyData(entity.getPolicyData().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
952                         entity.setScope(newScope);
953                         entity.setModifiedBy(userId);
954                         if(newpolicyName.contains("Config_")){
955                                 String oldConfigurationName = configEntity.getConfigurationName();
956                                 configEntity.setConfigurationName(configEntity.getConfigurationName().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
957                                 controller.updateData(configEntity);
958                                 String newConfigurationName = configEntity.getConfigurationName();
959                                 File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName);
960                                 if(file.exists()){
961                                         File renamefile = new File(PolicyController.getConfigHome() + File.separator + newConfigurationName);
962                                         file.renameTo(renamefile);
963                                 }
964                         }else if(newpolicyName.contains("Action_")){
965                                 String oldConfigurationName = actionEntity.getActionBodyName();
966                                 actionEntity.setActionBody(actionEntity.getActionBody().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
967                                 controller.updateData(actionEntity);
968                                 String newConfigurationName = actionEntity.getActionBodyName();
969                                 File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName);
970                                 if(file.exists()){
971                                         File renamefile = new File(PolicyController.getActionHome() + File.separator + newConfigurationName);
972                                         file.renameTo(renamefile);
973                                 }
974                         }
975                         controller.updateData(entity);
976
977                         PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldpolicyName);
978                         versionEntity.setPolicyName(policyName);
979                         versionEntity.setModifiedBy(userId);
980                         controller.updateData(versionEntity);
981                         String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator)+1);
982                         String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
983                         if(movePolicyCheck.equals(moveOldPolicyCheck)){
984                                 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move");
985                         }else{
986                                 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename");
987                         }
988                         return success();
989                 } catch (Exception e) {
990                         LOGGER.error("Exception Occured"+e);
991                         return error(e.getMessage());
992                 }
993         }
994
995         private JSONObject cloneRecord(String newpolicyName, String oldScope, String removeoldPolicyExtension, String newScope, String removenewPolicyExtension, PolicyEntity entity, String userId) throws ServletException{
996                 FileWriter fw = null;
997                 String queryEntityName = null;
998                 PolicyController controller = getPolicyControllerInstance();
999                 PolicyEntity cloneEntity = new PolicyEntity();
1000                 cloneEntity.setPolicyName(newpolicyName);
1001                 removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
1002                 removenewPolicyExtension = removenewPolicyExtension.replace(".xml", "");
1003                 cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope+"."+removeoldPolicyExtension, newScope+"."+removenewPolicyExtension));
1004                 cloneEntity.setScope(entity.getScope());
1005                 String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
1006                 String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
1007                 if(newpolicyName.contains("Config_")){
1008                         ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
1009                         configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1010                         queryEntityName = configurationDataEntity.getConfigurationName();
1011                         configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody());
1012                         configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType());
1013                         configurationDataEntity.setDeleted(false);
1014                         configurationDataEntity.setCreatedBy(userId);
1015                         configurationDataEntity.setModifiedBy(userId);
1016                         controller.saveData(configurationDataEntity);
1017                         ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
1018                         cloneEntity.setConfigurationData(configEntiy);
1019                         String newConfigurationName = configEntiy.getConfigurationName();
1020                         try {
1021                                 fw = new FileWriter(PolicyController.getConfigHome() + File.separator + newConfigurationName);
1022                                 BufferedWriter bw = new BufferedWriter(fw);
1023                                 bw.write(configEntiy.getConfigBody());
1024                                 bw.close();
1025                         } catch (IOException e) {
1026                                 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1027                         }
1028                 }else if(newpolicyName.contains("Action_")){
1029                         ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
1030                         actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1031                         queryEntityName = actionBodyEntity.getActionBodyName();
1032                         actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody());
1033                         actionBodyEntity.setDeleted(false);
1034                         actionBodyEntity.setCreatedBy(userId);
1035                         actionBodyEntity.setModifiedBy(userId);
1036                         controller.saveData(actionBodyEntity);
1037                         ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class, "actionBodyName", queryEntityName);
1038                         cloneEntity.setActionBodyEntity(actionEntiy);
1039                         String newConfigurationName = actionEntiy.getActionBodyName();
1040                         try {
1041                                 fw = new FileWriter(PolicyController.getActionHome() + File.separator + newConfigurationName);
1042                                 BufferedWriter bw = new BufferedWriter(fw);
1043                                 bw.write(actionEntiy.getActionBody());
1044                                 bw.close();
1045                         } catch (IOException e) {
1046                                 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1047                         }
1048                 }
1049                 if(fw != null){
1050                         try {
1051                                 fw.close();
1052                         } catch (IOException e) {
1053                                 LOGGER.error("Exception Occured While closing the File input stream"+e);
1054                         }
1055                 }
1056                 cloneEntity.setDeleted(entity.isDeleted());
1057                 cloneEntity.setCreatedBy(userId);
1058                 cloneEntity.setModifiedBy(userId);
1059                 controller.saveData(cloneEntity);
1060
1061                 return success();
1062         }
1063
1064         //Clone the Policy
1065         private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
1066                 try {
1067                         String userId = UserUtils.getUserSession(request).getOrgUserId();
1068                         String oldPath = params.getString("path");
1069                         String newPath = params.getString("newPath");
1070                         oldPath = oldPath.substring(oldPath.indexOf("/")+1);
1071                         newPath = newPath.substring(newPath.indexOf("/")+1);
1072
1073                         String policyVersionName = newPath.replace(".xml", "");
1074                         String version = policyVersionName.substring(policyVersionName.indexOf(".")+1);
1075                         String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")).replace("/", File.separator);
1076
1077                         String newpolicyName = newPath.replace("/", ".");
1078
1079                         String orignalPolicyName = oldPath.replace("/", ".");
1080
1081                         String newPolicyCheck = newpolicyName;
1082                         if(newPolicyCheck.contains("Config_")){
1083                                 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
1084                         }else if(newPolicyCheck.contains("Action_")){
1085                                 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
1086                         }else if(newPolicyCheck.contains("Decision_")){
1087                                 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
1088                         }
1089                         String[] newPolicySplit = newPolicyCheck.split(":");
1090
1091                         String oldPolicyCheck = orignalPolicyName;
1092                         if(oldPolicyCheck.contains("Config_")){
1093                                 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
1094                         }else if(oldPolicyCheck.contains("Action_")){
1095                                 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
1096                         }else if(oldPolicyCheck.contains("Decision_")){
1097                                 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
1098                         }
1099                         String[] oldPolicySplit = oldPolicyCheck.split(":");
1100
1101                         PolicyController controller = getPolicyControllerInstance();
1102
1103                         PolicyEntity entity = null;
1104                         boolean success = false;
1105
1106                         //Check PolicyEntity table with newPolicy Name
1107                         String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
1108                         SimpleBindings policyParams = new SimpleBindings();
1109                         policyParams.put("newPolicySplit_1", newPolicySplit[1]);
1110                         policyParams.put("newPolicySplit_0", newPolicySplit[0]);
1111                         List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
1112                         if(!queryData.isEmpty()){
1113                                 return error("Policy already exists with same name");
1114                         }
1115
1116                         //Query the Policy Entity with oldPolicy Name
1117                         policyEntityquery = "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0";
1118                         SimpleBindings peParams = new SimpleBindings();
1119                         peParams.put("oldPolicySplit_1", oldPolicySplit[1]);
1120                         peParams.put("oldPolicySplit_0", oldPolicySplit[0]);
1121                         queryData = controller.getDataByQuery(policyEntityquery, peParams);
1122                         if(!queryData.isEmpty()){
1123                                 entity = (PolicyEntity) queryData.get(0);
1124                         }
1125                         if(entity != null){
1126                                 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1],  newPolicySplit[0], newPolicySplit[1], entity, userId);
1127                                 success = true;
1128                         }
1129                         
1130                         if(success){
1131                                 PolicyVersion entityItem = new PolicyVersion();
1132                                 entityItem.setActiveVersion(Integer.parseInt(version));
1133                                 entityItem.setHigherVersion(Integer.parseInt(version));
1134                                 entityItem.setPolicyName(policyName);
1135                                 entityItem.setCreatedBy(userId);
1136                                 entityItem.setModifiedBy(userId);
1137                                 controller.saveData(entityItem);
1138                         }
1139
1140                         LOGGER.debug("copy from: {} to: {}" + oldPath +newPath);
1141
1142                         return success();
1143                 } catch (Exception e) {
1144                         LOGGER.error("copy", e);
1145                         return error(e.getMessage());
1146                 }
1147         }
1148
1149         //Delete Policy or Scope Functionality
1150         private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
1151                 PolicyController controller = getPolicyControllerInstance();
1152                 PolicyRestController restController = new PolicyRestController();
1153                 PolicyEntity policyEntity = null;
1154                 String policyNamewithoutExtension;
1155                 try {
1156                         String userId = UserUtils.getUserSession(request).getOrgUserId();
1157                         String deleteVersion = "";
1158                         String path = params.getString("path");
1159                         LOGGER.debug("delete {}" +path);
1160                         if(params.has("deleteVersion")){
1161                                 deleteVersion  = params.getString("deleteVersion");
1162                         }
1163                         path = path.substring(path.indexOf("/")+1);
1164                         String policyNamewithExtension = path.replace("/", File.separator);
1165                         String policyVersionName = policyNamewithExtension.replace(".xml", "");
1166                         String query = "";
1167                         SimpleBindings policyParams = new SimpleBindings();
1168                         if(path.endsWith(".xml")){
1169                                 policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf("."));
1170                                 policyNamewithoutExtension = policyNamewithoutExtension.replace(File.separator, ".");
1171                                 String splitPolicyName = null;
1172                                 if(policyNamewithoutExtension.contains("Config_")){
1173                                         splitPolicyName = policyNamewithoutExtension.replace(".Config_", ":Config_");
1174                                 }else if(policyNamewithoutExtension.contains("Action_")){
1175                                         splitPolicyName = policyNamewithoutExtension.replace(".Action_", ":Action_");
1176                                 }else if(policyNamewithoutExtension.contains("Decision_")){
1177                                         splitPolicyName = policyNamewithoutExtension.replace(".Decision_", ":Decision_");
1178                                 }
1179                                 String[] split = splitPolicyName.split(":");
1180                                 query = "FROM PolicyEntity where policyName like split_1 and scope = split_0";
1181                                 policyParams.put("split_1", split[1] + "%");
1182                                 policyParams.put("split_0", split[0]);
1183                         }else{
1184                                 policyNamewithoutExtension = path.replace(File.separator, ".");
1185                                 query = "FROM PolicyEntity where scope like :policyNamewithoutExtension";
1186                                 policyParams.put("policyNamewithoutExtension", policyNamewithoutExtension + "%");
1187                         }
1188                         
1189                         List<Object> policyEntityobjects = controller.getDataByQuery(query, policyParams);
1190                         String activePolicyName = null;
1191                         boolean pdpCheck = false;
1192                         if(path.endsWith(".xml")){
1193                                 policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator);
1194                                 int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf(".")+1));
1195                                 if("ALL".equals(deleteVersion)){
1196                                         if(!policyEntityobjects.isEmpty()){
1197                                                 for(Object object : policyEntityobjects){
1198                                                         policyEntity = (PolicyEntity) object;
1199                                                         String groupEntityquery = "from PolicyGroupEntity where policyid = :policyId";
1200                                                         SimpleBindings pgeParams = new SimpleBindings();
1201                                                         pgeParams.put("policyId", policyEntity.getPolicyId());
1202                                                         List<Object> groupobject = controller.getDataByQuery(groupEntityquery, pgeParams);
1203                                                         if(!groupobject.isEmpty()){
1204                                                                 pdpCheck = true;
1205                                                                 activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName();
1206                                                         }else{
1207                                                                 //Delete the entity from Elastic Search Database
1208                                                                 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1209                                                                 restController.deleteElasticData(searchFileName);
1210                                                                 //Delete the entity from Policy Entity table
1211                                                                 controller.deleteData(policyEntity);
1212                                                                 if(policyNamewithoutExtension.contains("Config_")){
1213                                                                         controller.deleteData(policyEntity.getConfigurationData());
1214                                                                 }else if(policyNamewithoutExtension.contains("Action_")){
1215                                                                         controller.deleteData(policyEntity.getActionBodyEntity());
1216                                                                 }                       
1217                                                         }
1218                                                 }
1219                                         }
1220                                         //Policy Notification
1221                                         PolicyVersion versionEntity = new PolicyVersion();
1222                                         versionEntity.setPolicyName(policyNamewithoutExtension);
1223                                         versionEntity.setModifiedBy(userId);
1224                                         controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll");
1225                                         if(pdpCheck){
1226                                                 //Delete from policyVersion table
1227                                                 String getActivePDPPolicyVersion = activePolicyName.replace(".xml", "");
1228                                                 getActivePDPPolicyVersion = getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf(".")+1);
1229                                                 String policyVersionQuery = "update PolicyVersion set active_version='"+getActivePDPPolicyVersion+"' , highest_version='"+getActivePDPPolicyVersion+"'  where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1230                                                 if(policyVersionQuery != null){
1231                                                         controller.executeQuery(policyVersionQuery);
1232                                                 }
1233                                                 return error("Policies with Same name has been deleted. Except the Active Policy in PDP.     PolicyName: "+activePolicyName);
1234                                         }else{
1235                                                 //No Active Policy in PDP. So, deleting all entries from policyVersion table
1236                                                 String policyVersionQuery = "delete from PolicyVersion  where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1237                                                 if(policyVersionQuery != null){
1238                                                         controller.executeQuery(policyVersionQuery);
1239                                                 }
1240                                         }
1241                                 }else if("CURRENT".equals(deleteVersion)){
1242                                         String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1);
1243                                         String currentVersionScope = policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator)).replace(File.separator, ".");
1244                                         query = "FROM PolicyEntity where policyName = :currentVersionPolicyName and scope = :currentVersionScope";
1245                                         
1246                                         SimpleBindings peParams = new SimpleBindings();
1247                                         peParams.put("currentVersionPolicyName", currentVersionPolicyName);
1248                                         peParams.put("currentVersionScope", currentVersionScope);
1249                                         
1250                                         List<Object> policyEntitys = controller.getDataByQuery(query, peParams);
1251                                         if(!policyEntitys.isEmpty()){
1252                                                 policyEntity = (PolicyEntity) policyEntitys.get(0);
1253                                         }
1254                                         if(policyEntity != null){
1255                                                 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId and policyid > 0";
1256                                                 SimpleBindings geParams = new SimpleBindings();
1257                                                 geParams.put("policyEntityId", policyEntity.getPolicyId());
1258                                                 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1259                                                 if(groupobject.isEmpty()){
1260                                                         //Delete the entity from Elastic Search Database
1261                                                         String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1262                                                         restController.deleteElasticData(searchFileName);
1263                                                         //Delete the entity from Policy Entity table
1264                                                         controller.deleteData(policyEntity);
1265                                                         if(policyNamewithoutExtension.contains("Config_")){
1266                                                                 controller.deleteData(policyEntity.getConfigurationData());
1267                                                         }else if(policyNamewithoutExtension.contains("Action_")){
1268                                                                 controller.deleteData(policyEntity.getActionBodyEntity());
1269                                                         }
1270                                                         
1271                                                         if(version > 1){
1272                                                                 int highestVersion = 0; 
1273                                                                 if(!policyEntityobjects.isEmpty()){
1274                                                                         for(Object object : policyEntityobjects){
1275                                                                                 policyEntity = (PolicyEntity) object;
1276                                                                                 String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
1277                                                                                 int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf(".")+1));
1278                                                                                 if(policyEntityVersion > highestVersion && policyEntityVersion != version){
1279                                                                                         highestVersion = policyEntityVersion;
1280                                                                                 }
1281                                                                         }
1282                                                                 }
1283
1284                                                                 //Policy Notification
1285                                                                 PolicyVersion entity = new PolicyVersion();
1286                                                                 entity.setPolicyName(policyNamewithoutExtension);
1287                                                                 entity.setActiveVersion(highestVersion);
1288                                                                 entity.setModifiedBy(userId);
1289                                                                 controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne");
1290
1291                                                                 String updatequery = "update PolicyVersion set active_version='"+highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"'";
1292                                                                 controller.executeQuery(updatequery);
1293                                                         }else{
1294                                                                 String policyVersionQuery = "delete from PolicyVersion  where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1295                                                                 if(policyVersionQuery != null){
1296                                                                         controller.executeQuery(policyVersionQuery);
1297                                                                 }
1298                                                         }
1299                                                 }else{
1300                                                         return error("Policy can't be deleted, it is active in PDP Groups.     PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'");
1301                                                 }
1302                                         }
1303                                 }       
1304                         }else{
1305                                 List<String> activePoliciesInPDP = new ArrayList<String>();
1306                                 if(!policyEntityobjects.isEmpty()){
1307                                         for(Object object : policyEntityobjects){
1308                                                 policyEntity = (PolicyEntity) object;
1309                                                 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId";
1310                                                 SimpleBindings geParams = new SimpleBindings();
1311                                                 geParams.put("policyEntityId", policyEntity.getPolicyId());
1312                                                 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1313                                                 if(!groupobject.isEmpty()){
1314                                                         pdpCheck = true;
1315                                                         activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName());
1316                                                 }else{
1317                                                         //Delete the entity from Elastic Search Database
1318                                                         String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1319                                                         restController.deleteElasticData(searchFileName);
1320                                                         //Delete the entity from Policy Entity table
1321                                                         controller.deleteData(policyEntity);
1322                                                         policyNamewithoutExtension = policyEntity.getPolicyName();
1323                                                         if(policyNamewithoutExtension.contains("Config_")){
1324                                                                 controller.deleteData(policyEntity.getConfigurationData());
1325                                                         }else if(policyNamewithoutExtension.contains("Action_")){
1326                                                                 controller.deleteData(policyEntity.getActionBodyEntity());
1327                                                         }
1328                                                 }
1329                                         }
1330                                         //Delete from policyVersion and policyEditor Scope table
1331                                         String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1332                                         controller.executeQuery(policyVersionQuery);
1333                                         
1334                                         //Policy Notification
1335                                         PolicyVersion entity = new PolicyVersion();
1336                                         entity.setPolicyName(path);
1337                                         entity.setModifiedBy(userId);
1338                                         controller.watchPolicyFunction(entity, path, "DeleteScope");
1339                                         if(pdpCheck){
1340                                                 //Add Active Policies List to PolicyVersionTable
1341                                                 for(int i =0; i < activePoliciesInPDP.size(); i++){
1342                                                         String activePDPPolicyName = activePoliciesInPDP.get(i).replace(".xml", "");
1343                                                         int activePDPPolicyVersion = Integer.parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf(".")+1));
1344                                                         activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf(".")).replace(".", File.separator);
1345                                                         PolicyVersion insertactivePDPVersion = new PolicyVersion();
1346                                                         insertactivePDPVersion.setPolicyName(activePDPPolicyName);
1347                                                         insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion);
1348                                                         insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion);
1349                                                         insertactivePDPVersion.setCreatedBy(userId);
1350                                                         insertactivePDPVersion.setModifiedBy(userId);
1351                                                         controller.saveData(insertactivePDPVersion);
1352                                                 }
1353                                                 
1354                                                 return error("All the Policies has been deleted in Scope. Except the following list of Policies:"+activePoliciesInPDP);
1355                                         }else{
1356                                                 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1357                                             controller.executeQuery(policyScopeQuery);
1358                                         }
1359                                 }else{
1360                                         String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1361                                         controller.executeQuery(policyScopeQuery);
1362                                 }
1363                         }
1364                         return success();
1365                 } catch (Exception e) {
1366                         LOGGER.error("delete", e);
1367                         return error(e.getMessage());
1368                 }
1369         }
1370
1371         //Edit the Policy
1372         private JSONObject editFile(JSONObject params) throws ServletException {
1373                 // get content
1374                 try {
1375                         PolicyController controller = getPolicyControllerInstance();
1376                         String mode = params.getString("mode");
1377                         String path = params.getString("path");
1378                         LOGGER.debug("editFile path: {}"+ path);
1379                         
1380                         String domain = path.substring(1, path.lastIndexOf("/"));
1381                         domain = domain.replace("/", ".");
1382                         
1383                         path = path.substring(1);
1384                         path = path.replace("/", ".");
1385                         String dbCheckName = path;
1386                         if(dbCheckName.contains("Config_")){
1387                                 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
1388                         }else if(dbCheckName.contains("Action_")){
1389                                 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
1390                         }else if(dbCheckName.contains("Decision_")){
1391                                 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
1392                         }
1393                         
1394                         String[] split = dbCheckName.split(":");
1395                         String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
1396                         SimpleBindings peParams = new SimpleBindings();
1397                         peParams.put("split_1", split[1]);
1398                         peParams.put("split_0", split[0]);
1399                         List<Object> queryData = controller.getDataByQuery(query, peParams);
1400                         PolicyEntity entity = (PolicyEntity) queryData.get(0);
1401                         InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
1402
1403
1404                         Object policy = XACMLPolicyScanner.readPolicy(stream);
1405                         PolicyRestAdapter policyAdapter  = new PolicyRestAdapter();             
1406                         policyAdapter.setData(policy);
1407
1408                         if("viewPolicy".equalsIgnoreCase(mode)){
1409                                 policyAdapter.setReadOnly(true);
1410                                 policyAdapter.setEditPolicy(false);
1411                         }else{
1412                                 policyAdapter.setReadOnly(false);
1413                                 policyAdapter.setEditPolicy(true);
1414                         }
1415                         policyAdapter.setDomain(domain);
1416                         policyAdapter.setDomainDir(domain);
1417                         policyAdapter.setPolicyData(policy);
1418                         String policyName = path.replace(".xml", "");
1419                         policyName = policyName.substring(0, policyName.lastIndexOf("."));
1420                         policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf(".")+1));
1421
1422                         PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance();
1423                         setpolicyAdapter.configure(policyAdapter,entity);
1424                         
1425                         policyAdapter.setParentPath(null);
1426                         ObjectMapper mapper = new ObjectMapper();
1427                         String json = mapper.writeValueAsString(policyAdapter);
1428                         JsonNode jsonNode = mapper.readTree(json);
1429
1430                         return new JSONObject().put(RESULT, jsonNode);
1431                 } catch (Exception e) {
1432                         LOGGER.error("editFile", e);
1433                         return error(e.getMessage());
1434                 }
1435         }
1436
1437         //Add Scopes
1438         private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
1439                 PolicyController controller = getPolicyControllerInstance();
1440                 String name = "";
1441                 try {
1442                         String userId = UserUtils.getUserSession(request).getOrgUserId();
1443                         String path = params.getString("path");
1444                         try{
1445                                 if(params.has("subScopename")){
1446                                         if(!params.getString("subScopename").equals("")){
1447                                                 name = params.getString("path").replace("/", File.separator) + File.separator +params.getString("subScopename");
1448                                         }
1449                                 }else{
1450                                         name = params.getString("name");
1451                                 }       
1452                         }catch(Exception e){
1453                                 name = params.getString("name");
1454                                 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e);
1455                         }
1456                         String validateName;
1457                         if(name.contains(File.separator)){
1458                                 validateName = name.substring(name.lastIndexOf(File.separator)+1);
1459                         }else{
1460                                 validateName = name;
1461                         }
1462                         if(!name.isEmpty()){
1463                                 String validate = PolicyUtils.emptyPolicyValidator(validateName);
1464                                 if(!validate.contains("success")){
1465                                         return error(validate);
1466                                 } 
1467                         }
1468                         LOGGER.debug("addFolder path: {} name: {}" + path +name);
1469                         if(!name.equals("")){
1470                                 if(name.startsWith(File.separator)){
1471                                         name = name.substring(1);
1472                                 }
1473                                 PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, "scopeName", name);
1474                                 if(entity == null){
1475                                         UserInfo userInfo = new UserInfo();
1476                                         userInfo.setUserLoginId(userId);
1477                                         PolicyEditorScopes newScope = new PolicyEditorScopes();
1478                                         newScope.setScopeName(name);
1479                                         newScope.setUserCreatedBy(userInfo);
1480                                         newScope.setUserModifiedBy(userInfo);
1481                                         controller.saveData(newScope);  
1482                                 }else{
1483                                         return error("Scope Already Exists");
1484                                 }
1485                         }
1486                         return success();
1487                 } catch (Exception e) {
1488                         LOGGER.error("addFolder", e);
1489                         return error(e.getMessage());
1490                 }
1491         }
1492
1493         //Return Error Object
1494         private JSONObject error(String msg) throws ServletException {
1495                 try {
1496                         JSONObject result = new JSONObject();
1497                         result.put("success", false);
1498                         result.put("error", msg);
1499                         return new JSONObject().put(RESULT, result);
1500                 } catch (JSONException e) {
1501                         throw new ServletException(e);
1502                 }
1503         }
1504
1505         //Return Success Object
1506         private JSONObject success() throws ServletException {
1507                 try {
1508                         JSONObject result = new JSONObject();
1509                         result.put("success", true);
1510                         result.put("error", (Object) null);
1511                         return new JSONObject().put(RESULT, result);
1512                 } catch (JSONException e) {
1513                         throw new ServletException(e);
1514                 }
1515         }
1516         
1517         private PolicyController getPolicyControllerInstance(){
1518                 return policyController != null ? getPolicyController() : new PolicyController();
1519         }
1520
1521         public String getTestUserId() {
1522                 return testUserId;
1523         }
1524
1525         public static void setTestUserId(String testUserId) {
1526                 PolicyManagerServlet.testUserId = testUserId;
1527         }
1528 }