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