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