2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.policy.admin;
23 import java.io.BufferedReader;
24 import java.io.BufferedWriter;
25 import java.io.ByteArrayInputStream;
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;
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;
56 import org.apache.commons.compress.utils.IOUtils;
57 import org.apache.commons.fileupload.FileItem;
58 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
59 import org.apache.commons.fileupload.servlet.ServletFileUpload;
60 import org.apache.http.HttpStatus;
61 import org.json.JSONArray;
62 import org.json.JSONException;
63 import org.json.JSONObject;
64 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
65 import org.openecomp.policy.common.logging.flexlogger.Logger;
66 import org.openecomp.policy.components.HumanPolicyComponent;
67 import org.openecomp.policy.controller.PolicyController;
68 import org.openecomp.policy.controller.PolicyExportAndImportController;
69 import org.openecomp.policy.model.Roles;
70 import org.openecomp.policy.rest.XACMLRest;
71 import org.openecomp.policy.rest.XACMLRestProperties;
72 import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
73 import org.openecomp.policy.rest.jpa.ActionBodyEntity;
74 import org.openecomp.policy.rest.jpa.ConfigurationDataEntity;
75 import org.openecomp.policy.rest.jpa.PolicyEditorScopes;
76 import org.openecomp.policy.rest.jpa.PolicyEntity;
77 import org.openecomp.policy.rest.jpa.PolicyVersion;
78 import org.openecomp.policy.rest.jpa.UserInfo;
79 import org.openecomp.policy.utils.PolicyUtils;
80 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
81 import org.openecomp.policy.xacml.util.XACMLPolicyScanner;
82 import org.openecomp.portalsdk.core.web.support.UserUtils;
84 import com.att.research.xacml.util.XACMLProperties;
85 import com.fasterxml.jackson.databind.JsonNode;
86 import com.fasterxml.jackson.databind.ObjectMapper;
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;
95 LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT, SEARCHLIST
98 private static String CONTENTTYPE = "application/json";
99 private static String SUPERADMIN = "super-admin";
100 private static String SUPEREDITOR = "super-editor";
101 private static String SUPERGUEST = "super-guest";
102 private static String ADMIN = "admin";
103 private static String EDITOR = "editor";
104 private static String GUEST = "guest";
105 private static String RESULT = "result";
107 private static Path closedLoopJsonLocation;
108 private static JsonArray policyNames;
110 public static JsonArray getPolicyNames() {
114 public static void setPolicyNames(JsonArray policyNames) {
115 PolicyManagerServlet.policyNames = policyNames;
118 private static List<String> serviceTypeNamesList = new ArrayList<String>();
119 private List<Object> policyData;
121 public static List<String> getServiceTypeNamesList() {
122 return serviceTypeNamesList;
126 public void init(ServletConfig servletConfig) throws ServletException {
127 super.init(servletConfig);
129 // Common initialization
131 XACMLRest.xacmlInit(servletConfig);
133 //Initialize ClosedLoop JSON
135 PolicyManagerServlet.initializeJSONLoad();
138 protected static void initializeJSONLoad() {
139 closedLoopJsonLocation = Paths.get(XACMLProperties
140 .getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP));
141 FileInputStream inputStream = null;
142 String location = closedLoopJsonLocation.toString();
144 inputStream = new FileInputStream(location);
145 } catch (FileNotFoundException e) {
146 LOGGER.error("Exception Occured while initializing the JSONConfig file"+e);
148 if (location.endsWith("json")) {
149 JsonReader jsonReader = null;
150 jsonReader = Json.createReader(inputStream);
151 policyNames = jsonReader.readArray();
152 serviceTypeNamesList = new ArrayList<String>();
153 for (int i = 0; i < policyNames.size(); i++) {
154 javax.json.JsonObject policyName = policyNames.getJsonObject(i);
155 String name = policyName.getJsonString("serviceTypePolicyName").getString();
156 serviceTypeNamesList.add(name);
163 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
164 LOGGER.debug("doPost");
166 // if request contains multipart-form-data
167 if (ServletFileUpload.isMultipartContent(request)) {
168 uploadFile(request, response);
170 // all other post request has json params in body
172 fileOperation(request, response);
174 } catch (Exception e) {
175 setError(e, response);
179 //Set Error Message for Exception
180 private void setError(Exception t, HttpServletResponse response) throws IOException {
182 JSONObject responseJsonObject = error(t.getMessage());
183 response.setContentType(CONTENTTYPE);
184 PrintWriter out = response.getWriter();
185 out.print(responseJsonObject);
187 } catch (Exception x) {
188 response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage());
192 //Policy Import Functionality
193 private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException {
196 Map<String, InputStream> files = new HashMap<String, InputStream>();
198 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
199 for (FileItem item : items) {
200 if (!item.isFormField()) {
201 // Process form file field (input type="file").
202 files.put(item.getName(), item.getInputStream());
203 if(item.getName().endsWith(".xls")){
205 File file = new File(item.getName());
206 OutputStream outputStream = new FileOutputStream(file);
207 IOUtils.copy(item.getInputStream(), outputStream);
208 outputStream.close();
209 newFile = file.toString();
210 PolicyExportAndImportController importController = new PolicyExportAndImportController();
211 importController.importRepositoryFile(newFile, request);
213 LOGGER.error("Upload error : " + e);
219 JSONObject responseJsonObject = null;
220 responseJsonObject = this.success();
221 response.setContentType("application/json");
222 PrintWriter out = response.getWriter();
223 out.print(responseJsonObject);
225 } catch (Exception e) {
226 LOGGER.debug("Cannot write file");
227 throw new ServletException("Cannot write file", e);
231 //File Operation Functionality
232 private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
233 JSONObject responseJsonObject = null;
235 StringBuilder sb = new StringBuilder();
236 BufferedReader br = request.getReader();
238 while ((str = br.readLine()) != null) {
242 JSONObject jObj = new JSONObject(sb.toString());
243 JSONObject params = jObj.getJSONObject("params");
244 Mode mode = Mode.valueOf(params.getString("mode"));
247 responseJsonObject = addFolder(params, request);
250 responseJsonObject = copy(params, request);
253 responseJsonObject = delete(params, request);
256 responseJsonObject = editFile(params);
259 responseJsonObject = editFile(params);
262 responseJsonObject = list(params, request);
265 responseJsonObject = rename(params, request);
267 case DESCRIBEPOLICYFILE:
268 responseJsonObject = describePolicy(params);
271 responseJsonObject = addFolder(params, request);
274 responseJsonObject = switchVersion(params, request);
277 responseJsonObject = searchPolicyList(params, request);
280 throw new ServletException("not implemented");
282 if (responseJsonObject == null) {
283 responseJsonObject = error("generic error : responseJsonObject is null");
285 } catch (Exception e) {
286 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While doing File Operation" + e);
287 responseJsonObject = error(e.getMessage());
289 response.setContentType("application/json");
290 PrintWriter out = response.getWriter();
291 out.print(responseJsonObject);
295 private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) {
296 Set<String> scopes = null;
297 List<String> roles = null;
298 policyData = new ArrayList<Object>();
299 JSONArray policyList = null;
300 if(params.has("policyList")){
301 policyList = (JSONArray) params.get("policyList");
303 PolicyController controller = new PolicyController();
304 List<JSONObject> resultList = new ArrayList<JSONObject>();
306 //Get the Login Id of the User from Request
307 String userId = UserUtils.getUserSession(request).getOrgUserId();
308 //Check if the Role and Scope Size are Null get the values from db.
309 List<Object> userRoles = PolicyController.getRoles(userId);
310 roles = new ArrayList<String>();
311 scopes = new HashSet<String>();
312 for(Object role: userRoles){
313 Roles userRole = (Roles) role;
314 roles.add(userRole.getRole());
315 if(userRole.getScope() != null){
316 if(userRole.getScope().contains(",")){
317 String[] multipleScopes = userRole.getScope().split(",");
318 for(int i =0; i < multipleScopes.length; i++){
319 scopes.add(multipleScopes[i]);
322 scopes.add(userRole.getScope());
326 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
327 if(scopes.isEmpty()){
328 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
331 if(policyList!= null){
332 for(int i = 0; i < policyList.length(); i++){
333 String policyName = policyList.get(i).toString().replace(".xml", "");
334 String version = policyName.substring(policyName.lastIndexOf(".")+1);
335 policyName = policyName.substring(0, policyName.lastIndexOf(".")).replace(".", File.separator);
336 if(policyName.contains("\\")){
337 policyName = policyName.replace("\\", "\\\\");
339 String policyVersionQuery = "From PolicyVersion where policy_name ='"+policyName+"' and active_version = '"+version+"'and id >0";
340 List<Object> activeData = controller.getDataByQuery(policyVersionQuery);
341 if(!activeData.isEmpty()){
342 PolicyVersion policy = (PolicyVersion) activeData.get(0);
343 JSONObject el = new JSONObject();
344 el.put("name", policy.getPolicyName().replace(File.separator, "/"));
345 el.put("date", policy.getModifiedDate());
346 el.put("version", policy.getActiveVersion());
348 el.put("type", "file");
349 el.put("createdBy", getUserName(policy.getCreatedBy()));
350 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
355 if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest") ){
356 policyData = controller.getData(PolicyVersion.class);
358 List<Object> filterdatas = controller.getData(PolicyVersion.class);
359 for(Object filter : filterdatas){
360 PolicyVersion filterdata = (PolicyVersion) filter;
361 String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator));
362 if(scopes.contains(scopeName)){
363 policyData.add(filterdata);
368 if(!policyData.isEmpty()){
369 for(int i =0; i < policyData.size(); i++){
370 PolicyVersion policy = (PolicyVersion) policyData.get(i);
371 JSONObject el = new JSONObject();
372 el.put("name", policy.getPolicyName().replace(File.separator, "/"));
373 el.put("date", policy.getModifiedDate());
374 el.put("version", policy.getActiveVersion());
376 el.put("type", "file");
377 el.put("createdBy", getUserName(policy.getCreatedBy()));
378 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
384 LOGGER.error("Exception occured while reading policy Data from Policy Version table for Policy Search Data"+e);
387 return new JSONObject().put(RESULT, resultList);
390 //Switch Version Functionality
391 private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{
392 String path = params.getString("path");
393 String userId = null;
395 userId = UserUtils.getUserSession(request).getOrgUserId();
396 } catch (Exception e) {
397 LOGGER.error("Exception Occured while reading userid from cookie" +e);
400 String removeExtension = path.replace(".xml", "");
401 if(path.startsWith("/")){
402 policyName = removeExtension.substring(1, removeExtension.lastIndexOf("."));
404 policyName = removeExtension.substring(0, removeExtension.lastIndexOf("."));
407 String activePolicy = null;
408 PolicyController controller = new PolicyController();
409 if(params.toString().contains("activeVersion")){
410 String activeVersion = params.getString("activeVersion");
411 String highestVersion = params.get("highestVersion").toString();
412 if(Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)){
413 return error("The Version shouldn't be greater than Highest Value");
415 activePolicy = policyName + "." + activeVersion + ".xml";
416 String dbCheckName = activePolicy.replace("/", ".");
417 if(dbCheckName.contains("Config_")){
418 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
419 }else if(dbCheckName.contains("Action_")){
420 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
421 }else if(dbCheckName.contains("Decision_")){
422 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
424 String[] splitDBCheckName = dbCheckName.split(":");
425 String peQuery = "FROM PolicyEntity where policyName = '"+splitDBCheckName[1]+"' and scope ='"+splitDBCheckName[0]+"'";
426 List<Object> policyEntity = controller.getDataByQuery(peQuery);
427 PolicyEntity pentity = (PolicyEntity) policyEntity.get(0);
428 if(pentity.isDeleted()){
429 return error("The Policy is Not Existing in Workspace");
431 if(policyName.contains("/")){
432 policyName = policyName.replace("/", File.separator);
434 policyName = policyName.substring(policyName.indexOf(File.separator)+1);
435 if(policyName.contains("\\")){
436 policyName = policyName.replace(File.separator, "\\");
438 policyName = splitDBCheckName[0].replace(".", File.separator)+File.separator+policyName;
439 String watchPolicyName = policyName;
440 if(policyName.contains("/")){
441 policyName = policyName.replace("/", File.separator);
443 if(policyName.contains("\\")){
444 policyName = policyName.replace("\\", "\\\\");
446 String query = "update PolicyVersion set active_version='"+activeVersion+"' where policy_name ='"+policyName+"' and id >0";
448 controller.executeQuery(query);
449 //Policy Notification
450 PolicyVersion entity = new PolicyVersion();
451 entity.setPolicyName(watchPolicyName);
452 entity.setActiveVersion(Integer.parseInt(activeVersion));
453 entity.setModifiedBy(userId);
454 controller.watchPolicyFunction(entity, activePolicy, "SwitchVersion");
459 return controller.switchVersionPolicyContent(policyName);
463 private JSONObject describePolicy(JSONObject params) throws ServletException{
464 JSONObject object = null;
465 String path = params.getString("path");
466 String policyName = null;
467 if(path.startsWith("/")){
468 path = path.substring(1);
469 policyName = path.substring(path.lastIndexOf("/") +1);
470 path = path.replace("/", ".");
472 path = path.replace("/", ".");
474 if(path.contains("Config_")){
475 path = path.replace(".Config_", ":Config_");
476 }else if(path.contains("Action_")){
477 path = path.replace(".Action_", ":Action_");
478 }else if(path.contains("Decision_")){
479 path = path.replace(".Decision_", ":Decision_");
481 PolicyController controller = new PolicyController();
482 String[] split = path.split(":");
483 String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'";
484 List<Object> queryData = controller.getDataByQuery(query);
485 if(!queryData.isEmpty()){
486 PolicyEntity entity = (PolicyEntity) queryData.get(0);
489 temp = File.createTempFile(policyName, ".tmp");
490 BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
491 bw.write(entity.getPolicyData());
493 object = HumanPolicyComponent.DescribePolicy(temp);
494 } catch (IOException e) {
495 LOGGER.error("Exception Occured while Describing the Policy"+e);
500 return error("Error Occured while Describing the Policy");
506 //Get the List of Policies and Scopes for Showing in Editor tab
507 private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException {
508 Set<String> scopes = null;
509 List<String> roles = null;
511 //Get the Login Id of the User from Request
512 String userId = UserUtils.getUserSession(request).getOrgUserId();
513 //Check if the Role and Scope Size are Null get the values from db.
514 List<Object> userRoles = PolicyController.getRoles(userId);
515 roles = new ArrayList<String>();
516 scopes = new HashSet<String>();
517 for(Object role: userRoles){
518 Roles userRole = (Roles) role;
519 roles.add(userRole.getRole());
520 if(userRole.getScope() != null){
521 if(userRole.getScope().contains(",")){
522 String[] multipleScopes = userRole.getScope().split(",");
523 for(int i =0; i < multipleScopes.length; i++){
524 scopes.add(multipleScopes[i]);
527 scopes.add(userRole.getScope());
531 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
532 if(scopes.isEmpty()){
533 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
537 List<JSONObject> resultList = new ArrayList<JSONObject>();
538 boolean onlyFolders = params.getBoolean("onlyFolders");
539 String path = params.getString("path");
540 if(path.contains("..xml")){
541 path = path.replaceAll("..xml", "").trim();
545 if("/".equals(path)){
546 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
547 List<Object> scopesList = queryPolicyEditorScopes(null);
548 for(Object list : scopesList){
549 PolicyEditorScopes scope = (PolicyEditorScopes) list;
550 if(!(scope.getScopeName().contains(File.separator))){
551 JSONObject el = new JSONObject();
552 el.put("name", scope.getScopeName());
553 el.put("date", scope.getCreatedDate());
555 el.put("type", "dir");
556 el.put("createdBy", scope.getUserCreatedBy().getUserName());
557 el.put("modifiedBy", scope.getUserModifiedBy().getUserName());
561 }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){
562 for(Object scope : scopes){
563 JSONObject el = new JSONObject();
564 List<Object> scopesList = queryPolicyEditorScopes(scope.toString());
565 PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
566 el.put("name", scopeById.getScopeName());
567 el.put("date", scopeById.getCreatedDate());
569 el.put("type", "dir");
570 el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
571 el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
577 String scopeName = path.substring(path.indexOf("/") +1);
578 activePolicyList(scopeName, resultList, roles, scopes, onlyFolders);
579 } catch (Exception ex) {
580 LOGGER.error("Error Occured While reading Policy Files List"+ex );
584 return new JSONObject().put(RESULT, resultList);
585 } catch (Exception e) {
586 LOGGER.error("list", e);
587 return error(e.getMessage());
591 private List<Object> queryPolicyEditorScopes(String scopeName){
592 String scopeNamequery = "";
593 if(scopeName == null){
594 scopeNamequery = "from PolicyEditorScopes";
596 scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"'";
598 PolicyController controller = new PolicyController();
599 List<Object> scopesList = controller.getDataByQuery(scopeNamequery);
603 //Get Active Policy List based on Scope Selection form Policy Version table
604 private void activePolicyList(String scopeName, List<JSONObject> resultList, List<String> roles, Set<String> scopes, boolean onlyFolders){
605 PolicyController controller = new PolicyController();
606 if(scopeName.contains("/")){
607 scopeName = scopeName.replace("/", File.separator);
609 if(scopeName.contains("\\")){
610 scopeName = scopeName.replace("\\", "\\\\\\\\");
612 String query = "from PolicyVersion where POLICY_NAME like'" +scopeName+"%'";
613 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"%'";
614 List<Object> activePolicies = controller.getDataByQuery(query);
615 List<Object> scopesList = controller.getDataByQuery(scopeNamequery);
616 for(Object list : scopesList){
617 PolicyEditorScopes scopeById = (PolicyEditorScopes) list;
618 String scope = scopeById.getScopeName();
619 if(scope.contains(File.separator)){
620 String checkScope = scope.substring(0, scope.lastIndexOf(File.separator));
621 if(scopeName.contains("\\\\")){
622 scopeName = scopeName.replace("\\\\", File.separator);
624 if(scope.contains(File.separator)){
625 scope = scope.substring(checkScope.length()+1);
626 if(scope.contains(File.separator)){
627 scope = scope.substring(0, scope.indexOf(File.separator));
630 if(scopeName.equalsIgnoreCase(checkScope)){
631 JSONObject el = new JSONObject();
632 el.put("name", scope);
633 el.put("date", scopeById.getModifiedDate());
635 el.put("type", "dir");
636 el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
637 el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
642 String scopeNameCheck = null;
643 for (Object list : activePolicies) {
644 PolicyVersion policy = (PolicyVersion) list;
645 String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator));
646 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
647 if((scopeName.contains("\\\\"))){
648 scopeNameCheck = scopeName.replace("\\\\", File.separator);
650 scopeNameCheck = scopeName;
652 if(scopeNameValue.equals(scopeNameCheck)){
653 JSONObject el = new JSONObject();
654 el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
655 el.put("date", policy.getModifiedDate());
656 el.put("version", policy.getActiveVersion());
658 el.put("type", "file");
659 el.put("createdBy", getUserName(policy.getCreatedBy()));
660 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
663 }else if(!scopes.isEmpty()){
664 if(scopes.contains(scopeNameValue)){
665 JSONObject el = new JSONObject();
666 el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
667 el.put("date", policy.getModifiedDate());
668 el.put("version", policy.getActiveVersion());
670 el.put("type", "file");
671 el.put("createdBy", getUserName(policy.getCreatedBy()));
672 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
679 private String getUserName(String loginId){
680 PolicyController controller = new PolicyController();
681 UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
682 if(userInfo == null){
683 return "super-admin";
685 return userInfo.getUserName();
689 private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
691 String userId = UserUtils.getUserSession(request).getOrgUserId();
692 String oldPath = params.getString("path");
693 String newPath = params.getString("newPath");
694 oldPath = oldPath.substring(oldPath.indexOf("/")+1);
695 newPath = newPath.substring(newPath.indexOf("/")+1);
696 if(oldPath.endsWith(".xml")){
697 policyRename(oldPath, newPath, userId);
699 String scopeName = oldPath;
700 String newScopeName = newPath;
701 if(scopeName.contains("/")){
702 scopeName = scopeName.replace("/", File.separator);
703 newScopeName = newScopeName.replace("/", File.separator);
705 if(scopeName.contains("\\")){
706 scopeName = scopeName.replace("\\", "\\\\\\\\");
707 newScopeName = newScopeName.replace("\\", "\\\\\\\\");
709 PolicyController controller = new PolicyController();
710 String query = "from PolicyVersion where POLICY_NAME like'" +scopeName+"%'";
711 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"%'";
712 List<Object> activePolicies = controller.getDataByQuery(query);
713 List<Object> scopesList = controller.getDataByQuery(scopeNamequery);
714 for(Object object : activePolicies){
715 PolicyVersion activeVersion = (PolicyVersion) object;
716 String policyOldPath = activeVersion.getPolicyName().replace(File.separator, "/") + "." + activeVersion.getActiveVersion() + ".xml";
717 String policyNewPath = policyOldPath.replace(oldPath, newPath);
718 policyRename(policyOldPath, policyNewPath, userId);
720 for(Object object : scopesList){
721 PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object;
722 if(scopeName.contains("\\\\\\\\")){
723 scopeName = scopeName.replace("\\\\\\\\", File.separator);
724 newScopeName = newScopeName.replace("\\\\\\\\", File.separator);
726 String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName);
727 editorScopeEntity.setScopeName(scope);
728 controller.updateData(editorScopeEntity);
732 } catch (Exception e) {
733 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
734 return error(e.getMessage());
738 private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
740 PolicyEntity entity = null;
741 PolicyController controller = new PolicyController();
743 String policyVersionName = newPath.replace(".xml", "");
744 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")).replace("/", File.separator);
746 String oldpolicyVersionName = oldPath.replace(".xml", "");
747 String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf(".")).replace("/", File.separator);
749 String newpolicyName = newPath.replace("/", ".");
750 String newPolicyCheck = newpolicyName;
751 if(newPolicyCheck.contains("Config_")){
752 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
753 }else if(newPolicyCheck.contains("Action_")){
754 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
755 }else if(newPolicyCheck.contains("Decision_")){
756 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
758 String[] newPolicySplit = newPolicyCheck.split(":");
760 String orignalPolicyName = oldPath.replace("/", ".");
761 String oldPolicyCheck = orignalPolicyName;
762 if(oldPolicyCheck.contains("Config_")){
763 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
764 }else if(oldPolicyCheck.contains("Action_")){
765 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
766 }else if(oldPolicyCheck.contains("Decision_")){
767 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
769 String[] oldPolicySplit = oldPolicyCheck.split(":");
771 //Check PolicyEntity table with newPolicy Name
772 String policyEntityquery = "FROM PolicyEntity where policyName = '"+newPolicySplit[1]+"' and scope ='"+newPolicySplit[0]+"'";
773 System.out.println(policyEntityquery);
774 List<Object> queryData = controller.getDataByQuery(policyEntityquery);
775 if(!queryData.isEmpty()){
776 entity = (PolicyEntity) queryData.get(0);
780 //if a policy exists with new name check if it is deleted or not
781 if(entity.isDeleted()){
782 //Check Policy Group Entity table if policy has been pushed or not
783 String query = "from PolicyGroupEntity where policyid = '"+entity.getPolicyId()+"'";
784 List<Object> object = controller.getDataByQuery(query);
785 if(object.isEmpty()){
786 //if PolicyGroupEntity data is empty delete the entry from database
787 controller.deleteData(entity);
788 //Query the Policy Entity with oldPolicy Name
789 String oldpolicyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'";
790 System.out.println(oldpolicyEntityquery);
791 List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery);
792 if(!oldEntityData.isEmpty()){
793 entity = (PolicyEntity) oldEntityData.get(0);
795 checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0], newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
797 return error("Policy rename failed due to policy with new name existing in PDP Group.");
800 return error("Policy rename failed due to same name existing.");
803 //Query the Policy Entity with oldPolicy Name
804 String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf("."));
805 String oldpolicyEntityquery = "FROM PolicyEntity where policyName like '"+policyEntityCheck+"%' and scope ='"+oldPolicySplit[0]+"'";
806 List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery);
807 if(!oldEntityData.isEmpty()){
808 for(int i=0; i<oldEntityData.size(); i++){
809 entity = (PolicyEntity) oldEntityData.get(i);
810 checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0] , newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
816 } catch (Exception e) {
817 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
818 return error(e.getMessage());
822 private JSONObject checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, String oldScope, String removeoldPolicyExtension,
823 String policyName, String newpolicyName, String oldpolicyName, String userId) throws ServletException{
825 ConfigurationDataEntity configEntity;
826 ActionBodyEntity actionEntity;
827 PolicyController controller = new PolicyController();
828 configEntity = entity.getConfigurationData();
829 actionEntity = entity.getActionBodyEntity();
831 //Check Policy Group Entity table if policy has been pushed or not
832 String query = "from PolicyGroupEntity where policyid = '"+entity.getPolicyId()+"'";
833 List<Object> object = controller.getDataByQuery(query);
834 if(object.isEmpty()){
835 String oldPolicyNameWithoutExtension = removeoldPolicyExtension;
836 String newPolicyNameWithoutExtension = removenewPolicyExtension;
837 if(removeoldPolicyExtension.endsWith(".xml")){
838 oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf("."));
839 newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf("."));
841 entity.setPolicyName(entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
842 entity.setPolicyData(entity.getPolicyData().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
843 entity.setScope(newScope);
844 entity.setModifiedBy(userId);
845 if(newpolicyName.contains("Config_")){
846 configEntity.setConfigurationName(configEntity.getConfigurationName().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
847 controller.updateData(configEntity);
848 }else if(newpolicyName.contains("Action_")){
849 actionEntity.setActionBody(actionEntity.getActionBody().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
850 controller.updateData(actionEntity);
852 controller.updateData(entity);
854 //Mark as Deleted in PolicyEntiy table
855 entity.setDeleted(true);
856 controller.updateData(entity);
857 //Mark as Deleted in ConfigurationDataEntity table
858 configEntity.setDeleted(true);
859 controller.updateData(configEntity);
860 //Mark as Deleted in ActionDataEntity table
861 actionEntity.setDeleted(true);
862 controller.updateData(actionEntity);
864 cloneRecord(newpolicyName, oldScope, removeoldPolicyExtension, newScope, removenewPolicyExtension, entity, userId);
867 PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldpolicyName);
868 versionEntity.setPolicyName(policyName);
869 versionEntity.setModifiedBy(userId);
870 controller.updateData(versionEntity);
871 String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator)+1);
872 String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
873 if(movePolicyCheck.equals(moveOldPolicyCheck)){
874 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move");
876 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename");
880 } catch (Exception e) {
881 LOGGER.error("Exception Occured"+e);
882 return error(e.getMessage());
886 private JSONObject cloneRecord(String newpolicyName, String oldScope, String removeoldPolicyExtension, String newScope, String removenewPolicyExtension, PolicyEntity entity, String userId) throws ServletException{
887 String queryEntityName = null;
888 PolicyController controller = new PolicyController();
889 PolicyEntity cloneEntity = new PolicyEntity();
890 cloneEntity.setPolicyName(newpolicyName);
891 removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
892 removenewPolicyExtension = removenewPolicyExtension.replace(".xml", "");
893 cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope+"."+removeoldPolicyExtension, newScope+"."+removenewPolicyExtension));
894 cloneEntity.setScope(entity.getScope());
895 String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
896 String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
897 if(newpolicyName.contains("Config_")){
898 ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
899 configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
900 queryEntityName = configurationDataEntity.getConfigurationName();
901 configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody());
902 configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType());
903 configurationDataEntity.setDeleted(false);
904 configurationDataEntity.setCreatedBy(userId);
905 configurationDataEntity.setModifiedBy(userId);
906 controller.saveData(configurationDataEntity);
907 ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
908 cloneEntity.setConfigurationData(configEntiy);
909 }else if(newpolicyName.contains("Action_")){
910 ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
911 actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
912 queryEntityName = actionBodyEntity.getActionBodyName();
913 actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody());
914 actionBodyEntity.setDeleted(false);
915 actionBodyEntity.setCreatedBy(userId);
916 actionBodyEntity.setModifiedBy(userId);
917 controller.saveData(actionBodyEntity);
918 ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class, "actionBodyName", queryEntityName);
919 cloneEntity.setActionBodyEntity(actionEntiy);
921 cloneEntity.setDeleted(entity.isDeleted());
922 cloneEntity.setCreatedBy(userId);
923 cloneEntity.setModifiedBy(userId);
924 controller.saveData(cloneEntity);
930 private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
932 String userId = UserUtils.getUserSession(request).getOrgUserId();
933 String oldPath = params.getString("path");
934 String newPath = params.getString("newPath");
935 oldPath = oldPath.substring(oldPath.indexOf("/")+1);
936 newPath = newPath.substring(newPath.indexOf("/")+1);
938 String policyVersionName = newPath.replace(".xml", "");
939 String version = policyVersionName.substring(policyVersionName.indexOf(".")+1);
940 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")).replace("/", File.separator);
942 String newpolicyName = newPath.replace("/", ".");
944 String orignalPolicyName = oldPath.replace("/", ".");
946 String newPolicyCheck = newpolicyName;
947 if(newPolicyCheck.contains("Config_")){
948 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
949 }else if(newPolicyCheck.contains("Action_")){
950 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
951 }else if(newPolicyCheck.contains("Decision_")){
952 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
954 String[] newPolicySplit = newPolicyCheck.split(":");
956 String oldPolicyCheck = orignalPolicyName;
957 if(oldPolicyCheck.contains("Config_")){
958 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
959 }else if(oldPolicyCheck.contains("Action_")){
960 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
961 }else if(oldPolicyCheck.contains("Decision_")){
962 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
964 String[] oldPolicySplit = oldPolicyCheck.split(":");
966 PolicyController controller = new PolicyController();
968 PolicyEntity entity = null;
969 boolean success = false;
971 //Check PolicyEntity table with newPolicy Name
972 String policyEntityquery = "FROM PolicyEntity where policyName = '"+newPolicySplit[1]+"' and scope ='"+newPolicySplit[0]+"'";
973 System.out.println(policyEntityquery);
974 List<Object> queryData = controller.getDataByQuery(policyEntityquery);
975 if(!queryData.isEmpty()){
976 entity = (PolicyEntity) queryData.get(0);
979 //if a policy exists with new name check if it is deleted or not
980 if(entity.isDeleted()){
981 //Check Policy Group Entity table if policy has been pushed or not
982 String query = "from PolicyGroupEntity where policyid = '"+entity.getPolicyId()+"'";
983 List<Object> object = controller.getDataByQuery(query);
985 //if PolicyGroupEntity data is empty delete the entry from database
986 controller.deleteData(entity);
987 //Query the Policy Entity with oldPolicy Name
988 policyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'";
989 System.out.println(policyEntityquery);
990 queryData = controller.getDataByQuery(policyEntityquery);
991 if(!queryData.isEmpty()){
992 entity = (PolicyEntity) queryData.get(0);
995 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId);
999 return error("Policy Clone failed due to policy with new name existing in PDP Group.");
1002 return error("Policy Clone failed due to same name existing.");
1005 //Query the Policy Entity with oldPolicy Name
1006 policyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'";
1007 System.out.println(policyEntityquery);
1008 queryData = controller.getDataByQuery(policyEntityquery);
1009 if(!queryData.isEmpty()){
1010 entity = (PolicyEntity) queryData.get(0);
1013 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId);
1018 PolicyVersion entityItem = new PolicyVersion();
1019 entityItem.setActiveVersion(Integer.parseInt(version));
1020 entityItem.setHigherVersion(Integer.parseInt(version));
1021 entityItem.setPolicyName(policyName);
1022 entityItem.setCreatedBy(userId);
1023 entityItem.setModifiedBy(userId);
1024 controller.saveData(entityItem);
1027 LOGGER.debug("copy from: {} to: {}" + oldPath +newPath);
1030 } catch (Exception e) {
1031 LOGGER.error("copy", e);
1032 return error(e.getMessage());
1036 //Delete Policy or Scope Functionality
1037 private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
1038 PolicyController controller = new PolicyController();
1039 PolicyRestController restController = new PolicyRestController();
1040 PolicyEntity policyEntity = null;
1041 String policyNamewithoutExtension;
1043 String userId = UserUtils.getUserSession(request).getOrgUserId();
1044 String deleteVersion = "";
1045 String path = params.getString("path");
1046 LOGGER.debug("delete {}" +path);
1047 if(params.has("deleteVersion")){
1048 deleteVersion = params.getString("deleteVersion");
1050 path = path.substring(path.indexOf("/")+1);
1051 String policyNamewithExtension = path.replace("/", File.separator);
1052 String policyVersionName = policyNamewithExtension.replace(".xml", "");
1054 if(path.endsWith(".xml")){
1055 policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf("."));
1056 policyNamewithoutExtension = policyNamewithoutExtension.replace(File.separator, ".");
1057 String splitPolicyName = null;
1058 if(policyNamewithoutExtension.contains("Config_")){
1059 splitPolicyName = policyNamewithoutExtension.replace(".Config_", ":Config_");
1060 }else if(policyNamewithoutExtension.contains("Action_")){
1061 splitPolicyName = policyNamewithoutExtension.replace(".Action_", ":Action_");
1062 }else if(policyNamewithoutExtension.contains("Decision_")){
1063 splitPolicyName = policyNamewithoutExtension.replace(".Decision_", ":Decision_");
1065 String[] split = splitPolicyName.split(":");
1066 query = "FROM PolicyEntity where policyName like '"+split[1]+"%' and scope ='"+split[0]+"'";
1068 policyNamewithoutExtension = path.replace(File.separator, ".");
1069 query = "FROM PolicyEntity where scope like '"+policyNamewithoutExtension+"%'";
1072 List<Object> policyEntityobjects = controller.getDataByQuery(query);
1073 String activePolicyName = null;
1074 boolean pdpCheck = false;
1075 if(path.endsWith(".xml")){
1076 policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator);
1077 int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf(".")+1));
1078 if("ALL".equals(deleteVersion)){
1079 if(!policyEntityobjects.isEmpty()){
1080 for(Object object : policyEntityobjects){
1081 policyEntity = (PolicyEntity) object;
1082 String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'";
1083 List<Object> groupobject = controller.getDataByQuery(groupEntityquery);
1084 if(!groupobject.isEmpty()){
1086 activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName();
1088 //Delete the entity from Elastic Search Database
1089 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1090 restController.deleteElasticData(searchFileName);
1091 //Delete the entity from Policy Entity table
1092 controller.deleteData(policyEntity);
1093 if(policyNamewithoutExtension.contains("Config_")){
1094 controller.deleteData(policyEntity.getConfigurationData());
1095 }else if(policyNamewithoutExtension.contains("Action_")){
1096 controller.deleteData(policyEntity.getActionBodyEntity());
1101 //Policy Notification
1102 PolicyVersion versionEntity = new PolicyVersion();
1103 versionEntity.setPolicyName(policyNamewithoutExtension);
1104 versionEntity.setModifiedBy(userId);
1105 controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll");
1107 //Delete from policyVersion table
1108 String getActivePDPPolicyVersion = activePolicyName.replace(".xml", "");
1109 getActivePDPPolicyVersion = getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf(".")+1);
1110 String policyVersionQuery = "update PolicyVersion set active_version='"+getActivePDPPolicyVersion+"' , highest_version='"+getActivePDPPolicyVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1111 if(policyVersionQuery != null){
1112 controller.executeQuery(policyVersionQuery);
1114 return error("Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "+activePolicyName);
1116 //No Active Policy in PDP. So, deleting all entries from policyVersion table
1117 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1118 if(policyVersionQuery != null){
1119 controller.executeQuery(policyVersionQuery);
1122 }else if("CURRENT".equals(deleteVersion)){
1123 String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1);
1124 String currentVersionScope = policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator)).replace(File.separator, ".");
1125 query = "FROM PolicyEntity where policyName = '"+currentVersionPolicyName+"' and scope ='"+currentVersionScope+"'";
1126 List<Object> policyEntitys = controller.getDataByQuery(query);
1127 if(!policyEntitys.isEmpty()){
1128 policyEntity = (PolicyEntity) policyEntitys.get(0);
1130 if(policyEntity != null){
1131 String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"' and policyid > 0";
1132 List<Object> groupobject = controller.getDataByQuery(groupEntityquery);
1133 if(groupobject.isEmpty()){
1134 //Delete the entity from Elastic Search Database
1135 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1136 restController.deleteElasticData(searchFileName);
1137 //Delete the entity from Policy Entity table
1138 controller.deleteData(policyEntity);
1139 if(policyNamewithoutExtension.contains("Config_")){
1140 controller.deleteData(policyEntity.getConfigurationData());
1141 }else if(policyNamewithoutExtension.contains("Action_")){
1142 controller.deleteData(policyEntity.getActionBodyEntity());
1146 int highestVersion = 0;
1147 if(!policyEntityobjects.isEmpty()){
1148 for(Object object : policyEntityobjects){
1149 policyEntity = (PolicyEntity) object;
1150 String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
1151 int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf(".")+1));
1152 if(policyEntityVersion > highestVersion){
1153 highestVersion = policyEntityVersion;
1158 //Policy Notification
1159 PolicyVersion entity = new PolicyVersion();
1160 entity.setPolicyName(policyNamewithoutExtension);
1161 entity.setActiveVersion(highestVersion);
1162 entity.setModifiedBy(userId);
1163 controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne");
1165 String updatequery = "update PolicyVersion set active_version='"+highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"'";
1166 controller.executeQuery(updatequery);
1168 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1169 if(policyVersionQuery != null){
1170 controller.executeQuery(policyVersionQuery);
1174 return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'");
1179 List<String> activePoliciesInPDP = new ArrayList<String>();
1180 if(!policyEntityobjects.isEmpty()){
1181 for(Object object : policyEntityobjects){
1182 policyEntity = (PolicyEntity) object;
1183 String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'";
1184 List<Object> groupobject = controller.getDataByQuery(groupEntityquery);
1185 if(!groupobject.isEmpty()){
1187 activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName());
1189 //Delete the entity from Elastic Search Database
1190 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1191 restController.deleteElasticData(searchFileName);
1192 //Delete the entity from Policy Entity table
1193 controller.deleteData(policyEntity);
1194 policyNamewithoutExtension = policyEntity.getPolicyName();
1195 if(policyNamewithoutExtension.contains("Config_")){
1196 controller.deleteData(policyEntity.getConfigurationData());
1197 }else if(policyNamewithoutExtension.contains("Action_")){
1198 controller.deleteData(policyEntity.getActionBodyEntity());
1202 //Delete from policyVersion and policyEditor Scope table
1203 String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1204 controller.executeQuery(policyVersionQuery);
1206 //Policy Notification
1207 PolicyVersion entity = new PolicyVersion();
1208 entity.setPolicyName(path);
1209 entity.setModifiedBy(userId);
1210 controller.watchPolicyFunction(entity, path, "DeleteScope");
1212 //Add Active Policies List to PolicyVersionTable
1213 for(int i =0; i < activePoliciesInPDP.size(); i++){
1214 String activePDPPolicyName = activePoliciesInPDP.get(i).replace(".xml", "");
1215 int activePDPPolicyVersion = Integer.parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf(".")+1));
1216 activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf(".")).replace(".", File.separator);
1217 PolicyVersion insertactivePDPVersion = new PolicyVersion();
1218 insertactivePDPVersion.setPolicyName(activePDPPolicyName);
1219 insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion);
1220 insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion);
1221 insertactivePDPVersion.setCreatedBy(userId);
1222 insertactivePDPVersion.setModifiedBy(userId);
1223 controller.saveData(insertactivePDPVersion);
1226 return error("All the Policies has been deleted in Scope. Except the following list of Policies:"+activePoliciesInPDP);
1228 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1229 controller.executeQuery(policyScopeQuery);
1232 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1233 controller.executeQuery(policyScopeQuery);
1237 } catch (Exception e) {
1238 LOGGER.error("delete", e);
1239 return error(e.getMessage());
1244 private JSONObject editFile(JSONObject params) throws ServletException {
1247 PolicyController controller = new PolicyController();
1248 String mode = params.getString("mode");
1249 String path = params.getString("path");
1250 LOGGER.debug("editFile path: {}"+ path);
1252 String domain = path.substring(1, path.lastIndexOf("/"));
1253 domain = domain.replace("/", ".");
1255 path = path.substring(1);
1256 path = path.replace("/", ".");
1257 String dbCheckName = path;
1258 if(dbCheckName.contains("Config_")){
1259 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
1260 }else if(dbCheckName.contains("Action_")){
1261 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
1262 }else if(dbCheckName.contains("Decision_")){
1263 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
1266 String[] split = dbCheckName.split(":");
1267 String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'";
1268 List<Object> queryData = controller.getDataByQuery(query);
1269 PolicyEntity entity = (PolicyEntity) queryData.get(0);
1270 InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
1273 Object policy = XACMLPolicyScanner.readPolicy(stream);
1274 PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
1275 policyAdapter.setData(policy);
1277 if("viewPolicy".equalsIgnoreCase(mode)){
1278 policyAdapter.setReadOnly(true);
1279 policyAdapter.setEditPolicy(false);
1281 policyAdapter.setReadOnly(false);
1282 policyAdapter.setEditPolicy(true);
1284 policyAdapter.setDomain(domain);
1285 policyAdapter.setDomainDir(domain);
1286 policyAdapter.setPolicyData(policy);
1287 String policyName = path.replace(".xml", "");
1288 policyName = policyName.substring(0, policyName.lastIndexOf("."));
1289 policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf(".")+1));
1291 PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance();
1292 setpolicyAdapter.configure(policyAdapter,entity);
1294 policyAdapter.setParentPath(null);
1295 ObjectMapper mapper = new ObjectMapper();
1296 String json = mapper.writeValueAsString(policyAdapter);
1297 JsonNode jsonNode = mapper.readTree(json);
1299 return new JSONObject().put(RESULT, jsonNode);
1300 } catch (Exception e) {
1301 LOGGER.error("editFile", e);
1302 return error(e.getMessage());
1307 private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
1308 PolicyController controller = new PolicyController();
1311 String userId = UserUtils.getUserSession(request).getOrgUserId();
1312 String path = params.getString("path");
1314 if(params.has("subScopename")){
1315 if(!params.getString("subScopename").equals("")){
1316 name = params.getString("path").replace("/", File.separator) + File.separator +params.getString("subScopename");
1319 name = params.getString("name");
1321 }catch(Exception e){
1322 name = params.getString("name");
1323 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e);
1325 String validateName;
1326 if(name.contains(File.separator)){
1327 validateName = name.substring(name.lastIndexOf(File.separator)+1);
1329 validateName = name;
1331 if(!name.isEmpty()){
1332 String validate = PolicyUtils.emptyPolicyValidator(validateName);
1333 if(!validate.contains("success")){
1334 return error(validate);
1337 LOGGER.debug("addFolder path: {} name: {}" + path +name);
1338 if(!name.equals("")){
1339 PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, "scopeName", name);
1341 UserInfo userInfo = new UserInfo();
1342 userInfo.setUserLoginId(userId);
1343 PolicyEditorScopes newScope = new PolicyEditorScopes();
1344 String scopeName = null;
1345 if(name.startsWith(File.separator)){
1346 scopeName = name.substring(1);
1350 newScope.setScopeName(scopeName);
1351 newScope.setUserCreatedBy(userInfo);
1352 newScope.setUserModifiedBy(userInfo);
1353 controller.saveData(newScope);
1355 return error("Scope Already Exists");
1359 } catch (Exception e) {
1360 LOGGER.error("addFolder", e);
1361 return error(e.getMessage());
1365 //Return Error Object
1366 private JSONObject error(String msg) throws ServletException {
1368 JSONObject result = new JSONObject();
1369 result.put("success", false);
1370 result.put("error", msg);
1371 return new JSONObject().put(RESULT, result);
1372 } catch (JSONException e) {
1373 throw new ServletException(e);
1377 //Return Success Object
1378 private JSONObject success() throws ServletException {
1380 JSONObject result = new JSONObject();
1381 result.put("success", true);
1382 result.put("error", (Object) null);
1383 return new JSONObject().put(RESULT, result);
1384 } catch (JSONException e) {
1385 throw new ServletException(e);