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