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.onap.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.FileOutputStream;
29 import java.io.FileWriter;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.io.OutputStream;
33 import java.io.PrintWriter;
34 import java.nio.charset.StandardCharsets;
35 import java.nio.file.Files;
36 import java.nio.file.Path;
37 import java.nio.file.Paths;
38 import java.util.ArrayList;
39 import java.util.Date;
40 import java.util.HashMap;
41 import java.util.HashSet;
42 import java.util.List;
46 import javax.json.Json;
47 import javax.json.JsonArray;
48 import javax.json.JsonReader;
49 import javax.script.SimpleBindings;
50 import javax.servlet.ServletConfig;
51 import javax.servlet.ServletException;
52 import javax.servlet.annotation.WebInitParam;
53 import javax.servlet.annotation.WebServlet;
54 import javax.servlet.http.HttpServlet;
55 import javax.servlet.http.HttpServletRequest;
56 import javax.servlet.http.HttpServletResponse;
58 import org.apache.commons.compress.utils.IOUtils;
59 import org.apache.commons.fileupload.FileItem;
60 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
61 import org.apache.commons.fileupload.servlet.ServletFileUpload;
62 import org.apache.http.HttpStatus;
63 import org.json.JSONArray;
64 import org.json.JSONException;
65 import org.json.JSONObject;
66 import org.onap.policy.common.logging.flexlogger.FlexLogger;
67 import org.onap.policy.common.logging.flexlogger.Logger;
68 import org.onap.policy.components.HumanPolicyComponent;
69 import org.onap.policy.controller.PolicyController;
70 import org.onap.policy.controller.PolicyExportAndImportController;
71 import org.onap.policy.rest.XACMLRest;
72 import org.onap.policy.rest.XACMLRestProperties;
73 import org.onap.policy.rest.adapter.PolicyRestAdapter;
74 import org.onap.policy.rest.jpa.ActionBodyEntity;
75 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
76 import org.onap.policy.rest.jpa.PolicyEditorScopes;
77 import org.onap.policy.rest.jpa.PolicyEntity;
78 import org.onap.policy.rest.jpa.PolicyVersion;
79 import org.onap.policy.rest.jpa.UserInfo;
80 import org.onap.policy.utils.PolicyUtils;
81 import org.onap.policy.utils.UserUtils.Pair;
82 import org.onap.policy.xacml.api.XACMLErrorConstants;
83 import org.onap.policy.xacml.util.XACMLPolicyScanner;
84 import org.onap.portalsdk.core.web.support.UserUtils;
86 import com.att.research.xacml.util.XACMLProperties;
87 import com.fasterxml.jackson.databind.JsonNode;
88 import com.fasterxml.jackson.databind.ObjectMapper;
91 @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.") })
92 public class PolicyManagerServlet extends HttpServlet {
93 private static final Logger LOGGER = FlexLogger.getLogger(PolicyManagerServlet.class);
94 private static final long serialVersionUID = -8453502699403909016L;
97 LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT, SEARCHLIST
100 private static PolicyController policyController;
101 public synchronized PolicyController getPolicyController() {
102 return policyController;
105 public static synchronized void setPolicyController(PolicyController policyController) {
106 PolicyManagerServlet.policyController = policyController;
109 private static String CONTENTTYPE = "application/json";
110 private static String SUPERADMIN = "super-admin";
111 private static String SUPEREDITOR = "super-editor";
112 private static String SUPERGUEST = "super-guest";
113 private static String ADMIN = "admin";
114 private static String EDITOR = "editor";
115 private static String GUEST = "guest";
116 private static String RESULT = "result";
118 private static Path closedLoopJsonLocation;
119 private static JsonArray policyNames;
120 private static String testUserId = null;
122 public static JsonArray getPolicyNames() {
126 public static void setPolicyNames(JsonArray policyNames) {
127 PolicyManagerServlet.policyNames = policyNames;
130 private static List<String> serviceTypeNamesList = new ArrayList<>();
132 public static List<String> getServiceTypeNamesList() {
133 return serviceTypeNamesList;
137 public void init(ServletConfig servletConfig) throws ServletException {
138 super.init(servletConfig);
140 // Common initialization
142 XACMLRest.xacmlInit(servletConfig);
144 //Initialize ClosedLoop JSON
146 PolicyManagerServlet.initializeJSONLoad();
149 protected static void initializeJSONLoad() {
150 closedLoopJsonLocation = Paths.get(XACMLProperties
151 .getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP));
152 String location = closedLoopJsonLocation.toString();
153 if (! location.endsWith("json")) {
154 LOGGER.warn("JSONConfig file does not end with extension .json");
157 try (FileInputStream inputStream = new FileInputStream(location);
158 JsonReader jsonReader = Json.createReader(inputStream)) {
159 policyNames = jsonReader.readArray();
160 serviceTypeNamesList = new ArrayList<>();
161 for (int i = 0; i < policyNames.size(); i++) {
162 javax.json.JsonObject policyName = policyNames.getJsonObject(i);
163 String name = policyName.getJsonString("serviceTypePolicyName").getString();
164 serviceTypeNamesList.add(name);
166 } catch (IOException e) {
167 LOGGER.error("Exception Occured while initializing the JSONConfig file"+e);
172 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
173 LOGGER.debug("doPost");
175 // if request contains multipart-form-data
176 if (ServletFileUpload.isMultipartContent(request)) {
177 uploadFile(request, response);
179 // all other post request has json params in body
181 fileOperation(request, response);
183 } catch (Exception e) {
185 setError(e, response);
186 }catch(Exception e1){
187 LOGGER.error("Exception Occured"+e1);
192 //Set Error Message for Exception
193 private void setError(Exception t, HttpServletResponse response) throws IOException {
195 JSONObject responseJsonObject = error(t.getMessage());
196 response.setContentType(CONTENTTYPE);
197 PrintWriter out = response.getWriter();
198 out.print(responseJsonObject);
200 } catch (Exception x) {
201 LOGGER.error("Exception Occured"+x);
202 response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage());
206 //Policy Import Functionality
207 private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException {
210 Map<String, InputStream> files = new HashMap<>();
212 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
213 for (FileItem item : items) {
214 if (!item.isFormField()) {
215 // Process form file field (input type="file").
216 files.put(item.getName(), item.getInputStream());
217 if(item.getName().endsWith(".xls") && item.getSize() <= PolicyController.getFileSizeLimit()){
218 File file = new File(item.getName());
219 try (OutputStream outputStream = new FileOutputStream(file);)
221 IOUtils.copy(item.getInputStream(), outputStream);
222 newFile = file.toString();
223 PolicyExportAndImportController importController = new PolicyExportAndImportController();
224 importController.importRepositoryFile(newFile, request);
226 LOGGER.error("Upload error : " + e);
229 else if (!item.getName().endsWith(".xls")) {
230 LOGGER.error("Non .xls filetype uploaded: " + item.getName());
232 else { //uploaded file size is greater than allowed
233 LOGGER.error("Upload file size limit exceeded! File size (Bytes) is: " + item.getSize());
238 JSONObject responseJsonObject;
239 responseJsonObject = this.success();
240 response.setContentType(CONTENTTYPE);
241 PrintWriter out = response.getWriter();
242 out.print(responseJsonObject);
244 } catch (Exception e) {
245 LOGGER.debug("Cannot write file");
246 throw new ServletException("Cannot write file", e);
250 //File Operation Functionality
251 private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
252 JSONObject responseJsonObject = null;
254 StringBuilder sb = new StringBuilder();
255 BufferedReader br = request.getReader();
257 while ((str = br.readLine()) != null) {
261 JSONObject jObj = new JSONObject(sb.toString());
262 JSONObject params = jObj.getJSONObject("params");
263 Mode mode = Mode.valueOf(params.getString("mode"));
265 String userId = UserUtils.getUserSession(request).getOrgUserId();
266 LOGGER.info("****************************************Logging UserID while doing actions on Editor tab*******************************************");
267 LOGGER.info("UserId: " + userId + "Action Mode: "+ mode.toString() + "Action Params: "+params.toString());
268 LOGGER.info("***********************************************************************************************************************************");
273 responseJsonObject = addFolder(params, request);
276 responseJsonObject = copy(params, request);
279 responseJsonObject = delete(params, request);
283 responseJsonObject = editFile(params);
286 responseJsonObject = list(params, request);
289 responseJsonObject = rename(params, request);
291 case DESCRIBEPOLICYFILE:
292 responseJsonObject = describePolicy(params);
295 responseJsonObject = switchVersion(params, request);
298 responseJsonObject = searchPolicyList(params, request);
301 throw new ServletException("not implemented");
303 if (responseJsonObject == null) {
304 responseJsonObject = error("generic error : responseJsonObject is null");
306 } catch (Exception e) {
307 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While doing File Operation" + e);
308 responseJsonObject = error(e.getMessage());
310 response.setContentType(CONTENTTYPE);
311 PrintWriter out = response.getWriter();
312 out.print(responseJsonObject);
316 private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) {
319 List<Object> policyData = new ArrayList<>();
320 JSONArray policyList = null;
321 if(params.has("policyList")){
322 policyList = (JSONArray) params.get("policyList");
324 PolicyController controller = getPolicyControllerInstance();
325 List<JSONObject> resultList = new ArrayList<>();
327 //Get the Login Id of the User from Request
328 String userId = UserUtils.getUserSession(request).getOrgUserId();
329 List<Object> userRoles = controller.getRoles(userId);
330 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
333 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
334 if(scopes.isEmpty()){
335 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
337 Set<String> tempScopes = scopes;
338 for(String scope : tempScopes){
339 List<Object> scopesList = queryPolicyEditorScopes(scope);
340 if(!scopesList.isEmpty()){
341 for(int i = 0; i < scopesList.size(); i++){
342 PolicyEditorScopes tempScope = (PolicyEditorScopes) scopesList.get(i);
343 scopes.add(tempScope.getScopeName());
348 if(policyList!= null){
349 for(int i = 0; i < policyList.length(); i++){
350 String policyName = policyList.get(i).toString().replace(".xml", "");
351 String version = policyName.substring(policyName.lastIndexOf('.')+1);
352 policyName = policyName.substring(0, policyName.lastIndexOf('.')).replace(".", File.separator);
353 if(policyName.contains("\\")){
354 policyName = policyName.replace("\\", "\\\\");
356 String policyVersionQuery = "From PolicyVersion where policy_name = :policyName and active_version = :version and id >0";
357 SimpleBindings pvParams = new SimpleBindings();
358 pvParams.put("policyName", policyName);
359 pvParams.put("version", version);
360 List<Object> activeData = controller.getDataByQuery(policyVersionQuery, pvParams);
361 if(!activeData.isEmpty()){
362 PolicyVersion policy = (PolicyVersion) activeData.get(0);
363 JSONObject el = new JSONObject();
364 el.put("name", policy.getPolicyName().replace(File.separator, "/"));
365 el.put("date", policy.getModifiedDate());
366 el.put("version", policy.getActiveVersion());
368 el.put("type", "file");
369 el.put("createdBy", getUserName(policy.getCreatedBy()));
370 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
375 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ){
376 policyData = controller.getData(PolicyVersion.class);
378 List<Object> filterdatas = controller.getData(PolicyVersion.class);
379 for(Object filter : filterdatas){
380 PolicyVersion filterdata = (PolicyVersion) filter;
382 String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator));
383 if(scopes.contains(scopeName)){
384 policyData.add(filterdata);
387 LOGGER.error("Exception occured while filtering policyversion data"+e);
392 if(!policyData.isEmpty()){
393 for(int i =0; i < policyData.size(); i++){
394 PolicyVersion policy = (PolicyVersion) policyData.get(i);
395 JSONObject el = new JSONObject();
396 el.put("name", policy.getPolicyName().replace(File.separator, "/"));
397 el.put("date", policy.getModifiedDate());
398 el.put("version", policy.getActiveVersion());
400 el.put("type", "file");
401 el.put("createdBy", getUserName(policy.getCreatedBy()));
402 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
408 LOGGER.error("Exception occured while reading policy Data from Policy Version table for Policy Search Data"+e);
411 return new JSONObject().put(RESULT, resultList);
414 //Switch Version Functionality
415 private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{
416 String path = params.getString("path");
417 String userId = null;
419 userId = UserUtils.getUserSession(request).getOrgUserId();
420 } catch (Exception e) {
421 LOGGER.error("Exception Occured while reading userid from cookie" +e);
424 String removeExtension = path.replace(".xml", "");
425 if(path.startsWith("/")){
426 policyName = removeExtension.substring(1, removeExtension.lastIndexOf('.'));
428 policyName = removeExtension.substring(0, removeExtension.lastIndexOf('.'));
432 PolicyController controller = getPolicyControllerInstance();
433 if(params.toString().contains("activeVersion")){
434 String activeVersion = params.getString("activeVersion");
435 String highestVersion = params.get("highestVersion").toString();
436 if(Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)){
437 return error("The Version shouldn't be greater than Highest Value");
439 activePolicy = policyName + "." + activeVersion + ".xml";
440 String dbCheckName = activePolicy.replace("/", ".");
441 if(dbCheckName.contains("Config_")){
442 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
443 }else if(dbCheckName.contains("Action_")){
444 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
445 }else if(dbCheckName.contains("Decision_")){
446 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
448 String[] splitDBCheckName = dbCheckName.split(":");
449 String peQuery = "FROM PolicyEntity where policyName = :splitDBCheckName_1 and scope = :splitDBCheckName_0";
450 SimpleBindings policyParams = new SimpleBindings();
451 policyParams.put("splitDBCheckName_1", splitDBCheckName[1]);
452 policyParams.put("splitDBCheckName_0", splitDBCheckName[0]);
453 List<Object> policyEntity = controller.getDataByQuery(peQuery, policyParams);
454 PolicyEntity pentity = (PolicyEntity) policyEntity.get(0);
455 if(pentity.isDeleted()){
456 return error("The Policy is Not Existing in Workspace");
458 if(policyName.contains("/")){
459 policyName = policyName.replace("/", File.separator);
461 policyName = policyName.substring(policyName.indexOf(File.separator)+1);
462 if(policyName.contains("\\")){
463 policyName = policyName.replace(File.separator, "\\");
465 policyName = splitDBCheckName[0].replace(".", File.separator)+File.separator+policyName;
466 String watchPolicyName = policyName;
467 if(policyName.contains("/")){
468 policyName = policyName.replace("/", File.separator);
470 if(policyName.contains("\\")){
471 policyName = policyName.replace("\\", "\\\\");
473 String query = "update PolicyVersion set active_version='"+activeVersion+"' where policy_name ='"+policyName+"' and id >0";
475 controller.executeQuery(query);
476 //Policy Notification
477 PolicyVersion entity = new PolicyVersion();
478 entity.setPolicyName(watchPolicyName);
479 entity.setActiveVersion(Integer.parseInt(activeVersion));
480 entity.setModifiedBy(userId);
481 controller.watchPolicyFunction(entity, activePolicy, "SwitchVersion");
486 return controller.switchVersionPolicyContent(policyName);
490 private JSONObject describePolicy(JSONObject params) throws ServletException{
491 JSONObject object = null;
492 String path = params.getString("path");
493 String policyName = null;
494 if(path.startsWith("/")){
495 path = path.substring(1);
496 policyName = path.substring(path.lastIndexOf('/') +1);
497 path = path.replace("/", ".");
499 path = path.replace("/", ".");
502 if(path.contains("Config_")){
503 path = path.replace(".Config_", ":Config_");
504 }else if(path.contains("Action_")){
505 path = path.replace(".Action_", ":Action_");
506 }else if(path.contains("Decision_")){
507 path = path.replace(".Decision_", ":Decision_");
509 PolicyController controller = getPolicyControllerInstance();
510 String[] split = path.split(":");
511 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
512 SimpleBindings peParams = new SimpleBindings();
513 peParams.put("split_1", split[1]);
514 peParams.put("split_0", split[0]);
515 List<Object> queryData = null;
516 if(PolicyController.isjUnit()){
517 queryData = controller.getDataByQuery(query, null);
519 queryData = controller.getDataByQuery(query, peParams);
521 if(!queryData.isEmpty()){
522 PolicyEntity entity = (PolicyEntity) queryData.get(0);
524 BufferedWriter bw = null;
526 temp = File.createTempFile(policyName, ".tmp");
527 bw = new BufferedWriter(new FileWriter(temp));
528 bw.write(entity.getPolicyData());
530 object = HumanPolicyComponent.DescribePolicy(temp);
531 } catch (IOException e) {
532 LOGGER.error("Exception Occured while Describing the Policy"+e);
540 } catch (IOException e) {
541 LOGGER.error("Exception Occured while Closing the File Writer"+e);
546 return error("Error Occured while Describing the Policy");
552 //Get the List of Policies and Scopes for Showing in Editor tab
553 private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException {
554 Set<String> scopes = null;
555 List<String> roles = null;
557 PolicyController controller = getPolicyControllerInstance();
558 //Get the Login Id of the User from Request
559 String testUserID = getTestUserId();
560 String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId();
561 List<Object> userRoles = controller.getRoles(userId);
562 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
566 List<JSONObject> resultList = new ArrayList<>();
567 boolean onlyFolders = params.getBoolean("onlyFolders");
568 String path = params.getString("path");
569 if(path.contains("..xml")){
570 path = path.replaceAll("..xml", "").trim();
573 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
574 if(scopes.isEmpty()){
575 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
577 if(!"/".equals(path)){
578 String tempScope = path.substring(1, path.length());
579 tempScope = tempScope.replace("/", File.separator);
580 scopes.add(tempScope);
585 if("/".equals(path)){
586 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
587 List<Object> scopesList = queryPolicyEditorScopes(null);
588 for(Object list : scopesList){
589 PolicyEditorScopes scope = (PolicyEditorScopes) list;
590 if(!(scope.getScopeName().contains(File.separator))){
591 JSONObject el = new JSONObject();
592 el.put("name", scope.getScopeName());
593 el.put("date", scope.getModifiedDate());
595 el.put("type", "dir");
596 el.put("createdBy", scope.getUserCreatedBy().getUserName());
597 el.put("modifiedBy", scope.getUserModifiedBy().getUserName());
601 }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){
602 for(Object scope : scopes){
603 JSONObject el = new JSONObject();
604 List<Object> scopesList = queryPolicyEditorScopes(scope.toString());
605 if(!scopesList.isEmpty()){
606 PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
607 el.put("name", scopeById.getScopeName());
608 el.put("date", scopeById.getModifiedDate());
610 el.put("type", "dir");
611 el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
612 el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
619 String scopeName = path.substring(path.indexOf('/') +1);
620 activePolicyList(scopeName, resultList, roles, scopes, onlyFolders);
621 } catch (Exception ex) {
622 LOGGER.error("Error Occured While reading Policy Files List"+ex );
626 return new JSONObject().put(RESULT, resultList);
627 } catch (Exception e) {
628 LOGGER.error("list", e);
629 return error(e.getMessage());
633 private List<Object> queryPolicyEditorScopes(String scopeName){
634 String scopeNamequery;
635 SimpleBindings params = new SimpleBindings();
636 if(scopeName == null){
637 scopeNamequery = "from PolicyEditorScopes";
639 scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
640 params.put("scopeName", scopeName + "%");
642 PolicyController controller = getPolicyControllerInstance();
643 List<Object> scopesList;
644 if(PolicyController.isjUnit()){
645 scopesList = controller.getDataByQuery(scopeNamequery, null);
647 scopesList = controller.getDataByQuery(scopeNamequery, params);
652 //Get Active Policy List based on Scope Selection form Policy Version table
653 private void activePolicyList(String scopeName, List<JSONObject> resultList, List<String> roles, Set<String> scopes, boolean onlyFolders){
654 PolicyController controller = getPolicyControllerInstance();
655 if(scopeName.contains("/")){
656 scopeName = scopeName.replace("/", File.separator);
658 if(scopeName.contains("\\")){
659 scopeName = scopeName.replace("\\", "\\\\\\\\");
661 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
662 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
664 SimpleBindings params = new SimpleBindings();
665 params.put("scopeName", scopeName + "%");
667 List<Object> activePolicies;
668 List<Object> scopesList;
669 if(PolicyController.isjUnit()){
670 activePolicies = controller.getDataByQuery(query, null);
671 scopesList = controller.getDataByQuery(scopeNamequery, null);
673 activePolicies = controller.getDataByQuery(query, params);
674 scopesList = controller.getDataByQuery(scopeNamequery, params);
676 for(Object list : scopesList){
677 PolicyEditorScopes scopeById = (PolicyEditorScopes) list;
678 String scope = scopeById.getScopeName();
679 if(scope.contains(File.separator)){
680 String checkScope = scope.substring(0, scope.lastIndexOf(File.separator));
681 if(scopeName.contains("\\\\")){
682 scopeName = scopeName.replace("\\\\", File.separator);
684 if(scope.contains(File.separator)){
685 scope = scope.substring(checkScope.length()+1);
686 if(scope.contains(File.separator)){
687 scope = scope.substring(0, scope.indexOf(File.separator));
690 if(scopeName.equalsIgnoreCase(checkScope)){
691 JSONObject el = new JSONObject();
692 el.put("name", scope);
693 el.put("date", scopeById.getModifiedDate());
695 el.put("type", "dir");
696 el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
697 el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
702 String scopeNameCheck;
703 for (Object list : activePolicies) {
704 PolicyVersion policy = (PolicyVersion) list;
705 String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator));
706 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
707 if((scopeName.contains("\\\\"))){
708 scopeNameCheck = scopeName.replace("\\\\", File.separator);
710 scopeNameCheck = scopeName;
712 if(scopeNameValue.equals(scopeNameCheck)){
713 JSONObject el = new JSONObject();
714 el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
715 el.put("date", policy.getModifiedDate());
716 el.put("version", policy.getActiveVersion());
718 el.put("type", "file");
719 el.put("createdBy", getUserName(policy.getCreatedBy()));
720 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
723 }else if(!scopes.isEmpty() && scopes.contains(scopeNameValue)){
724 JSONObject el = new JSONObject();
725 el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
726 el.put("date", policy.getModifiedDate());
727 el.put("version", policy.getActiveVersion());
729 el.put("type", "file");
730 el.put("createdBy", getUserName(policy.getCreatedBy()));
731 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
737 private String getUserName(String loginId){
738 PolicyController controller = getPolicyControllerInstance();
739 UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
740 if(userInfo == null){
743 return userInfo.getUserName();
747 private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
749 boolean isActive = false;
750 List<String> policyActiveInPDP = new ArrayList<>();
751 Set<String> scopeOfPolicyActiveInPDP = new HashSet<>();
752 String userId = UserUtils.getUserSession(request).getOrgUserId();
753 String oldPath = params.getString("path");
754 String newPath = params.getString("newPath");
755 oldPath = oldPath.substring(oldPath.indexOf('/')+1);
756 newPath = newPath.substring(newPath.indexOf('/')+1);
757 if(oldPath.endsWith(".xml")){
758 JSONObject result = policyRename(oldPath, newPath, userId);
759 if(!(Boolean)(result.getJSONObject("result").get("success"))){
763 String scopeName = oldPath;
764 String newScopeName = newPath;
765 if(scopeName.contains("/")){
766 scopeName = scopeName.replace("/", File.separator);
767 newScopeName = newScopeName.replace("/", File.separator);
769 if(scopeName.contains("\\")){
770 scopeName = scopeName.replace("\\", "\\\\\\\\");
771 newScopeName = newScopeName.replace("\\", "\\\\\\\\");
773 PolicyController controller = getPolicyControllerInstance();
774 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
775 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
776 SimpleBindings pvParams = new SimpleBindings();
777 pvParams.put("scopeName", scopeName + "%");
778 List<Object> activePolicies = controller.getDataByQuery(query, pvParams);
779 List<Object> scopesList = controller.getDataByQuery(scopeNamequery, pvParams);
780 for(Object object : activePolicies){
781 PolicyVersion activeVersion = (PolicyVersion) object;
782 String policyOldPath = activeVersion.getPolicyName().replace(File.separator, "/") + "." + activeVersion.getActiveVersion() + ".xml";
783 String policyNewPath = policyOldPath.replace(oldPath, newPath);
784 JSONObject result = policyRename(policyOldPath, policyNewPath, userId);
785 if(!(Boolean)(result.getJSONObject("result").get("success"))){
787 policyActiveInPDP.add(policyOldPath);
788 String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf('/'));
789 scopeOfPolicyActiveInPDP.add(scope.replace("/", File.separator));
792 boolean rename = false;
793 if(activePolicies.size() != policyActiveInPDP.size()){
797 UserInfo userInfo = new UserInfo();
798 userInfo.setUserLoginId(userId);
799 if(policyActiveInPDP.isEmpty()){
800 renameScope(scopesList, scopeName, newScopeName, controller);
802 renameScope(scopesList, scopeName, newScopeName, controller);
803 for(String scope : scopeOfPolicyActiveInPDP){
804 PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes();
805 editorScopeEntity.setScopeName(scope.replace("\\", "\\\\\\\\"));
806 editorScopeEntity.setUserCreatedBy(userInfo);
807 editorScopeEntity.setUserModifiedBy(userInfo);
808 controller.saveData(editorScopeEntity);
812 return error("The Following policies rename failed. Since they are active in PDP Groups" +policyActiveInPDP);
816 } catch (Exception e) {
817 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
818 return error(e.getMessage());
822 private void renameScope(List<Object> scopesList, String scopeName, String newScopeName, PolicyController controller){
823 for(Object object : scopesList){
824 PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object;
825 if(scopeName.contains("\\\\\\\\")){
826 scopeName = scopeName.replace("\\\\\\\\", File.separator);
827 newScopeName = newScopeName.replace("\\\\\\\\", File.separator);
829 String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName);
830 editorScopeEntity.setScopeName(scope);
831 controller.updateData(editorScopeEntity);
835 private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
838 PolicyController controller = getPolicyControllerInstance();
840 String policyVersionName = newPath.replace(".xml", "");
841 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')).replace("/", File.separator);
843 String oldpolicyVersionName = oldPath.replace(".xml", "");
844 String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf('.')).replace("/", File.separator);
846 String newpolicyName = newPath.replace("/", ".");
847 String newPolicyCheck = newpolicyName;
848 if(newPolicyCheck.contains("Config_")){
849 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
850 }else if(newPolicyCheck.contains("Action_")){
851 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
852 }else if(newPolicyCheck.contains("Decision_")){
853 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
855 String[] newPolicySplit = newPolicyCheck.split(":");
857 String orignalPolicyName = oldPath.replace("/", ".");
858 String oldPolicyCheck = orignalPolicyName;
859 if(oldPolicyCheck.contains("Config_")){
860 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
861 }else if(oldPolicyCheck.contains("Action_")){
862 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
863 }else if(oldPolicyCheck.contains("Decision_")){
864 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
866 String[] oldPolicySplit = oldPolicyCheck.split(":");
868 //Check PolicyEntity table with newPolicy Name
869 String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
870 SimpleBindings policyParams = new SimpleBindings();
871 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
872 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
873 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
874 if(!queryData.isEmpty()){
875 return error("Policy rename failed. Since, the policy with same name already exists.");
878 //Query the Policy Entity with oldPolicy Name
879 String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf('.'));
880 String oldpolicyEntityquery = "FROM PolicyEntity where policyName like :policyEntityCheck and scope = :oldPolicySplit_0";
881 SimpleBindings params = new SimpleBindings();
882 params.put("policyEntityCheck", policyEntityCheck + "%");
883 params.put("oldPolicySplit_0", oldPolicySplit[0]);
884 List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery, params);
885 if(!oldEntityData.isEmpty()){
886 StringBuilder groupQuery = new StringBuilder();
887 groupQuery.append("FROM PolicyGroupEntity where (");
888 SimpleBindings geParams = new SimpleBindings();
889 for(int i=0; i<oldEntityData.size(); i++){
890 entity = (PolicyEntity) oldEntityData.get(i);
892 groupQuery.append("policyid = :policyId");
893 geParams.put("policyId", entity.getPolicyId());
895 groupQuery.append(" or policyid = :policyId" + i);
896 geParams.put("policyId" + i, entity.getPolicyId());
899 groupQuery.append(")");
900 List<Object> groupEntityData = controller.getDataByQuery(groupQuery.toString(), geParams);
901 if(! groupEntityData.isEmpty()){
902 return error("Policy rename failed. Since the policy or its version is active in PDP Groups.");
904 for(int i=0; i<oldEntityData.size(); i++){
905 entity = (PolicyEntity) oldEntityData.get(i);
906 checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0] , newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
909 return error("Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin.");
913 } catch (Exception e) {
914 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
915 return error(e.getMessage());
919 private JSONObject checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, String oldScope, String removeoldPolicyExtension,
920 String policyName, String newpolicyName, String oldpolicyName, String userId) throws ServletException{
922 ConfigurationDataEntity configEntity = entity.getConfigurationData();
923 ActionBodyEntity actionEntity = entity.getActionBodyEntity();
924 PolicyController controller = getPolicyControllerInstance();
926 String oldPolicyNameWithoutExtension = removeoldPolicyExtension;
927 String newPolicyNameWithoutExtension = removenewPolicyExtension;
928 if(removeoldPolicyExtension.endsWith(".xml")){
929 oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf('.'));
930 newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf('.'));
932 entity.setPolicyName(entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
933 entity.setPolicyData(entity.getPolicyData().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
934 entity.setScope(newScope);
935 entity.setModifiedBy(userId);
936 if(newpolicyName.contains("Config_")){
937 String oldConfigurationName = configEntity.getConfigurationName();
938 configEntity.setConfigurationName(configEntity.getConfigurationName().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
939 controller.updateData(configEntity);
940 String newConfigurationName = configEntity.getConfigurationName();
941 File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName);
943 File renamefile = new File(PolicyController.getConfigHome() + File.separator + newConfigurationName);
944 file.renameTo(renamefile);
946 }else if(newpolicyName.contains("Action_")){
947 String oldConfigurationName = actionEntity.getActionBodyName();
948 actionEntity.setActionBody(actionEntity.getActionBody().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
949 controller.updateData(actionEntity);
950 String newConfigurationName = actionEntity.getActionBodyName();
951 File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName);
953 File renamefile = new File(PolicyController.getActionHome() + File.separator + newConfigurationName);
954 file.renameTo(renamefile);
957 controller.updateData(entity);
959 PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldpolicyName);
960 versionEntity.setPolicyName(policyName);
961 versionEntity.setModifiedBy(userId);
962 controller.updateData(versionEntity);
963 String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator)+1);
964 String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
965 if(movePolicyCheck.equals(moveOldPolicyCheck)){
966 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move");
968 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename");
971 } catch (Exception e) {
972 LOGGER.error("Exception Occured"+e);
973 return error(e.getMessage());
977 private JSONObject cloneRecord(String newpolicyName, String oldScope, String removeoldPolicyExtension, String newScope, String removenewPolicyExtension, PolicyEntity entity, String userId) throws ServletException{
978 FileWriter fw = null;
979 String queryEntityName;
980 PolicyController controller = getPolicyControllerInstance();
981 PolicyEntity cloneEntity = new PolicyEntity();
982 cloneEntity.setPolicyName(newpolicyName);
983 removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
984 removenewPolicyExtension = removenewPolicyExtension.replace(".xml", "");
985 cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope+"."+removeoldPolicyExtension, newScope+"."+removenewPolicyExtension));
986 cloneEntity.setScope(entity.getScope());
987 String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
988 String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
989 if(newpolicyName.contains("Config_")){
990 ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
991 configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
992 queryEntityName = configurationDataEntity.getConfigurationName();
993 configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody());
994 configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType());
995 configurationDataEntity.setDeleted(false);
996 configurationDataEntity.setCreatedBy(userId);
997 configurationDataEntity.setModifiedBy(userId);
998 controller.saveData(configurationDataEntity);
999 ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
1000 cloneEntity.setConfigurationData(configEntiy);
1001 String newConfigurationName = configEntiy.getConfigurationName();
1003 fw = new FileWriter(PolicyController.getConfigHome() + File.separator + newConfigurationName);
1004 BufferedWriter bw = new BufferedWriter(fw);
1005 bw.write(configEntiy.getConfigBody());
1007 } catch (IOException e) {
1008 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1010 }else if(newpolicyName.contains("Action_")){
1011 ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
1012 actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1013 queryEntityName = actionBodyEntity.getActionBodyName();
1014 actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody());
1015 actionBodyEntity.setDeleted(false);
1016 actionBodyEntity.setCreatedBy(userId);
1017 actionBodyEntity.setModifiedBy(userId);
1018 controller.saveData(actionBodyEntity);
1019 ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class, "actionBodyName", queryEntityName);
1020 cloneEntity.setActionBodyEntity(actionEntiy);
1021 String newConfigurationName = actionEntiy.getActionBodyName();
1023 fw = new FileWriter(PolicyController.getActionHome() + File.separator + newConfigurationName);
1024 BufferedWriter bw = new BufferedWriter(fw);
1025 bw.write(actionEntiy.getActionBody());
1027 } catch (IOException e) {
1028 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1034 } catch (IOException e) {
1035 LOGGER.error("Exception Occured While closing the File input stream"+e);
1038 cloneEntity.setDeleted(entity.isDeleted());
1039 cloneEntity.setCreatedBy(userId);
1040 cloneEntity.setModifiedBy(userId);
1041 controller.saveData(cloneEntity);
1047 private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
1049 String userId = UserUtils.getUserSession(request).getOrgUserId();
1050 String oldPath = params.getString("path");
1051 String newPath = params.getString("newPath");
1052 oldPath = oldPath.substring(oldPath.indexOf('/')+1);
1053 newPath = newPath.substring(newPath.indexOf('/')+1);
1055 String policyVersionName = newPath.replace(".xml", "");
1056 String version = policyVersionName.substring(policyVersionName.indexOf('.')+1);
1057 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')).replace("/", File.separator);
1059 String newpolicyName = newPath.replace("/", ".");
1061 String orignalPolicyName = oldPath.replace("/", ".");
1063 String newPolicyCheck = newpolicyName;
1064 if(newPolicyCheck.contains("Config_")){
1065 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
1066 }else if(newPolicyCheck.contains("Action_")){
1067 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
1068 }else if(newPolicyCheck.contains("Decision_")){
1069 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
1071 String[] newPolicySplit = newPolicyCheck.split(":");
1073 String oldPolicyCheck = orignalPolicyName;
1074 if(oldPolicyCheck.contains("Config_")){
1075 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
1076 }else if(oldPolicyCheck.contains("Action_")){
1077 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
1078 }else if(oldPolicyCheck.contains("Decision_")){
1079 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
1081 String[] oldPolicySplit = oldPolicyCheck.split(":");
1083 PolicyController controller = getPolicyControllerInstance();
1085 PolicyEntity entity = null;
1086 boolean success = false;
1088 //Check PolicyEntity table with newPolicy Name
1089 String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
1090 SimpleBindings policyParams = new SimpleBindings();
1091 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
1092 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
1093 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
1094 if(!queryData.isEmpty()){
1095 return error("Policy already exists with same name");
1098 //Query the Policy Entity with oldPolicy Name
1099 policyEntityquery = "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0";
1100 SimpleBindings peParams = new SimpleBindings();
1101 peParams.put("oldPolicySplit_1", oldPolicySplit[1]);
1102 peParams.put("oldPolicySplit_0", oldPolicySplit[0]);
1103 queryData = controller.getDataByQuery(policyEntityquery, peParams);
1104 if(!queryData.isEmpty()){
1105 entity = (PolicyEntity) queryData.get(0);
1108 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId);
1113 PolicyVersion entityItem = new PolicyVersion();
1114 entityItem.setActiveVersion(Integer.parseInt(version));
1115 entityItem.setHigherVersion(Integer.parseInt(version));
1116 entityItem.setPolicyName(policyName);
1117 entityItem.setCreatedBy(userId);
1118 entityItem.setModifiedBy(userId);
1119 entityItem.setModifiedDate(new Date());
1120 controller.saveData(entityItem);
1123 LOGGER.debug("copy from: {} to: {}" + oldPath +newPath);
1126 } catch (Exception e) {
1127 LOGGER.error("copy", e);
1128 return error(e.getMessage());
1132 //Delete Policy or Scope Functionality
1133 private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
1134 PolicyController controller = getPolicyControllerInstance();
1135 PolicyRestController restController = new PolicyRestController();
1136 PolicyEntity policyEntity = null;
1137 String policyNamewithoutExtension;
1139 String userId = UserUtils.getUserSession(request).getOrgUserId();
1140 String deleteVersion = "";
1141 String path = params.getString("path");
1142 LOGGER.debug("delete {}" +path);
1143 if(params.has("deleteVersion")){
1144 deleteVersion = params.getString("deleteVersion");
1146 path = path.substring(path.indexOf('/')+1);
1147 String policyNamewithExtension = path.replace("/", File.separator);
1148 String policyVersionName = policyNamewithExtension.replace(".xml", "");
1150 SimpleBindings policyParams = new SimpleBindings();
1151 if(path.endsWith(".xml")){
1152 policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf('.'));
1153 policyNamewithoutExtension = policyNamewithoutExtension.replace(File.separator, ".");
1154 String splitPolicyName = null;
1155 if(policyNamewithoutExtension.contains("Config_")){
1156 splitPolicyName = policyNamewithoutExtension.replace(".Config_", ":Config_");
1157 }else if(policyNamewithoutExtension.contains("Action_")){
1158 splitPolicyName = policyNamewithoutExtension.replace(".Action_", ":Action_");
1159 }else if(policyNamewithoutExtension.contains("Decision_")){
1160 splitPolicyName = policyNamewithoutExtension.replace(".Decision_", ":Decision_");
1162 String[] split = splitPolicyName.split(":");
1164 query = "FROM PolicyEntity where policyName like :split_1 and scope = :split_0";
1165 policyParams.put("split_1", split[1] + "%");
1166 policyParams.put("split_0", split[0]);
1168 policyNamewithoutExtension = path.replace(File.separator, ".");
1169 query = "FROM PolicyEntity where scope like :policyNamewithoutExtension";
1170 policyParams.put("policyNamewithoutExtension", policyNamewithoutExtension + "%");
1173 List<Object> policyEntityobjects = controller.getDataByQuery(query, policyParams);
1174 String activePolicyName = null;
1175 boolean pdpCheck = false;
1176 if(path.endsWith(".xml")){
1177 policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator);
1178 int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf('.')+1));
1179 if("ALL".equals(deleteVersion)){
1180 if(!policyEntityobjects.isEmpty()){
1181 for(Object object : policyEntityobjects){
1182 policyEntity = (PolicyEntity) object;
1183 String groupEntityquery = "from PolicyGroupEntity where policyid ='"+policyEntity.getPolicyId()+"'";
1184 SimpleBindings pgeParams = new SimpleBindings();
1185 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, pgeParams);
1186 if(!groupobject.isEmpty()){
1188 activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName();
1190 //Delete the entity from Elastic Search Database
1191 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1192 restController.deleteElasticData(searchFileName);
1193 //Delete the entity from Policy Entity table
1194 controller.deleteData(policyEntity);
1195 if(policyNamewithoutExtension.contains("Config_")){
1196 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1197 controller.deleteData(policyEntity.getConfigurationData());
1198 }else if(policyNamewithoutExtension.contains("Action_")){
1199 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1200 controller.deleteData(policyEntity.getActionBodyEntity());
1205 //Policy Notification
1206 PolicyVersion versionEntity = new PolicyVersion();
1207 versionEntity.setPolicyName(policyNamewithoutExtension);
1208 versionEntity.setModifiedBy(userId);
1209 controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll");
1211 //Delete from policyVersion table
1212 String getActivePDPPolicyVersion = activePolicyName.replace(".xml", "");
1213 getActivePDPPolicyVersion = getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf('.')+1);
1214 String policyVersionQuery = "update PolicyVersion set active_version='"+getActivePDPPolicyVersion+"' , highest_version='"+getActivePDPPolicyVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1215 if(policyVersionQuery != null){
1216 controller.executeQuery(policyVersionQuery);
1218 return error("Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "+activePolicyName);
1220 //No Active Policy in PDP. So, deleting all entries from policyVersion table
1221 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1222 if(policyVersionQuery != null){
1223 controller.executeQuery(policyVersionQuery);
1226 }else if("CURRENT".equals(deleteVersion)){
1227 String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1);
1228 String currentVersionScope = policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator)).replace(File.separator, ".");
1229 query = "FROM PolicyEntity where policyName = :currentVersionPolicyName and scope = :currentVersionScope";
1231 SimpleBindings peParams = new SimpleBindings();
1232 peParams.put("currentVersionPolicyName", currentVersionPolicyName);
1233 peParams.put("currentVersionScope", currentVersionScope);
1235 List<Object> policyEntitys = controller.getDataByQuery(query, peParams);
1236 if(!policyEntitys.isEmpty()){
1237 policyEntity = (PolicyEntity) policyEntitys.get(0);
1239 if(policyEntity != null){
1240 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId and policyid > 0";
1241 SimpleBindings geParams = new SimpleBindings();
1242 geParams.put("policyEntityId", policyEntity.getPolicyId());
1243 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1244 if(groupobject.isEmpty()){
1245 //Delete the entity from Elastic Search Database
1246 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1247 restController.deleteElasticData(searchFileName);
1248 //Delete the entity from Policy Entity table
1249 controller.deleteData(policyEntity);
1250 if(policyNamewithoutExtension.contains("Config_")){
1251 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1252 controller.deleteData(policyEntity.getConfigurationData());
1253 }else if(policyNamewithoutExtension.contains("Action_")){
1254 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1255 controller.deleteData(policyEntity.getActionBodyEntity());
1259 int highestVersion = 0;
1260 if(!policyEntityobjects.isEmpty()){
1261 for(Object object : policyEntityobjects){
1262 policyEntity = (PolicyEntity) object;
1263 String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
1264 int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf('.')+1));
1265 if(policyEntityVersion > highestVersion && policyEntityVersion != version){
1266 highestVersion = policyEntityVersion;
1271 //Policy Notification
1272 PolicyVersion entity = new PolicyVersion();
1273 entity.setPolicyName(policyNamewithoutExtension);
1274 entity.setActiveVersion(highestVersion);
1275 entity.setModifiedBy(userId);
1276 controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne");
1278 String updatequery = "update PolicyVersion set active_version='"+highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"'";
1279 controller.executeQuery(updatequery);
1281 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1282 if(policyVersionQuery != null){
1283 controller.executeQuery(policyVersionQuery);
1287 return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'");
1292 List<String> activePoliciesInPDP = new ArrayList<String>();
1293 if(!policyEntityobjects.isEmpty()){
1294 for(Object object : policyEntityobjects){
1295 policyEntity = (PolicyEntity) object;
1296 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId";
1297 SimpleBindings geParams = new SimpleBindings();
1298 geParams.put("policyEntityId", policyEntity.getPolicyId());
1299 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1300 if(!groupobject.isEmpty()){
1302 activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName());
1304 //Delete the entity from Elastic Search Database
1305 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1306 restController.deleteElasticData(searchFileName);
1307 //Delete the entity from Policy Entity table
1308 controller.deleteData(policyEntity);
1309 policyNamewithoutExtension = policyEntity.getPolicyName();
1310 if(policyNamewithoutExtension.contains("Config_")){
1311 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1312 controller.deleteData(policyEntity.getConfigurationData());
1313 }else if(policyNamewithoutExtension.contains("Action_")){
1314 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1315 controller.deleteData(policyEntity.getActionBodyEntity());
1319 //Delete from policyVersion and policyEditor Scope table
1320 String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1321 controller.executeQuery(policyVersionQuery);
1323 //Policy Notification
1324 PolicyVersion entity = new PolicyVersion();
1325 entity.setPolicyName(path);
1326 entity.setModifiedBy(userId);
1327 controller.watchPolicyFunction(entity, path, "DeleteScope");
1329 //Add Active Policies List to PolicyVersionTable
1330 for(int i =0; i < activePoliciesInPDP.size(); i++){
1331 String activePDPPolicyName = activePoliciesInPDP.get(i).replace(".xml", "");
1332 int activePDPPolicyVersion = Integer.parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf('.')+1));
1333 activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf('.')).replace(".", File.separator);
1334 PolicyVersion insertactivePDPVersion = new PolicyVersion();
1335 insertactivePDPVersion.setPolicyName(activePDPPolicyName);
1336 insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion);
1337 insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion);
1338 insertactivePDPVersion.setCreatedBy(userId);
1339 insertactivePDPVersion.setModifiedBy(userId);
1340 controller.saveData(insertactivePDPVersion);
1343 return error("All the Policies has been deleted in Scope. Except the following list of Policies:"+activePoliciesInPDP);
1345 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1346 controller.executeQuery(policyScopeQuery);
1349 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1350 controller.executeQuery(policyScopeQuery);
1354 } catch (Exception e) {
1355 LOGGER.error("delete", e);
1356 return error(e.getMessage());
1361 private JSONObject editFile(JSONObject params) throws ServletException {
1364 PolicyController controller = getPolicyControllerInstance();
1365 String mode = params.getString("mode");
1366 String path = params.getString("path");
1367 LOGGER.debug("editFile path: {}"+ path);
1369 String domain = path.substring(1, path.lastIndexOf('/'));
1370 domain = domain.replace("/", ".");
1372 path = path.substring(1);
1373 path = path.replace("/", ".");
1374 String dbCheckName = path;
1375 if(dbCheckName.contains("Config_")){
1376 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
1377 }else if(dbCheckName.contains("Action_")){
1378 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
1379 }else if(dbCheckName.contains("Decision_")){
1380 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
1383 String[] split = dbCheckName.split(":");
1384 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
1385 SimpleBindings peParams = new SimpleBindings();
1386 peParams.put("split_1", split[1]);
1387 peParams.put("split_0", split[0]);
1388 List<Object> queryData;
1389 if(PolicyController.isjUnit()){
1390 queryData = controller.getDataByQuery(query, null);
1392 queryData = controller.getDataByQuery(query, peParams);
1394 PolicyEntity entity = (PolicyEntity) queryData.get(0);
1395 InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
1398 Object policy = XACMLPolicyScanner.readPolicy(stream);
1399 PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
1400 policyAdapter.setData(policy);
1402 if("viewPolicy".equalsIgnoreCase(mode)){
1403 policyAdapter.setReadOnly(true);
1404 policyAdapter.setEditPolicy(false);
1406 policyAdapter.setReadOnly(false);
1407 policyAdapter.setEditPolicy(true);
1410 policyAdapter.setDomainDir(domain);
1411 policyAdapter.setPolicyData(policy);
1412 String policyName = path.replace(".xml", "");
1413 policyName = policyName.substring(0, policyName.lastIndexOf('.'));
1414 policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf('.')+1));
1416 PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance();
1417 setpolicyAdapter.configure(policyAdapter,entity);
1419 policyAdapter.setParentPath(null);
1420 ObjectMapper mapper = new ObjectMapper();
1421 String json = mapper.writeValueAsString(policyAdapter);
1422 JsonNode jsonNode = mapper.readTree(json);
1424 return new JSONObject().put(RESULT, jsonNode);
1425 } catch (Exception e) {
1426 LOGGER.error("editFile", e);
1427 return error(e.getMessage());
1432 private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
1433 PolicyController controller = getPolicyControllerInstance();
1436 String userId = UserUtils.getUserSession(request).getOrgUserId();
1437 String path = params.getString("path");
1439 if(params.has("subScopename")){
1440 if(! "".equals(params.getString("subScopename"))) {
1441 name = params.getString("path").replace("/", File.separator) + File.separator +params.getString("subScopename");
1444 name = params.getString("name");
1446 }catch(Exception e){
1447 name = params.getString("name");
1448 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e);
1450 String validateName;
1451 if(name.contains(File.separator)){
1452 validateName = name.substring(name.lastIndexOf(File.separator)+1);
1454 validateName = name;
1456 if(!name.isEmpty()){
1457 String validate = PolicyUtils.policySpecialCharValidator(validateName);
1458 if(!validate.contains("success")){
1459 return error(validate);
1462 LOGGER.debug("addFolder path: {} name: {}" + path +name);
1463 if(! "".equals(name)){
1464 if(name.startsWith(File.separator)){
1465 name = name.substring(1);
1467 PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, "scopeName", name);
1469 UserInfo userInfo = new UserInfo();
1470 userInfo.setUserLoginId(userId);
1471 PolicyEditorScopes newScope = new PolicyEditorScopes();
1472 newScope.setScopeName(name);
1473 newScope.setUserCreatedBy(userInfo);
1474 newScope.setUserModifiedBy(userInfo);
1475 controller.saveData(newScope);
1477 return error("Scope Already Exists");
1481 } catch (Exception e) {
1482 LOGGER.error("addFolder", e);
1483 return error(e.getMessage());
1487 //Return Error Object
1488 private JSONObject error(String msg) throws ServletException {
1490 JSONObject result = new JSONObject();
1491 result.put("success", false);
1492 result.put("error", msg);
1493 return new JSONObject().put(RESULT, result);
1494 } catch (JSONException e) {
1495 throw new ServletException(e);
1499 //Return Success Object
1500 private JSONObject success() throws ServletException {
1502 JSONObject result = new JSONObject();
1503 result.put("success", true);
1504 result.put("error", (Object) null);
1505 return new JSONObject().put(RESULT, result);
1506 } catch (JSONException e) {
1507 throw new ServletException(e);
1511 private PolicyController getPolicyControllerInstance(){
1512 return policyController != null ? getPolicyController() : new PolicyController();
1515 public String getTestUserId() {
1519 public static void setTestUserId(String testUserId) {
1520 PolicyManagerServlet.testUserId = testUserId;