Merge "Continue addressing technical debt for ONAP-XACML"
[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                         String activeVersion = params.getString("activeVersion");
435                         String highestVersion = params.get("highestVersion").toString();
436                         if(Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)){
437                                 return error("The Version shouldn't be greater than Highest Value");
438                         }else{
439                                 activePolicy = policyName + "." + activeVersion + ".xml";
440                                 String dbCheckName = activePolicy.replace("/", ".");
441                                 if(dbCheckName.contains("Config_")){
442                                         dbCheckName = dbCheckName.replace(".Config_", ":Config_");
443                                 }else if(dbCheckName.contains("Action_")){
444                                         dbCheckName = dbCheckName.replace(".Action_", ":Action_");
445                                 }else if(dbCheckName.contains("Decision_")){
446                                         dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
447                                 }
448                                 String[] splitDBCheckName = dbCheckName.split(":");
449                                 String peQuery =   "FROM PolicyEntity where policyName = :splitDBCheckName_1 and scope = :splitDBCheckName_0";
450                                 SimpleBindings policyParams = new SimpleBindings();
451                                 policyParams.put("splitDBCheckName_1", splitDBCheckName[1]);
452                                 policyParams.put("splitDBCheckName_0", splitDBCheckName[0]);
453                                 List<Object> policyEntity = controller.getDataByQuery(peQuery, policyParams);
454                                 PolicyEntity pentity = (PolicyEntity) policyEntity.get(0);
455                                 if(pentity.isDeleted()){
456                                         return error("The Policy is Not Existing in Workspace");
457                                 }else{
458                                         if(policyName.contains("/")){
459                                                 policyName = policyName.replace("/", File.separator);
460                                         }
461                                         policyName = policyName.substring(policyName.indexOf(File.separator)+1);
462                                         if(policyName.contains("\\")){
463                                                 policyName = policyName.replace(File.separator, "\\");
464                                         }
465                                         policyName = splitDBCheckName[0].replace(".", File.separator)+File.separator+policyName;
466                                         String watchPolicyName = policyName;
467                                         if(policyName.contains("/")){
468                                                 policyName = policyName.replace("/", File.separator);
469                                         }
470                                         if(policyName.contains("\\")){
471                                                 policyName = policyName.replace("\\", "\\\\");
472                                         }
473                                         String query = "update PolicyVersion set active_version='"+activeVersion+"' where policy_name ='"+policyName+"'  and id >0";
474                                         //query the database
475                                         controller.executeQuery(query);
476                                         //Policy Notification
477                                         PolicyVersion entity = new PolicyVersion();
478                                         entity.setPolicyName(watchPolicyName);
479                                         entity.setActiveVersion(Integer.parseInt(activeVersion));
480                                         entity.setModifiedBy(userId);
481                                         controller.watchPolicyFunction(entity, activePolicy, "SwitchVersion");
482                                         return success();
483                                 }
484                         }
485                 }
486                 return controller.switchVersionPolicyContent(policyName);
487         }
488
489         //Describe Policy
490         private JSONObject describePolicy(JSONObject params) throws ServletException{
491                 JSONObject object = null;
492                 String path = params.getString("path");
493                 String policyName = null;
494                 if(path.startsWith("/")){
495                         path = path.substring(1);
496                         policyName = path.substring(path.lastIndexOf('/') +1);
497                         path = path.replace("/", ".");
498                 }else{
499                         path = path.replace("/", ".");
500                         policyName = path;
501                 }
502                 if(path.contains("Config_")){
503                         path = path.replace(".Config_", ":Config_");
504                 }else if(path.contains("Action_")){
505                         path = path.replace(".Action_", ":Action_");
506                 }else if(path.contains("Decision_")){
507                         path = path.replace(".Decision_", ":Decision_");
508                 }
509                 PolicyController controller = getPolicyControllerInstance();
510                 String[] split = path.split(":");
511                 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
512                 SimpleBindings peParams = new SimpleBindings();
513                 peParams.put("split_1", split[1]);
514                 peParams.put("split_0", split[0]);
515                 List<Object> queryData = null;
516                 if(PolicyController.isjUnit()){
517                         queryData = controller.getDataByQuery(query, null);
518                 }else{
519                         queryData = controller.getDataByQuery(query, peParams);
520                 }
521                 if(!queryData.isEmpty()){
522                         PolicyEntity entity = (PolicyEntity) queryData.get(0);
523                         File temp = null;
524                         BufferedWriter bw = null;
525                         try {
526                                 temp = File.createTempFile(policyName, ".tmp");
527                                 bw = new BufferedWriter(new FileWriter(temp));
528                                 bw.write(entity.getPolicyData());
529                                 bw.close();
530                                 object = HumanPolicyComponent.DescribePolicy(temp);
531                         } catch (IOException e) {
532                                 LOGGER.error("Exception Occured while Describing the Policy"+e);
533                         }finally{
534                                 if(temp != null){
535                                         temp.delete();
536                                 }
537                                 if(bw != null){
538                                         try {
539                                                 bw.close();
540                                         } catch (IOException e) {
541                                                 LOGGER.error("Exception Occured while Closing the File Writer"+e);
542                                         }
543                                 }
544                         }
545                 }else{
546                         return error("Error Occured while Describing the Policy");
547                 }
548
549                 return object;
550         }
551
552         //Get the List of Policies and Scopes for Showing in Editor tab
553         private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException {
554                 Set<String> scopes = null;
555                 List<String> roles = null;
556                 try {
557                         PolicyController controller = getPolicyControllerInstance();
558                         //Get the Login Id of the User from Request
559                         String testUserID = getTestUserId();
560                         String userId =  testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId();
561                         List<Object> userRoles = controller.getRoles(userId);
562                         Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
563                         roles = pair.u;
564                         scopes = pair.t;
565
566                         List<JSONObject> resultList = new ArrayList<>();
567                         boolean onlyFolders = params.getBoolean("onlyFolders");
568                         String path = params.getString("path");
569                         if(path.contains("..xml")){
570                                 path = path.replaceAll("..xml", "").trim();
571                         }
572
573                         if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
574                                 if(scopes.isEmpty()){
575                                         return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
576                                 }else{
577                                         if(!"/".equals(path)){
578                                                 String tempScope = path.substring(1, path.length());
579                                                 tempScope = tempScope.replace("/", File.separator);
580                                                 scopes.add(tempScope);
581                                         }
582                                 }
583                         }
584
585                         if("/".equals(path)){
586                                 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
587                                         List<Object> scopesList = queryPolicyEditorScopes(null);
588                                         for(Object list : scopesList){
589                                                 PolicyEditorScopes scope = (PolicyEditorScopes) list;
590                                                 if(!(scope.getScopeName().contains(File.separator))){
591                                                         JSONObject el = new JSONObject();
592                                                         el.put("name", scope.getScopeName());
593                                                         el.put("date", scope.getModifiedDate());
594                                                         el.put("size", "");
595                                                         el.put("type", "dir");
596                                                         el.put("createdBy", scope.getUserCreatedBy().getUserName());
597                                                         el.put("modifiedBy", scope.getUserModifiedBy().getUserName());
598                                                         resultList.add(el);
599                                                 }
600                                         }
601                                 }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){
602                                         for(Object scope : scopes){
603                                                 JSONObject el = new JSONObject();
604                                                 List<Object> scopesList = queryPolicyEditorScopes(scope.toString());
605                                                 if(!scopesList.isEmpty()){
606                                                         PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
607                                                         el.put("name", scopeById.getScopeName());
608                                                         el.put("date", scopeById.getModifiedDate());
609                                                         el.put("size", "");
610                                                         el.put("type", "dir");
611                                                         el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
612                                                         el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
613                                                         resultList.add(el);
614                                                 }
615                                         }
616                                 }
617                         }else{
618                                 try{
619                                         String scopeName = path.substring(path.indexOf('/') +1);
620                                         activePolicyList(scopeName, resultList, roles, scopes, onlyFolders);
621                                 } catch (Exception ex) {
622                                         LOGGER.error("Error Occured While reading Policy Files List"+ex );
623                                 }
624                         }
625
626                         return new JSONObject().put(RESULT, resultList);
627                 } catch (Exception e) {
628                         LOGGER.error("list", e);
629                         return error(e.getMessage());
630                 }
631         }
632
633         private List<Object> queryPolicyEditorScopes(String scopeName){
634                 String scopeNamequery;
635                 SimpleBindings params = new SimpleBindings();
636                 if(scopeName == null){
637                         scopeNamequery = "from PolicyEditorScopes";
638                 }else{
639                         scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
640                         params.put("scopeName", scopeName + "%");
641                 }
642                 PolicyController controller = getPolicyControllerInstance();
643                 List<Object> scopesList;
644                 if(PolicyController.isjUnit()){
645                         scopesList = controller.getDataByQuery(scopeNamequery, null);
646                 }else{
647                         scopesList = controller.getDataByQuery(scopeNamequery, params);
648                 }
649                 return  scopesList;
650         }
651
652         //Get Active Policy List based on Scope Selection form Policy Version table
653         private void activePolicyList(String scopeName, List<JSONObject> resultList, List<String> roles, Set<String> scopes, boolean onlyFolders){
654                 PolicyController controller = getPolicyControllerInstance();
655                 if(scopeName.contains("/")){
656                         scopeName = scopeName.replace("/", File.separator);
657                 }
658                 if(scopeName.contains("\\")){
659                         scopeName = scopeName.replace("\\", "\\\\\\\\");
660                 }
661                 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
662                 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
663
664                 SimpleBindings params = new SimpleBindings();
665                 params.put("scopeName", scopeName + "%");
666
667                 List<Object> activePolicies;
668                 List<Object> scopesList;
669                 if(PolicyController.isjUnit()){
670                         activePolicies = controller.getDataByQuery(query, null);
671                         scopesList = controller.getDataByQuery(scopeNamequery, null);
672                 }else{
673                         activePolicies = controller.getDataByQuery(query, params);
674                         scopesList = controller.getDataByQuery(scopeNamequery, params);
675                 }
676                 for(Object list : scopesList){
677                         PolicyEditorScopes scopeById = (PolicyEditorScopes) list;
678                         String scope = scopeById.getScopeName();
679                         if(scope.contains(File.separator)){
680                                 String checkScope = scope.substring(0, scope.lastIndexOf(File.separator));
681                                 if(scopeName.contains("\\\\")){
682                                         scopeName = scopeName.replace("\\\\", File.separator);
683                                 }
684                                 if(scope.contains(File.separator)){
685                                         scope = scope.substring(checkScope.length()+1);
686                                         if(scope.contains(File.separator)){
687                                                 scope = scope.substring(0, scope.indexOf(File.separator));
688                                         }
689                                 }
690                                 if(scopeName.equalsIgnoreCase(checkScope)){
691                                         JSONObject el = new JSONObject();
692                                         el.put("name", scope);
693                                         el.put("date", scopeById.getModifiedDate());
694                                         el.put("size", "");
695                                         el.put("type", "dir");
696                                         el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
697                                         el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
698                                         resultList.add(el);
699                                 }
700                         }
701                 }
702                 String scopeNameCheck;
703                 for (Object list : activePolicies) {
704                         PolicyVersion policy = (PolicyVersion) list;
705                         String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator));
706                         if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
707                                 if((scopeName.contains("\\\\"))){
708                                         scopeNameCheck = scopeName.replace("\\\\", File.separator);
709                                 }else{
710                                         scopeNameCheck = scopeName;
711                                 }
712                                 if(scopeNameValue.equals(scopeNameCheck)){
713                                         JSONObject el = new JSONObject();
714                                         el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
715                                         el.put("date", policy.getModifiedDate());
716                                         el.put("version", policy.getActiveVersion());
717                                         el.put("size", "");
718                                         el.put("type", "file");
719                                         el.put("createdBy", getUserName(policy.getCreatedBy()));
720                                         el.put("modifiedBy", getUserName(policy.getModifiedBy()));
721                                         resultList.add(el);
722                                 }
723                         }else if(!scopes.isEmpty() && scopes.contains(scopeNameValue)){
724                                         JSONObject el = new JSONObject();
725                                         el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
726                                         el.put("date", policy.getModifiedDate());
727                                         el.put("version", policy.getActiveVersion());
728                                         el.put("size", "");
729                                         el.put("type", "file");
730                                         el.put("createdBy", getUserName(policy.getCreatedBy()));
731                                         el.put("modifiedBy", getUserName(policy.getModifiedBy()));
732                                         resultList.add(el);
733                         }
734                 }
735         }
736
737         private String getUserName(String loginId){
738                 PolicyController controller = getPolicyControllerInstance();
739                 UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
740                 if(userInfo == null){
741                         return SUPERADMIN;
742                 }
743                 return userInfo.getUserName();
744         }
745
746         //Rename Policy
747         private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
748                 try {
749                         boolean isActive = false;
750                         List<String> policyActiveInPDP = new ArrayList<>();
751                         Set<String>  scopeOfPolicyActiveInPDP = new HashSet<>();
752                         String userId = UserUtils.getUserSession(request).getOrgUserId();
753                         String oldPath = params.getString("path");
754                         String newPath = params.getString("newPath");
755                         oldPath = oldPath.substring(oldPath.indexOf('/')+1);
756                         newPath = newPath.substring(newPath.indexOf('/')+1);
757                         if(oldPath.endsWith(".xml")){
758                                 JSONObject result = policyRename(oldPath, newPath, userId);
759                                 if(!(Boolean)(result.getJSONObject("result").get("success"))){
760                                         return result;
761                                 }
762                         }else{
763                                 String scopeName = oldPath;
764                                 String newScopeName = newPath;
765                                 if(scopeName.contains("/")){
766                                         scopeName = scopeName.replace("/", File.separator);
767                                         newScopeName = newScopeName.replace("/", File.separator);
768                                 }
769                                 if(scopeName.contains("\\")){
770                                         scopeName = scopeName.replace("\\", "\\\\\\\\");
771                                         newScopeName = newScopeName.replace("\\", "\\\\\\\\");
772                                 }
773                                 PolicyController controller = getPolicyControllerInstance();
774                                 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
775                                 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
776                                 SimpleBindings pvParams = new SimpleBindings();
777                                 pvParams.put("scopeName", scopeName + "%");
778                                 List<Object> activePolicies = controller.getDataByQuery(query, pvParams);
779                                 List<Object> scopesList = controller.getDataByQuery(scopeNamequery, pvParams);
780                                 for(Object object : activePolicies){
781                                         PolicyVersion activeVersion = (PolicyVersion) object;
782                                         String policyOldPath = activeVersion.getPolicyName().replace(File.separator, "/") + "." + activeVersion.getActiveVersion() + ".xml";
783                                         String policyNewPath = policyOldPath.replace(oldPath, newPath);
784                                         JSONObject result = policyRename(policyOldPath, policyNewPath, userId);
785                                         if(!(Boolean)(result.getJSONObject("result").get("success"))){
786                                                 isActive = true;
787                                                 policyActiveInPDP.add(policyOldPath);
788                                                 String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf('/'));
789                                                 scopeOfPolicyActiveInPDP.add(scope.replace("/", File.separator));
790                                         }
791                                 }
792                                 boolean rename = false;
793                                 if(activePolicies.size() != policyActiveInPDP.size()){
794                                         rename = true;
795                                 }
796
797                                 UserInfo userInfo = new UserInfo();
798                                 userInfo.setUserLoginId(userId);
799                                 if(policyActiveInPDP.isEmpty()){
800                                         renameScope(scopesList, scopeName, newScopeName, controller);
801                                 }else if(rename){
802                                         renameScope(scopesList, scopeName, newScopeName, controller);
803                                         for(String scope : scopeOfPolicyActiveInPDP){
804                                                 PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes();
805                                                 editorScopeEntity.setScopeName(scope.replace("\\", "\\\\\\\\"));
806                                                 editorScopeEntity.setUserCreatedBy(userInfo);
807                                                 editorScopeEntity.setUserModifiedBy(userInfo);
808                                                 controller.saveData(editorScopeEntity);
809                                         }
810                                 }
811                                 if(isActive){
812                                         return error("The Following policies rename failed. Since they are active in PDP Groups" +policyActiveInPDP);
813                                 }
814                         }
815                         return success();
816                 } catch (Exception e) {
817                         LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
818                         return error(e.getMessage());
819                 }
820         }
821
822         private void renameScope(List<Object> scopesList, String scopeName, String newScopeName, PolicyController controller){
823                 for(Object object : scopesList){
824                         PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object;
825                         if(scopeName.contains("\\\\\\\\")){
826                                 scopeName = scopeName.replace("\\\\\\\\", File.separator);
827                                 newScopeName = newScopeName.replace("\\\\\\\\", File.separator);
828                         }
829                         String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName);
830                         editorScopeEntity.setScopeName(scope);
831                         controller.updateData(editorScopeEntity);
832                 }
833         }
834
835         private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
836                 try {
837                         PolicyEntity entity;
838                         PolicyController controller = getPolicyControllerInstance();
839
840                         String policyVersionName = newPath.replace(".xml", "");
841                         String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')).replace("/", File.separator);
842
843                         String oldpolicyVersionName = oldPath.replace(".xml", "");
844                         String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf('.')).replace("/", File.separator);
845
846                         String newpolicyName = newPath.replace("/", ".");
847                         String newPolicyCheck = newpolicyName;
848                         if(newPolicyCheck.contains("Config_")){
849                                 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
850                         }else if(newPolicyCheck.contains("Action_")){
851                                 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
852                         }else if(newPolicyCheck.contains("Decision_")){
853                                 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
854                         }
855                         String[] newPolicySplit = newPolicyCheck.split(":");
856
857                         String orignalPolicyName = oldPath.replace("/", ".");
858                         String oldPolicyCheck = orignalPolicyName;
859                         if(oldPolicyCheck.contains("Config_")){
860                                 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
861                         }else if(oldPolicyCheck.contains("Action_")){
862                                 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
863                         }else if(oldPolicyCheck.contains("Decision_")){
864                                 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
865                         }
866                         String[] oldPolicySplit = oldPolicyCheck.split(":");
867
868                         //Check PolicyEntity table with newPolicy Name
869                         String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
870                         SimpleBindings policyParams = new SimpleBindings();
871                         policyParams.put("newPolicySplit_1", newPolicySplit[1]);
872                         policyParams.put("newPolicySplit_0", newPolicySplit[0]);
873                         List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
874                         if(!queryData.isEmpty()){
875                                 return error("Policy rename failed. Since, the policy with same name already exists.");
876                         }
877
878                         //Query the Policy Entity with oldPolicy Name
879                         String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf('.'));
880                         String oldpolicyEntityquery = "FROM PolicyEntity where policyName like :policyEntityCheck and scope = :oldPolicySplit_0";
881                         SimpleBindings params = new SimpleBindings();
882                         params.put("policyEntityCheck", policyEntityCheck + "%");
883                         params.put("oldPolicySplit_0", oldPolicySplit[0]);
884                         List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery, params);
885                         if(!oldEntityData.isEmpty()){
886                                 StringBuilder groupQuery = new StringBuilder();
887                                 groupQuery.append("FROM PolicyGroupEntity where (");
888                                 SimpleBindings geParams = new SimpleBindings();
889                                 for(int i=0; i<oldEntityData.size(); i++){
890                                         entity = (PolicyEntity) oldEntityData.get(i);
891                                         if(i == 0){
892                                                 groupQuery.append("policyid = :policyId");
893                                                 geParams.put("policyId", entity.getPolicyId());
894                                         }else{
895                                                 groupQuery.append(" or policyid = :policyId" + i);
896                                                 geParams.put("policyId" + i, entity.getPolicyId());
897                                         }
898                                 }
899                                 groupQuery.append(")");
900                                 List<Object> groupEntityData = controller.getDataByQuery(groupQuery.toString(), geParams);
901                                 if(! groupEntityData.isEmpty()){
902                                         return error("Policy rename failed. Since the policy or its version is active in PDP Groups.");
903                                 }
904                                 for(int i=0; i<oldEntityData.size(); i++){
905                                         entity = (PolicyEntity) oldEntityData.get(i);
906                                         checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0] , newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
907                                 }
908                         }else{
909                                 return error("Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin.");
910                         }
911
912                         return success();
913                 } catch (Exception e) {
914                         LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
915                         return error(e.getMessage());
916                 }
917         }
918
919         private JSONObject checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, String oldScope, String removeoldPolicyExtension,
920                         String policyName, String  newpolicyName, String oldpolicyName, String userId) throws ServletException{
921                 try {
922                         ConfigurationDataEntity configEntity = entity.getConfigurationData();
923                         ActionBodyEntity actionEntity = entity.getActionBodyEntity();
924                         PolicyController controller = getPolicyControllerInstance();
925
926                         String oldPolicyNameWithoutExtension = removeoldPolicyExtension;
927                         String newPolicyNameWithoutExtension = removenewPolicyExtension;
928                         if(removeoldPolicyExtension.endsWith(".xml")){
929                                 oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf('.'));
930                                 newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf('.'));
931                         }
932                         entity.setPolicyName(entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
933                         entity.setPolicyData(entity.getPolicyData().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
934                         entity.setScope(newScope);
935                         entity.setModifiedBy(userId);
936                         if(newpolicyName.contains("Config_")){
937                                 String oldConfigurationName = configEntity.getConfigurationName();
938                                 configEntity.setConfigurationName(configEntity.getConfigurationName().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
939                                 controller.updateData(configEntity);
940                                 String newConfigurationName = configEntity.getConfigurationName();
941                                 File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName);
942                                 if(file.exists()){
943                                         File renamefile = new File(PolicyController.getConfigHome() + File.separator + newConfigurationName);
944                                         file.renameTo(renamefile);
945                                 }
946                         }else if(newpolicyName.contains("Action_")){
947                                 String oldConfigurationName = actionEntity.getActionBodyName();
948                                 actionEntity.setActionBody(actionEntity.getActionBody().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
949                                 controller.updateData(actionEntity);
950                                 String newConfigurationName = actionEntity.getActionBodyName();
951                                 File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName);
952                                 if(file.exists()){
953                                         File renamefile = new File(PolicyController.getActionHome() + File.separator + newConfigurationName);
954                                         file.renameTo(renamefile);
955                                 }
956                         }
957                         controller.updateData(entity);
958
959                         PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldpolicyName);
960                         versionEntity.setPolicyName(policyName);
961                         versionEntity.setModifiedBy(userId);
962                         controller.updateData(versionEntity);
963                         String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator)+1);
964                         String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
965                         if(movePolicyCheck.equals(moveOldPolicyCheck)){
966                                 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move");
967                         }else{
968                                 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename");
969                         }
970                         return success();
971                 } catch (Exception e) {
972                         LOGGER.error("Exception Occured"+e);
973                         return error(e.getMessage());
974                 }
975         }
976
977         private JSONObject cloneRecord(String newpolicyName, String oldScope, String removeoldPolicyExtension, String newScope, String removenewPolicyExtension, PolicyEntity entity, String userId) throws ServletException{
978                 FileWriter fw = null;
979                 String queryEntityName;
980                 PolicyController controller = getPolicyControllerInstance();
981                 PolicyEntity cloneEntity = new PolicyEntity();
982                 cloneEntity.setPolicyName(newpolicyName);
983                 removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
984                 removenewPolicyExtension = removenewPolicyExtension.replace(".xml", "");
985                 cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope+"."+removeoldPolicyExtension, newScope+"."+removenewPolicyExtension));
986                 cloneEntity.setScope(entity.getScope());
987                 String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
988                 String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
989                 if(newpolicyName.contains("Config_")){
990                         ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
991                         configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
992                         queryEntityName = configurationDataEntity.getConfigurationName();
993                         configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody());
994                         configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType());
995                         configurationDataEntity.setDeleted(false);
996                         configurationDataEntity.setCreatedBy(userId);
997                         configurationDataEntity.setModifiedBy(userId);
998                         controller.saveData(configurationDataEntity);
999                         ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
1000                         cloneEntity.setConfigurationData(configEntiy);
1001                         String newConfigurationName = configEntiy.getConfigurationName();
1002                         try {
1003                                 fw = new FileWriter(PolicyController.getConfigHome() + File.separator + newConfigurationName);
1004                                 BufferedWriter bw = new BufferedWriter(fw);
1005                                 bw.write(configEntiy.getConfigBody());
1006                                 bw.close();
1007                         } catch (IOException e) {
1008                                 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1009                         }
1010                 }else if(newpolicyName.contains("Action_")){
1011                         ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
1012                         actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1013                         queryEntityName = actionBodyEntity.getActionBodyName();
1014                         actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody());
1015                         actionBodyEntity.setDeleted(false);
1016                         actionBodyEntity.setCreatedBy(userId);
1017                         actionBodyEntity.setModifiedBy(userId);
1018                         controller.saveData(actionBodyEntity);
1019                         ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class, "actionBodyName", queryEntityName);
1020                         cloneEntity.setActionBodyEntity(actionEntiy);
1021                         String newConfigurationName = actionEntiy.getActionBodyName();
1022                         try {
1023                                 fw = new FileWriter(PolicyController.getActionHome() + File.separator + newConfigurationName);
1024                                 BufferedWriter bw = new BufferedWriter(fw);
1025                                 bw.write(actionEntiy.getActionBody());
1026                                 bw.close();
1027                         } catch (IOException e) {
1028                                 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1029                         }
1030                 }
1031                 if(fw != null){
1032                         try {
1033                                 fw.close();
1034                         } catch (IOException e) {
1035                                 LOGGER.error("Exception Occured While closing the File input stream"+e);
1036                         }
1037                 }
1038                 cloneEntity.setDeleted(entity.isDeleted());
1039                 cloneEntity.setCreatedBy(userId);
1040                 cloneEntity.setModifiedBy(userId);
1041                 controller.saveData(cloneEntity);
1042
1043                 return success();
1044         }
1045
1046         //Clone the Policy
1047         private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
1048                 try {
1049                         String userId = UserUtils.getUserSession(request).getOrgUserId();
1050                         String oldPath = params.getString("path");
1051                         String newPath = params.getString("newPath");
1052                         oldPath = oldPath.substring(oldPath.indexOf('/')+1);
1053                         newPath = newPath.substring(newPath.indexOf('/')+1);
1054
1055                         String policyVersionName = newPath.replace(".xml", "");
1056                         String version = policyVersionName.substring(policyVersionName.indexOf('.')+1);
1057                         String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')).replace("/", File.separator);
1058
1059                         String newpolicyName = newPath.replace("/", ".");
1060
1061                         String orignalPolicyName = oldPath.replace("/", ".");
1062
1063                         String newPolicyCheck = newpolicyName;
1064                         if(newPolicyCheck.contains("Config_")){
1065                                 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
1066                         }else if(newPolicyCheck.contains("Action_")){
1067                                 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
1068                         }else if(newPolicyCheck.contains("Decision_")){
1069                                 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
1070                         }
1071                         String[] newPolicySplit = newPolicyCheck.split(":");
1072
1073                         String oldPolicyCheck = orignalPolicyName;
1074                         if(oldPolicyCheck.contains("Config_")){
1075                                 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
1076                         }else if(oldPolicyCheck.contains("Action_")){
1077                                 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
1078                         }else if(oldPolicyCheck.contains("Decision_")){
1079                                 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
1080                         }
1081                         String[] oldPolicySplit = oldPolicyCheck.split(":");
1082
1083                         PolicyController controller = getPolicyControllerInstance();
1084
1085                         PolicyEntity entity = null;
1086                         boolean success = false;
1087
1088                         //Check PolicyEntity table with newPolicy Name
1089                         String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
1090                         SimpleBindings policyParams = new SimpleBindings();
1091                         policyParams.put("newPolicySplit_1", newPolicySplit[1]);
1092                         policyParams.put("newPolicySplit_0", newPolicySplit[0]);
1093                         List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
1094                         if(!queryData.isEmpty()){
1095                                 return error("Policy already exists with same name");
1096                         }
1097
1098                         //Query the Policy Entity with oldPolicy Name
1099                         policyEntityquery = "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0";
1100                         SimpleBindings peParams = new SimpleBindings();
1101                         peParams.put("oldPolicySplit_1", oldPolicySplit[1]);
1102                         peParams.put("oldPolicySplit_0", oldPolicySplit[0]);
1103                         queryData = controller.getDataByQuery(policyEntityquery, peParams);
1104                         if(!queryData.isEmpty()){
1105                                 entity = (PolicyEntity) queryData.get(0);
1106                         }
1107                         if(entity != null){
1108                                 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1],  newPolicySplit[0], newPolicySplit[1], entity, userId);
1109                                 success = true;
1110                         }
1111
1112                         if(success){
1113                                 PolicyVersion entityItem = new PolicyVersion();
1114                                 entityItem.setActiveVersion(Integer.parseInt(version));
1115                                 entityItem.setHigherVersion(Integer.parseInt(version));
1116                                 entityItem.setPolicyName(policyName);
1117                                 entityItem.setCreatedBy(userId);
1118                                 entityItem.setModifiedBy(userId);
1119                                 entityItem.setModifiedDate(new Date());
1120                                 controller.saveData(entityItem);
1121                         }
1122
1123                         LOGGER.debug("copy from: {} to: {}" + oldPath +newPath);
1124
1125                         return success();
1126                 } catch (Exception e) {
1127                         LOGGER.error("copy", e);
1128                         return error(e.getMessage());
1129                 }
1130         }
1131
1132         //Delete Policy or Scope Functionality
1133         private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
1134                 PolicyController controller = getPolicyControllerInstance();
1135                 PolicyRestController restController = new PolicyRestController();
1136                 PolicyEntity policyEntity = null;
1137                 String policyNamewithoutExtension;
1138                 try {
1139                         String userId = UserUtils.getUserSession(request).getOrgUserId();
1140                         String deleteVersion = "";
1141                         String path = params.getString("path");
1142                         LOGGER.debug("delete {}" +path);
1143                         if(params.has("deleteVersion")){
1144                                 deleteVersion  = params.getString("deleteVersion");
1145                         }
1146                         path = path.substring(path.indexOf('/')+1);
1147                         String policyNamewithExtension = path.replace("/", File.separator);
1148                         String policyVersionName = policyNamewithExtension.replace(".xml", "");
1149                         String query;
1150                         SimpleBindings policyParams = new SimpleBindings();
1151                         if(path.endsWith(".xml")){
1152                                 policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf('.'));
1153                                 policyNamewithoutExtension = policyNamewithoutExtension.replace(File.separator, ".");
1154                                 String splitPolicyName = null;
1155                                 if(policyNamewithoutExtension.contains("Config_")){
1156                                         splitPolicyName = policyNamewithoutExtension.replace(".Config_", ":Config_");
1157                                 }else if(policyNamewithoutExtension.contains("Action_")){
1158                                         splitPolicyName = policyNamewithoutExtension.replace(".Action_", ":Action_");
1159                                 }else if(policyNamewithoutExtension.contains("Decision_")){
1160                                         splitPolicyName = policyNamewithoutExtension.replace(".Decision_", ":Decision_");
1161                                 }
1162                                 String[] split = splitPolicyName.split(":");
1163
1164                                 query = "FROM PolicyEntity where policyName like :split_1 and scope = :split_0";
1165                                 policyParams.put("split_1", split[1] + "%");
1166                                 policyParams.put("split_0", split[0]);
1167                         }else{
1168                                 policyNamewithoutExtension = path.replace(File.separator, ".");
1169                                 query = "FROM PolicyEntity where scope like :policyNamewithoutExtension";
1170                                 policyParams.put("policyNamewithoutExtension", policyNamewithoutExtension + "%");
1171                         }
1172
1173                         List<Object> policyEntityobjects = controller.getDataByQuery(query, policyParams);
1174                         String activePolicyName = null;
1175                         boolean pdpCheck = false;
1176                         if(path.endsWith(".xml")){
1177                                 policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator);
1178                                 int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf('.')+1));
1179                                 if("ALL".equals(deleteVersion)){
1180                                         if(!policyEntityobjects.isEmpty()){
1181                                                 for(Object object : policyEntityobjects){
1182                                                         policyEntity = (PolicyEntity) object;
1183                                                         String groupEntityquery = "from PolicyGroupEntity where policyid ='"+policyEntity.getPolicyId()+"'";
1184                                                         SimpleBindings pgeParams = new SimpleBindings();
1185                                                         List<Object> groupobject = controller.getDataByQuery(groupEntityquery, pgeParams);
1186                                                         if(!groupobject.isEmpty()){
1187                                                                 pdpCheck = true;
1188                                                                 activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName();
1189                                                         }else{
1190                                                                 //Delete the entity from Elastic Search Database
1191                                                                 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1192                                                                 restController.deleteElasticData(searchFileName);
1193                                                                 //Delete the entity from Policy Entity table
1194                                                                 controller.deleteData(policyEntity);
1195                                                                 if(policyNamewithoutExtension.contains("Config_")){
1196                                                                         Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1197                                                                         controller.deleteData(policyEntity.getConfigurationData());
1198                                                                 }else if(policyNamewithoutExtension.contains("Action_")){
1199                                                                         Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1200                                                                         controller.deleteData(policyEntity.getActionBodyEntity());
1201                                                                 }
1202                                                         }
1203                                                 }
1204                                         }
1205                                         //Policy Notification
1206                                         PolicyVersion versionEntity = new PolicyVersion();
1207                                         versionEntity.setPolicyName(policyNamewithoutExtension);
1208                                         versionEntity.setModifiedBy(userId);
1209                                         controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll");
1210                                         if(pdpCheck){
1211                                                 //Delete from policyVersion table
1212                                                 String getActivePDPPolicyVersion = activePolicyName.replace(".xml", "");
1213                                                 getActivePDPPolicyVersion = getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf('.')+1);
1214                                                 String policyVersionQuery = "update PolicyVersion set active_version='"+getActivePDPPolicyVersion+"' , highest_version='"+getActivePDPPolicyVersion+"'  where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1215                                                 if(policyVersionQuery != null){
1216                                                         controller.executeQuery(policyVersionQuery);
1217                                                 }
1218                                                 return error("Policies with Same name has been deleted. Except the Active Policy in PDP.     PolicyName: "+activePolicyName);
1219                                         }else{
1220                                                 //No Active Policy in PDP. So, deleting all entries from policyVersion table
1221                                                 String policyVersionQuery = "delete from PolicyVersion  where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1222                                                 if(policyVersionQuery != null){
1223                                                         controller.executeQuery(policyVersionQuery);
1224                                                 }
1225                                         }
1226                                 }else if("CURRENT".equals(deleteVersion)){
1227                                         String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1);
1228                                         String currentVersionScope = policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator)).replace(File.separator, ".");
1229                                         query = "FROM PolicyEntity where policyName = :currentVersionPolicyName and scope = :currentVersionScope";
1230
1231                                         SimpleBindings peParams = new SimpleBindings();
1232                                         peParams.put("currentVersionPolicyName", currentVersionPolicyName);
1233                                         peParams.put("currentVersionScope", currentVersionScope);
1234
1235                                         List<Object> policyEntitys = controller.getDataByQuery(query, peParams);
1236                                         if(!policyEntitys.isEmpty()){
1237                                                 policyEntity = (PolicyEntity) policyEntitys.get(0);
1238                                         }
1239                                         if(policyEntity != null){
1240                                                 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId and policyid > 0";
1241                                                 SimpleBindings geParams = new SimpleBindings();
1242                                                 geParams.put("policyEntityId", policyEntity.getPolicyId());
1243                                                 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1244                                                 if(groupobject.isEmpty()){
1245                                                         //Delete the entity from Elastic Search Database
1246                                                         String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1247                                                         restController.deleteElasticData(searchFileName);
1248                                                         //Delete the entity from Policy Entity table
1249                                                         controller.deleteData(policyEntity);
1250                                                         if(policyNamewithoutExtension.contains("Config_")){
1251                                                                 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1252                                                                 controller.deleteData(policyEntity.getConfigurationData());
1253                                                         }else if(policyNamewithoutExtension.contains("Action_")){
1254                                                                 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1255                                                                 controller.deleteData(policyEntity.getActionBodyEntity());
1256                                                         }
1257
1258                                                         if(version > 1){
1259                                                                 int highestVersion = 0;
1260                                                                 if(!policyEntityobjects.isEmpty()){
1261                                                                         for(Object object : policyEntityobjects){
1262                                                                                 policyEntity = (PolicyEntity) object;
1263                                                                                 String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
1264                                                                                 int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf('.')+1));
1265                                                                                 if(policyEntityVersion > highestVersion && policyEntityVersion != version){
1266                                                                                         highestVersion = policyEntityVersion;
1267                                                                                 }
1268                                                                         }
1269                                                                 }
1270
1271                                                                 //Policy Notification
1272                                                                 PolicyVersion entity = new PolicyVersion();
1273                                                                 entity.setPolicyName(policyNamewithoutExtension);
1274                                                                 entity.setActiveVersion(highestVersion);
1275                                                                 entity.setModifiedBy(userId);
1276                                                                 controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne");
1277
1278                                                                 String updatequery = "update PolicyVersion set active_version='"+highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"'";
1279                                                                 controller.executeQuery(updatequery);
1280                                                         }else{
1281                                                                 String policyVersionQuery = "delete from PolicyVersion  where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1282                                                                 if(policyVersionQuery != null){
1283                                                                         controller.executeQuery(policyVersionQuery);
1284                                                                 }
1285                                                         }
1286                                                 }else{
1287                                                         return error("Policy can't be deleted, it is active in PDP Groups.     PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'");
1288                                                 }
1289                                         }
1290                                 }
1291                         }else{
1292                                 List<String> activePoliciesInPDP = new ArrayList<String>();
1293                                 if(!policyEntityobjects.isEmpty()){
1294                                         for(Object object : policyEntityobjects){
1295                                                 policyEntity = (PolicyEntity) object;
1296                                                 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId";
1297                                                 SimpleBindings geParams = new SimpleBindings();
1298                                                 geParams.put("policyEntityId", policyEntity.getPolicyId());
1299                                                 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1300                                                 if(!groupobject.isEmpty()){
1301                                                         pdpCheck = true;
1302                                                         activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName());
1303                                                 }else{
1304                                                         //Delete the entity from Elastic Search Database
1305                                                         String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1306                                                         restController.deleteElasticData(searchFileName);
1307                                                         //Delete the entity from Policy Entity table
1308                                                         controller.deleteData(policyEntity);
1309                                                         policyNamewithoutExtension = policyEntity.getPolicyName();
1310                                                         if(policyNamewithoutExtension.contains("Config_")){
1311                                                                 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1312                                                                 controller.deleteData(policyEntity.getConfigurationData());
1313                                                         }else if(policyNamewithoutExtension.contains("Action_")){
1314                                                                 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1315                                                                 controller.deleteData(policyEntity.getActionBodyEntity());
1316                                                         }
1317                                                 }
1318                                         }
1319                                         //Delete from policyVersion and policyEditor Scope table
1320                                         String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1321                                         controller.executeQuery(policyVersionQuery);
1322
1323                                         //Policy Notification
1324                                         PolicyVersion entity = new PolicyVersion();
1325                                         entity.setPolicyName(path);
1326                                         entity.setModifiedBy(userId);
1327                                         controller.watchPolicyFunction(entity, path, "DeleteScope");
1328                                         if(pdpCheck){
1329                                                 //Add Active Policies List to PolicyVersionTable
1330                                                 for(int i =0; i < activePoliciesInPDP.size(); i++){
1331                                                         String activePDPPolicyName = activePoliciesInPDP.get(i).replace(".xml", "");
1332                                                         int activePDPPolicyVersion = Integer.parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf('.')+1));
1333                                                         activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf('.')).replace(".", File.separator);
1334                                                         PolicyVersion insertactivePDPVersion = new PolicyVersion();
1335                                                         insertactivePDPVersion.setPolicyName(activePDPPolicyName);
1336                                                         insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion);
1337                                                         insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion);
1338                                                         insertactivePDPVersion.setCreatedBy(userId);
1339                                                         insertactivePDPVersion.setModifiedBy(userId);
1340                                                         controller.saveData(insertactivePDPVersion);
1341                                                 }
1342
1343                                                 return error("All the Policies has been deleted in Scope. Except the following list of Policies:"+activePoliciesInPDP);
1344                                         }else{
1345                                                 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1346                                             controller.executeQuery(policyScopeQuery);
1347                                         }
1348                                 }else{
1349                                         String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1350                                         controller.executeQuery(policyScopeQuery);
1351                                 }
1352                         }
1353                         return success();
1354                 } catch (Exception e) {
1355                         LOGGER.error("delete", e);
1356                         return error(e.getMessage());
1357                 }
1358         }
1359
1360         //Edit the Policy
1361         private JSONObject editFile(JSONObject params) throws ServletException {
1362                 // get content
1363                 try {
1364                         PolicyController controller = getPolicyControllerInstance();
1365                         String mode = params.getString("mode");
1366                         String path = params.getString("path");
1367                         LOGGER.debug("editFile path: {}"+ path);
1368
1369                         String domain = path.substring(1, path.lastIndexOf('/'));
1370                         domain = domain.replace("/", ".");
1371
1372                         path = path.substring(1);
1373                         path = path.replace("/", ".");
1374                         String dbCheckName = path;
1375                         if(dbCheckName.contains("Config_")){
1376                                 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
1377                         }else if(dbCheckName.contains("Action_")){
1378                                 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
1379                         }else if(dbCheckName.contains("Decision_")){
1380                                 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
1381                         }
1382
1383                         String[] split = dbCheckName.split(":");
1384                         String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
1385                         SimpleBindings peParams = new SimpleBindings();
1386                         peParams.put("split_1", split[1]);
1387                         peParams.put("split_0", split[0]);
1388                         List<Object> queryData;
1389                         if(PolicyController.isjUnit()){
1390                                 queryData = controller.getDataByQuery(query, null);
1391                         }else{
1392                                 queryData = controller.getDataByQuery(query, peParams);
1393                         }
1394                         PolicyEntity entity = (PolicyEntity) queryData.get(0);
1395                         InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
1396
1397
1398                         Object policy = XACMLPolicyScanner.readPolicy(stream);
1399                         PolicyRestAdapter policyAdapter  = new PolicyRestAdapter();
1400                         policyAdapter.setData(policy);
1401
1402                         if("viewPolicy".equalsIgnoreCase(mode)){
1403                                 policyAdapter.setReadOnly(true);
1404                                 policyAdapter.setEditPolicy(false);
1405                         }else{
1406                                 policyAdapter.setReadOnly(false);
1407                                 policyAdapter.setEditPolicy(true);
1408                         }
1409                         
1410                         policyAdapter.setDomainDir(domain);
1411                         policyAdapter.setPolicyData(policy);
1412                         String policyName = path.replace(".xml", "");
1413                         policyName = policyName.substring(0, policyName.lastIndexOf('.'));
1414                         policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf('.')+1));
1415
1416                         PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance();
1417                         setpolicyAdapter.configure(policyAdapter,entity);
1418
1419                         policyAdapter.setParentPath(null);
1420                         ObjectMapper mapper = new ObjectMapper();
1421                         String json = mapper.writeValueAsString(policyAdapter);
1422                         JsonNode jsonNode = mapper.readTree(json);
1423
1424                         return new JSONObject().put(RESULT, jsonNode);
1425                 } catch (Exception e) {
1426                         LOGGER.error("editFile", e);
1427                         return error(e.getMessage());
1428                 }
1429         }
1430
1431         //Add Scopes
1432         private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
1433                 PolicyController controller = getPolicyControllerInstance();
1434                 String name = "";
1435                 try {
1436                         String userId = UserUtils.getUserSession(request).getOrgUserId();
1437                         String path = params.getString("path");
1438                         try{
1439                                 if(params.has("subScopename")){
1440                                         if(! "".equals(params.getString("subScopename"))) {
1441                                                 name = params.getString("path").replace("/", File.separator) + File.separator +params.getString("subScopename");
1442                                         }
1443                                 }else{
1444                                         name = params.getString("name");
1445                                 }
1446                         }catch(Exception e){
1447                                 name = params.getString("name");
1448                                 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e);
1449                         }
1450                         String validateName;
1451                         if(name.contains(File.separator)){
1452                                 validateName = name.substring(name.lastIndexOf(File.separator)+1);
1453                         }else{
1454                                 validateName = name;
1455                         }
1456                         if(!name.isEmpty()){
1457                                 String validate = PolicyUtils.policySpecialCharValidator(validateName);
1458                                 if(!validate.contains("success")){
1459                                         return error(validate);
1460                                 }
1461                         }
1462                         LOGGER.debug("addFolder path: {} name: {}" + path +name);
1463                         if(! "".equals(name)){
1464                                 if(name.startsWith(File.separator)){
1465                                         name = name.substring(1);
1466                                 }
1467                                 PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, "scopeName", name);
1468                                 if(entity == null){
1469                                         UserInfo userInfo = new UserInfo();
1470                                         userInfo.setUserLoginId(userId);
1471                                         PolicyEditorScopes newScope = new PolicyEditorScopes();
1472                                         newScope.setScopeName(name);
1473                                         newScope.setUserCreatedBy(userInfo);
1474                                         newScope.setUserModifiedBy(userInfo);
1475                                         controller.saveData(newScope);
1476                                 }else{
1477                                         return error("Scope Already Exists");
1478                                 }
1479                         }
1480                         return success();
1481                 } catch (Exception e) {
1482                         LOGGER.error("addFolder", e);
1483                         return error(e.getMessage());
1484                 }
1485         }
1486
1487         //Return Error Object
1488         private JSONObject error(String msg) throws ServletException {
1489                 try {
1490                         JSONObject result = new JSONObject();
1491                         result.put("success", false);
1492                         result.put("error", msg);
1493                         return new JSONObject().put(RESULT, result);
1494                 } catch (JSONException e) {
1495                         throw new ServletException(e);
1496                 }
1497         }
1498
1499         //Return Success Object
1500         private JSONObject success() throws ServletException {
1501                 try {
1502                         JSONObject result = new JSONObject();
1503                         result.put("success", true);
1504                         result.put("error", (Object) null);
1505                         return new JSONObject().put(RESULT, result);
1506                 } catch (JSONException e) {
1507                         throw new ServletException(e);
1508                 }
1509         }
1510
1511         private PolicyController getPolicyControllerInstance(){
1512                 return policyController != null ? getPolicyController() : new PolicyController();
1513         }
1514
1515         public String getTestUserId() {
1516                 return testUserId;
1517         }
1518
1519         public static void setTestUserId(String testUserId) {
1520                 PolicyManagerServlet.testUserId = testUserId;
1521         }
1522 }