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