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