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