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) {
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;
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) {
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 return userInfo.getUserName();
686 private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
688 String userId = UserUtils.getUserSession(request).getOrgUserId();
689 String oldPath = params.getString("path");
690 String newPath = params.getString("newPath");
691 oldPath = oldPath.substring(oldPath.indexOf("/")+1);
692 newPath = newPath.substring(newPath.indexOf("/")+1);
693 if(oldPath.endsWith(".xml")){
694 policyRename(oldPath, newPath, userId);
696 String scopeName = oldPath;
697 String newScopeName = newPath;
698 if(scopeName.contains("/")){
699 scopeName = scopeName.replace("/", File.separator);
700 newScopeName = newScopeName.replace("/", File.separator);
702 if(scopeName.contains("\\")){
703 scopeName = scopeName.replace("\\", "\\\\\\\\");
704 newScopeName = newScopeName.replace("\\", "\\\\\\\\");
706 PolicyController controller = new PolicyController();
707 String query = "from PolicyVersion where POLICY_NAME like'" +scopeName+"%'";
708 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"%'";
709 List<Object> activePolicies = controller.getDataByQuery(query);
710 List<Object> scopesList = controller.getDataByQuery(scopeNamequery);
711 for(Object object : activePolicies){
712 PolicyVersion activeVersion = (PolicyVersion) object;
713 String policyOldPath = activeVersion.getPolicyName().replace(File.separator, "/") + "." + activeVersion.getActiveVersion() + ".xml";
714 String policyNewPath = policyOldPath.replace(oldPath, newPath);
715 policyRename(policyOldPath, policyNewPath, userId);
717 for(Object object : scopesList){
718 PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object;
719 if(scopeName.contains("\\\\\\\\")){
720 scopeName = scopeName.replace("\\\\\\\\", File.separator);
721 newScopeName = newScopeName.replace("\\\\\\\\", File.separator);
723 String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName);
724 editorScopeEntity.setScopeName(scope);
725 controller.updateData(editorScopeEntity);
729 } catch (Exception e) {
730 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
731 return error(e.getMessage());
735 private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
737 PolicyEntity entity = null;
738 PolicyController controller = new PolicyController();
740 String policyVersionName = newPath.replace(".xml", "");
741 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")).replace("/", File.separator);
743 String oldpolicyVersionName = oldPath.replace(".xml", "");
744 String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf(".")).replace("/", File.separator);
746 String newpolicyName = newPath.replace("/", ".");
747 String newPolicyCheck = newpolicyName;
748 if(newPolicyCheck.contains("Config_")){
749 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
750 }else if(newPolicyCheck.contains("Action_")){
751 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
752 }else if(newPolicyCheck.contains("Decision_")){
753 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
755 String[] newPolicySplit = newPolicyCheck.split(":");
757 String orignalPolicyName = oldPath.replace("/", ".");
758 String oldPolicyCheck = orignalPolicyName;
759 if(oldPolicyCheck.contains("Config_")){
760 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
761 }else if(oldPolicyCheck.contains("Action_")){
762 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
763 }else if(oldPolicyCheck.contains("Decision_")){
764 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
766 String[] oldPolicySplit = oldPolicyCheck.split(":");
768 //Check PolicyEntity table with newPolicy Name
769 String policyEntityquery = "FROM PolicyEntity where policyName = '"+newPolicySplit[1]+"' and scope ='"+newPolicySplit[0]+"'";
770 System.out.println(policyEntityquery);
771 List<Object> queryData = controller.getDataByQuery(policyEntityquery);
772 if(!queryData.isEmpty()){
773 entity = (PolicyEntity) queryData.get(0);
777 //if a policy exists with new name check if it is deleted or not
778 if(entity.isDeleted()){
779 //Check Policy Group Entity table if policy has been pushed or not
780 String query = "from PolicyGroupEntity where policyid = '"+entity.getPolicyId()+"'";
781 List<Object> object = controller.getDataByQuery(query);
782 if(object.isEmpty()){
783 //if PolicyGroupEntity data is empty delete the entry from database
784 controller.deleteData(entity);
785 //Query the Policy Entity with oldPolicy Name
786 String oldpolicyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'";
787 System.out.println(oldpolicyEntityquery);
788 List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery);
789 if(!oldEntityData.isEmpty()){
790 entity = (PolicyEntity) oldEntityData.get(0);
792 checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0], newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
794 return error("Policy rename failed due to policy with new name existing in PDP Group.");
797 return error("Policy rename failed due to same name existing.");
800 //Query the Policy Entity with oldPolicy Name
801 String oldpolicyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'";
802 System.out.println(oldpolicyEntityquery);
803 List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery);
804 if(!oldEntityData.isEmpty()){
805 entity = (PolicyEntity) oldEntityData.get(0);
807 checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0] , newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
811 } catch (Exception e) {
812 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
813 return error(e.getMessage());
817 private JSONObject checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, String oldScope, String removeoldPolicyExtension,
818 String policyName, String newpolicyName, String oldpolicyName, String userId) throws ServletException{
820 ConfigurationDataEntity configEntity;
821 ActionBodyEntity actionEntity;
822 PolicyController controller = new PolicyController();
823 configEntity = entity.getConfigurationData();
824 actionEntity = entity.getActionBodyEntity();
826 //Check Policy Group Entity table if policy has been pushed or not
827 String query = "from PolicyGroupEntity where policyid = '"+entity.getPolicyId()+"'";
828 List<Object> object = controller.getDataByQuery(query);
829 if(object.isEmpty()){
830 String oldPolicyNameWithoutExtension = removeoldPolicyExtension;
831 String newPolicyNameWithoutExtension = removenewPolicyExtension;
832 if(removeoldPolicyExtension.endsWith(".xml")){
833 oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf("."));
834 newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf("."));
836 entity.setPolicyName(entity.getPolicyName().replace(removeoldPolicyExtension, removenewPolicyExtension));
837 entity.setPolicyData(entity.getPolicyData().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
838 entity.setScope(newScope);
839 entity.setModifiedBy(userId);
840 String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
841 String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
842 if(newpolicyName.contains("Config_")){
843 configEntity.setConfigurationName(configEntity.getConfigurationName().replace(oldScope +"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
844 controller.updateData(configEntity);
845 }else if(newpolicyName.contains("Action_")){
846 actionEntity.setActionBody(actionEntity.getActionBody().replace(oldScope +"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
847 controller.updateData(actionEntity);
849 controller.updateData(entity);
851 //Mark as Deleted in PolicyEntiy table
852 entity.setDeleted(true);
853 controller.updateData(entity);
854 //Mark as Deleted in ConfigurationDataEntity table
855 configEntity.setDeleted(true);
856 controller.updateData(configEntity);
857 //Mark as Deleted in ActionDataEntity table
858 actionEntity.setDeleted(true);
859 controller.updateData(actionEntity);
861 cloneRecord(newpolicyName, oldScope, removeoldPolicyExtension, newScope, removenewPolicyExtension, entity, userId);
864 PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldpolicyName);
865 versionEntity.setPolicyName(policyName);
866 versionEntity.setModifiedBy(userId);
867 controller.updateData(versionEntity);
868 String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator)+1);
869 String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
870 if(movePolicyCheck.equals(moveOldPolicyCheck)){
871 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move");
873 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename");
877 } catch (Exception e) {
879 return error(e.getMessage());
883 private JSONObject cloneRecord(String newpolicyName, String oldScope, String removeoldPolicyExtension, String newScope, String removenewPolicyExtension, PolicyEntity entity, String userId) throws ServletException{
884 String queryEntityName = null;
885 PolicyController controller = new PolicyController();
886 PolicyEntity cloneEntity = new PolicyEntity();
887 cloneEntity.setPolicyName(newpolicyName);
888 removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
889 removenewPolicyExtension = removenewPolicyExtension.replace(".xml", "");
890 cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope+"."+removeoldPolicyExtension, newScope+"."+removenewPolicyExtension));
891 cloneEntity.setScope(entity.getScope());
892 String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
893 String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
894 if(newpolicyName.contains("Config_")){
895 ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
896 configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
897 queryEntityName = configurationDataEntity.getConfigurationName();
898 configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody());
899 configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType());
900 configurationDataEntity.setDeleted(false);
901 configurationDataEntity.setCreatedBy(userId);
902 configurationDataEntity.setModifiedBy(userId);
903 controller.saveData(configurationDataEntity);
904 ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
905 cloneEntity.setConfigurationData(configEntiy);
906 }else if(newpolicyName.contains("Action_")){
907 ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
908 actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
909 queryEntityName = actionBodyEntity.getActionBodyName();
910 actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody());
911 actionBodyEntity.setDeleted(false);
912 actionBodyEntity.setCreatedBy(userId);
913 actionBodyEntity.setModifiedBy(userId);
914 controller.saveData(actionBodyEntity);
915 ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class, "actionBodyName", queryEntityName);
916 cloneEntity.setActionBodyEntity(actionEntiy);
918 cloneEntity.setDeleted(entity.isDeleted());
919 cloneEntity.setCreatedBy(userId);
920 cloneEntity.setModifiedBy(userId);
921 controller.saveData(cloneEntity);
927 private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
929 String userId = UserUtils.getUserSession(request).getOrgUserId();
930 String oldPath = params.getString("path");
931 String newPath = params.getString("newPath");
932 oldPath = oldPath.substring(oldPath.indexOf("/")+1);
933 newPath = newPath.substring(newPath.indexOf("/")+1);
935 String policyVersionName = newPath.replace(".xml", "");
936 String version = policyVersionName.substring(policyVersionName.indexOf(".")+1);
937 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")).replace("/", File.separator);
939 String newpolicyName = newPath.replace("/", ".");
941 String orignalPolicyName = oldPath.replace("/", ".");
943 String newPolicyCheck = newpolicyName;
944 if(newPolicyCheck.contains("Config_")){
945 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
946 }else if(newPolicyCheck.contains("Action_")){
947 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
948 }else if(newPolicyCheck.contains("Decision_")){
949 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
951 String[] newPolicySplit = newPolicyCheck.split(":");
953 String oldPolicyCheck = orignalPolicyName;
954 if(oldPolicyCheck.contains("Config_")){
955 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
956 }else if(oldPolicyCheck.contains("Action_")){
957 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
958 }else if(oldPolicyCheck.contains("Decision_")){
959 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
961 String[] oldPolicySplit = oldPolicyCheck.split(":");
963 PolicyController controller = new PolicyController();
965 PolicyEntity entity = null;
966 boolean success = false;
968 //Check PolicyEntity table with newPolicy Name
969 String policyEntityquery = "FROM PolicyEntity where policyName = '"+newPolicySplit[1]+"' and scope ='"+newPolicySplit[0]+"'";
970 System.out.println(policyEntityquery);
971 List<Object> queryData = controller.getDataByQuery(policyEntityquery);
972 if(!queryData.isEmpty()){
973 entity = (PolicyEntity) queryData.get(0);
976 //if a policy exists with new name check if it is deleted or not
977 if(entity.isDeleted()){
978 //Check Policy Group Entity table if policy has been pushed or not
979 String query = "from PolicyGroupEntity where policyid = '"+entity.getPolicyId()+"'";
980 List<Object> object = controller.getDataByQuery(query);
982 //if PolicyGroupEntity data is empty delete the entry from database
983 controller.deleteData(entity);
984 //Query the Policy Entity with oldPolicy Name
985 policyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'";
986 System.out.println(policyEntityquery);
987 queryData = controller.getDataByQuery(policyEntityquery);
988 if(!queryData.isEmpty()){
989 entity = (PolicyEntity) queryData.get(0);
992 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId);
996 return error("Policy Clone failed due to policy with new name existing in PDP Group.");
999 return error("Policy Clone failed due to same name existing.");
1002 //Query the Policy Entity with oldPolicy Name
1003 policyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'";
1004 System.out.println(policyEntityquery);
1005 queryData = controller.getDataByQuery(policyEntityquery);
1006 if(!queryData.isEmpty()){
1007 entity = (PolicyEntity) queryData.get(0);
1010 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId);
1015 PolicyVersion entityItem = new PolicyVersion();
1016 entityItem.setActiveVersion(Integer.parseInt(version));
1017 entityItem.setHigherVersion(Integer.parseInt(version));
1018 entityItem.setPolicyName(policyName);
1019 entityItem.setCreatedBy(userId);
1020 entityItem.setModifiedBy(userId);
1021 controller.saveData(entityItem);
1024 LOGGER.debug("copy from: {} to: {}" + oldPath +newPath);
1027 } catch (Exception e) {
1028 LOGGER.error("copy", e);
1029 return error(e.getMessage());
1033 //Delete Policy or Scope Functionality
1034 private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
1035 PolicyController controller = new PolicyController();
1036 PolicyRestController restController = new PolicyRestController();
1037 PolicyEntity policyEntity = null;
1038 String policyNamewithoutExtension;
1040 String userId = UserUtils.getUserSession(request).getOrgUserId();
1041 String deleteVersion = "";
1042 String path = params.getString("path");
1043 LOGGER.debug("delete {}" +path);
1044 if(params.has("deleteVersion")){
1045 deleteVersion = params.getString("deleteVersion");
1047 path = path.substring(path.indexOf("/")+1);
1048 String policyNamewithExtension = path.replace("/", File.separator);
1049 String policyVersionName = policyNamewithExtension.replace(".xml", "");
1051 if(path.endsWith(".xml")){
1052 policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf("."));
1053 policyNamewithoutExtension = policyNamewithoutExtension.replace(File.separator, ".");
1054 String splitPolicyName = null;
1055 if(policyNamewithoutExtension.contains("Config_")){
1056 splitPolicyName = policyNamewithoutExtension.replace(".Config_", ":Config_");
1057 }else if(policyNamewithoutExtension.contains("Action_")){
1058 splitPolicyName = policyNamewithoutExtension.replace(".Action_", ":Action_");
1059 }else if(policyNamewithoutExtension.contains("Decision_")){
1060 splitPolicyName = policyNamewithoutExtension.replace(".Decision_", ":Decision_");
1062 String[] split = splitPolicyName.split(":");
1063 query = "FROM PolicyEntity where policyName like '"+split[1]+"%' and scope ='"+split[0]+"'";
1065 policyNamewithoutExtension = path.replace(File.separator, ".");
1066 query = "FROM PolicyEntity where scope like '"+policyNamewithoutExtension+"%'";
1069 List<Object> policyEntityobjects = controller.getDataByQuery(query);
1070 String activePolicyName = null;
1071 boolean pdpCheck = false;
1072 if(path.endsWith(".xml")){
1073 policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator);
1074 int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf(".")+1));
1075 if("ALL".equals(deleteVersion)){
1076 if(!policyEntityobjects.isEmpty()){
1077 for(Object object : policyEntityobjects){
1078 policyEntity = (PolicyEntity) object;
1079 String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'";
1080 List<Object> groupobject = controller.getDataByQuery(groupEntityquery);
1081 if(!groupobject.isEmpty()){
1083 activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName();
1085 //Delete the entity from Elastic Search Database
1086 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1087 restController.deleteElasticData(searchFileName);
1088 //Delete the entity from Policy Entity table
1089 controller.deleteData(policyEntity);
1090 if(policyNamewithoutExtension.contains("Config_")){
1091 controller.deleteData(policyEntity.getConfigurationData());
1092 }else if(policyNamewithoutExtension.contains("Action_")){
1093 controller.deleteData(policyEntity.getActionBodyEntity());
1098 //Policy Notification
1099 PolicyVersion versionEntity = new PolicyVersion();
1100 versionEntity.setPolicyName(policyNamewithoutExtension);
1101 versionEntity.setModifiedBy(userId);
1102 controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll");
1104 //Delete from policyVersion table
1105 String getActivePDPPolicyVersion = activePolicyName.replace(".xml", "");
1106 getActivePDPPolicyVersion = getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf(".")+1);
1107 String policyVersionQuery = "update PolicyVersion set active_version='"+getActivePDPPolicyVersion+"' , highest_version='"+getActivePDPPolicyVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1108 if(policyVersionQuery != null){
1109 controller.executeQuery(policyVersionQuery);
1111 return error("Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "+activePolicyName);
1113 //No Active Policy in PDP. So, deleting all entries from policyVersion table
1114 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1115 if(policyVersionQuery != null){
1116 controller.executeQuery(policyVersionQuery);
1119 }else if("CURRENT".equals(deleteVersion)){
1120 String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1);
1121 String currentVersionScope = policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator)).replace(File.separator, ".");
1122 query = "FROM PolicyEntity where policyName = '"+currentVersionPolicyName+"' and scope ='"+currentVersionScope+"'";
1123 List<Object> policyEntitys = controller.getDataByQuery(query);
1124 if(!policyEntitys.isEmpty()){
1125 policyEntity = (PolicyEntity) policyEntitys.get(0);
1127 if(policyEntity != null){
1128 String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"' and policyid > 0";
1129 List<Object> groupobject = controller.getDataByQuery(groupEntityquery);
1130 if(groupobject.isEmpty()){
1131 //Delete the entity from Elastic Search Database
1132 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1133 restController.deleteElasticData(searchFileName);
1134 //Delete the entity from Policy Entity table
1135 controller.deleteData(policyEntity);
1136 if(policyNamewithoutExtension.contains("Config_")){
1137 controller.deleteData(policyEntity.getConfigurationData());
1138 }else if(policyNamewithoutExtension.contains("Action_")){
1139 controller.deleteData(policyEntity.getActionBodyEntity());
1143 int highestVersion = 0;
1144 if(!policyEntityobjects.isEmpty()){
1145 for(Object object : policyEntityobjects){
1146 policyEntity = (PolicyEntity) object;
1147 String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
1148 int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf(".")+1));
1149 if(policyEntityVersion > highestVersion){
1150 highestVersion = policyEntityVersion;
1155 //Policy Notification
1156 PolicyVersion entity = new PolicyVersion();
1157 entity.setPolicyName(policyNamewithoutExtension);
1158 entity.setActiveVersion(highestVersion);
1159 entity.setModifiedBy(userId);
1160 controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne");
1162 String updatequery = "update PolicyVersion set active_version='"+highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"'";
1163 controller.executeQuery(updatequery);
1165 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1166 if(policyVersionQuery != null){
1167 controller.executeQuery(policyVersionQuery);
1171 return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'");
1176 List<String> activePoliciesInPDP = new ArrayList<String>();
1177 if(!policyEntityobjects.isEmpty()){
1178 for(Object object : policyEntityobjects){
1179 policyEntity = (PolicyEntity) object;
1180 String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'";
1181 List<Object> groupobject = controller.getDataByQuery(groupEntityquery);
1182 if(!groupobject.isEmpty()){
1184 activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName());
1186 //Delete the entity from Elastic Search Database
1187 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1188 restController.deleteElasticData(searchFileName);
1189 //Delete the entity from Policy Entity table
1190 controller.deleteData(policyEntity);
1191 policyNamewithoutExtension = policyEntity.getPolicyName();
1192 if(policyNamewithoutExtension.contains("Config_")){
1193 controller.deleteData(policyEntity.getConfigurationData());
1194 }else if(policyNamewithoutExtension.contains("Action_")){
1195 controller.deleteData(policyEntity.getActionBodyEntity());
1199 //Delete from policyVersion and policyEditor Scope table
1200 String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1201 controller.executeQuery(policyVersionQuery);
1203 //Policy Notification
1204 PolicyVersion entity = new PolicyVersion();
1205 entity.setPolicyName(path);
1206 entity.setModifiedBy(userId);
1207 controller.watchPolicyFunction(entity, path, "DeleteScope");
1209 //Add Active Policies List to PolicyVersionTable
1210 for(int i =0; i < activePoliciesInPDP.size(); i++){
1211 String activePDPPolicyName = activePoliciesInPDP.get(i).replace(".xml", "");
1212 int activePDPPolicyVersion = Integer.parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf(".")+1));
1213 activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf(".")).replace(".", File.separator);
1214 PolicyVersion insertactivePDPVersion = new PolicyVersion();
1215 insertactivePDPVersion.setPolicyName(activePDPPolicyName);
1216 insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion);
1217 insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion);
1218 insertactivePDPVersion.setCreatedBy(userId);
1219 insertactivePDPVersion.setModifiedBy(userId);
1220 controller.saveData(insertactivePDPVersion);
1223 return error("All the Policies has been deleted in Scope. Except the following list of Policies:"+activePoliciesInPDP);
1225 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1226 controller.executeQuery(policyScopeQuery);
1231 } catch (Exception e) {
1232 LOGGER.error("delete", e);
1233 return error(e.getMessage());
1238 private JSONObject editFile(JSONObject params) throws ServletException {
1241 PolicyController controller = new PolicyController();
1242 String mode = params.getString("mode");
1243 String path = params.getString("path");
1244 LOGGER.debug("editFile path: {}"+ path);
1246 String domain = path.substring(1, path.lastIndexOf("/"));
1247 domain = domain.replace("/", ".");
1249 path = path.substring(1);
1250 path = path.replace("/", ".");
1251 String dbCheckName = path;
1252 if(dbCheckName.contains("Config_")){
1253 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
1254 }else if(dbCheckName.contains("Action_")){
1255 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
1256 }else if(dbCheckName.contains("Decision_")){
1257 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
1260 String[] split = dbCheckName.split(":");
1261 String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'";
1262 List<Object> queryData = controller.getDataByQuery(query);
1263 PolicyEntity entity = (PolicyEntity) queryData.get(0);
1264 InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
1267 Object policy = XACMLPolicyScanner.readPolicy(stream);
1268 PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
1269 policyAdapter.setData(policy);
1271 if("viewPolicy".equalsIgnoreCase(mode)){
1272 policyAdapter.setReadOnly(true);
1273 policyAdapter.setEditPolicy(false);
1275 policyAdapter.setReadOnly(false);
1276 policyAdapter.setEditPolicy(true);
1278 policyAdapter.setDomain(domain);
1279 policyAdapter.setDomainDir(domain);
1280 policyAdapter.setPolicyData(policy);
1281 String policyName = path.replace(".xml", "");
1282 policyName = policyName.substring(0, policyName.lastIndexOf("."));
1283 policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf(".")+1));
1285 PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance();
1286 setpolicyAdapter.configure(policyAdapter,entity);
1288 policyAdapter.setParentPath(null);
1289 ObjectMapper mapper = new ObjectMapper();
1290 String json = mapper.writeValueAsString(policyAdapter);
1291 JsonNode jsonNode = mapper.readTree(json);
1293 return new JSONObject().put(RESULT, jsonNode);
1294 } catch (Exception e) {
1295 LOGGER.error("editFile", e);
1296 return error(e.getMessage());
1301 private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
1302 PolicyController controller = new PolicyController();
1305 String userId = UserUtils.getUserSession(request).getOrgUserId();
1306 String path = params.getString("path");
1308 if(params.has("subScopename")){
1309 if(!params.getString("subScopename").equals("")){
1310 name = params.getString("path").replace("/", File.separator) + File.separator +params.getString("subScopename");
1313 name = params.getString("name");
1315 }catch(Exception e){
1316 name = params.getString("name");
1317 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e);
1319 String validateName;
1320 if(name.contains(File.separator)){
1321 validateName = name.substring(name.lastIndexOf(File.separator)+1);
1323 validateName = name;
1325 if(!name.isEmpty()){
1326 String validate = PolicyUtils.emptyPolicyValidator(validateName);
1327 if(!validate.contains("success")){
1328 return error(validate);
1331 LOGGER.debug("addFolder path: {} name: {}" + path +name);
1332 if(!name.equals("")){
1333 PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, "scopeName", name);
1335 UserInfo userInfo = new UserInfo();
1336 userInfo.setUserLoginId(userId);
1337 PolicyEditorScopes newScope = new PolicyEditorScopes();
1338 String scopeName = null;
1339 if(name.startsWith(File.separator)){
1340 scopeName = name.substring(1);
1344 newScope.setScopeName(scopeName);
1345 newScope.setUserCreatedBy(userInfo);
1346 newScope.setUserModifiedBy(userInfo);
1347 controller.saveData(newScope);
1349 return error("Scope Already Exists");
1353 } catch (Exception e) {
1354 LOGGER.error("addFolder", e);
1355 return error(e.getMessage());
1359 //Return Error Object
1360 private JSONObject error(String msg) throws ServletException {
1362 JSONObject result = new JSONObject();
1363 result.put("success", false);
1364 result.put("error", msg);
1365 return new JSONObject().put(RESULT, result);
1366 } catch (JSONException e) {
1367 throw new ServletException(e);
1371 //Return Success Object
1372 private JSONObject success() throws ServletException {
1374 JSONObject result = new JSONObject();
1375 result.put("success", true);
1376 result.put("error", (Object) null);
1377 return new JSONObject().put(RESULT, result);
1378 } catch (JSONException e) {
1379 throw new ServletException(e);