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