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