2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.admin;
24 import java.io.BufferedReader;
25 import java.io.BufferedWriter;
26 import java.io.ByteArrayInputStream;
28 import java.io.FileInputStream;
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.Files;
37 import java.nio.file.Path;
38 import java.nio.file.Paths;
41 import javax.json.Json;
42 import javax.json.JsonArray;
43 import javax.json.JsonReader;
44 import javax.script.SimpleBindings;
45 import javax.servlet.ServletConfig;
46 import javax.servlet.ServletException;
47 import javax.servlet.annotation.WebInitParam;
48 import javax.servlet.annotation.WebServlet;
49 import javax.servlet.http.HttpServlet;
50 import javax.servlet.http.HttpServletRequest;
51 import javax.servlet.http.HttpServletResponse;
53 import org.apache.commons.compress.utils.IOUtils;
54 import org.apache.commons.fileupload.FileItem;
55 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
56 import org.apache.commons.fileupload.servlet.ServletFileUpload;
57 import org.apache.http.HttpStatus;
58 import org.json.JSONArray;
59 import org.json.JSONException;
60 import org.json.JSONObject;
61 import org.onap.policy.common.logging.flexlogger.FlexLogger;
62 import org.onap.policy.common.logging.flexlogger.Logger;
63 import org.onap.policy.components.HumanPolicyComponent;
64 import org.onap.policy.controller.PolicyController;
65 import org.onap.policy.controller.PolicyExportAndImportController;
66 import org.onap.policy.rest.XACMLRest;
67 import org.onap.policy.rest.XACMLRestProperties;
68 import org.onap.policy.rest.adapter.PolicyRestAdapter;
69 import org.onap.policy.rest.jpa.ActionBodyEntity;
70 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
71 import org.onap.policy.rest.jpa.PolicyEditorScopes;
72 import org.onap.policy.rest.jpa.PolicyEntity;
73 import org.onap.policy.rest.jpa.PolicyVersion;
74 import org.onap.policy.rest.jpa.UserInfo;
75 import org.onap.policy.utils.PolicyUtils;
76 import org.onap.policy.utils.UserUtils.Pair;
77 import org.onap.policy.xacml.api.XACMLErrorConstants;
78 import org.onap.policy.xacml.util.XACMLPolicyScanner;
79 import org.onap.portalsdk.core.web.support.UserUtils;
81 import com.att.research.xacml.util.XACMLProperties;
82 import com.fasterxml.jackson.databind.JsonNode;
83 import com.fasterxml.jackson.databind.ObjectMapper;
86 @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.") })
87 public class PolicyManagerServlet extends HttpServlet {
88 private static final Logger LOGGER = FlexLogger.getLogger(PolicyManagerServlet.class);
89 private static final long serialVersionUID = -8453502699403909016L;
90 private static final String VERSION = "version";
91 private static final String NAME = "name";
92 private static final String DATE = "date";
93 private static final String SIZE = "size";
94 private static final String TYPE = "type";
95 private static final String CREATED_BY = "createdBy";
96 private static final String MODIFIED_BY = "modifiedBy";
97 private static final String CONTENTTYPE = "application/json";
98 private static final String SUPERADMIN = "super-admin";
99 private static final String SUPEREDITOR = "super-editor";
100 private static final String SUPERGUEST = "super-guest";
101 private static final String ADMIN = "admin";
102 private static final String EDITOR = "editor";
103 private static final String GUEST = "guest";
104 private static final String RESULT = "result";
105 private static final String DELETE = "delete";
106 private static final String EXCEPTION_OCCURED = "Exception Occured";
107 private static final String CONFIG = ".Config_";
108 private static final String CONFIG1 = ":Config_";
109 private static final String ACTION = ".Action_";
110 private static final String ACTION1 = ":Action_";
111 private static final String DECISION = ".Decision_";
112 private static final String DECISION1 = ":Decision_";
113 private static final String CONFIG2 = "Config_";
114 private static final String ACTION2 = "Action_";
115 private static final String DECISION2 = "Decision_";
116 private static final String FORWARD_SLASH = "/";
117 private static final String BACKSLASH = "\\";
118 private static final String ESCAPE_BACKSLASH = "\\\\";
119 private static final String BACKSLASH_8TIMES = "\\\\\\\\";
120 private static final String DELETE_POLICY_VERSION_WHERE_POLICY_NAME = "delete from PolicyVersion where policy_name ='";
121 private static final String UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION = "update PolicyVersion set active_version='";
122 private static final String SPLIT_1 = "split_1";
123 private static final String SPLIT_0 = "split_0";
124 private static final String FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME = "from PolicyEditorScopes where SCOPENAME like :scopeName";
125 private static final String SCOPE_NAME = "scopeName";
126 private static final String SUCCESS = "success";
127 private static final String SUB_SCOPENAME = "subScopename";
128 private static final String PERCENT_AND_ID_GT_0 = "%' and id >0";
129 private static List<String> serviceTypeNamesList = new ArrayList<>();
130 private static JsonArray policyNames;
131 private static String testUserId = null;
134 LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT, SEARCHLIST
137 private static PolicyController policyController;
138 private synchronized PolicyController getPolicyController() {
139 return policyController;
142 public static synchronized void setPolicyController(PolicyController policyController) {
143 PolicyManagerServlet.policyController = policyController;
146 public static JsonArray getPolicyNames() {
150 public static void setPolicyNames(JsonArray policyNames) {
151 PolicyManagerServlet.policyNames = policyNames;
154 public static List<String> getServiceTypeNamesList() {
155 return serviceTypeNamesList;
159 public void init(ServletConfig servletConfig) throws ServletException {
160 super.init(servletConfig);
162 // Common initialization
164 XACMLRest.xacmlInit(servletConfig);
166 //Initialize ClosedLoop JSON
168 PolicyManagerServlet.initializeJSONLoad();
171 private static void initializeJSONLoad() {
172 Path closedLoopJsonLocation = Paths.get(XACMLProperties
173 .getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP));
174 String location = closedLoopJsonLocation.toString();
175 if (! location.endsWith("json")) {
176 LOGGER.warn("JSONConfig file does not end with extension .json");
179 try (FileInputStream inputStream = new FileInputStream(location);
180 JsonReader jsonReader = Json.createReader(inputStream)) {
181 policyNames = jsonReader.readArray();
182 serviceTypeNamesList = new ArrayList<>();
183 for (int i = 0; i < policyNames.size(); i++) {
184 javax.json.JsonObject policyName = policyNames.getJsonObject(i);
185 String name = policyName.getJsonString("serviceTypePolicyName").getString();
186 serviceTypeNamesList.add(name);
188 } catch (IOException e) {
189 LOGGER.error("Exception Occured while initializing the JSONConfig file"+e);
194 protected void doPost(HttpServletRequest request, HttpServletResponse response) {
195 LOGGER.debug("doPost");
197 // if request contains multipart-form-data
198 if (ServletFileUpload.isMultipartContent(request)) {
199 uploadFile(request, response);
201 // all other post request has json params in body
203 fileOperation(request, response);
205 } catch (Exception e) {
207 setError(e, response);
208 }catch(Exception e1){
209 LOGGER.error(EXCEPTION_OCCURED +e1);
214 //Set Error Message for Exception
215 private void setError(Exception t, HttpServletResponse response) throws IOException {
217 JSONObject responseJsonObject = error(t.getMessage());
218 response.setContentType(CONTENTTYPE);
219 PrintWriter out = response.getWriter();
220 out.print(responseJsonObject);
222 } catch (Exception x) {
223 LOGGER.error(EXCEPTION_OCCURED +x);
224 response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage());
228 //Policy Import Functionality
229 private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException {
231 Map<String, InputStream> files = new HashMap<>();
233 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
234 for (FileItem item : items) {
235 if (!item.isFormField()) {
236 // Process form file field (input type="file").
237 files.put(item.getName(), item.getInputStream());
238 processFormFile(request, item);
242 JSONObject responseJsonObject;
243 responseJsonObject = this.success();
244 response.setContentType(CONTENTTYPE);
245 PrintWriter out = response.getWriter();
246 out.print(responseJsonObject);
248 } catch (Exception e) {
249 LOGGER.debug("Cannot write file");
250 throw new ServletException("Cannot write file", e);
254 private void processFormFile(HttpServletRequest request, FileItem item) {
256 if(item.getName().endsWith(".xls") && item.getSize() <= PolicyController.getFileSizeLimit()){
257 File file = new File(item.getName());
258 try (OutputStream outputStream = new FileOutputStream(file))
260 IOUtils.copy(item.getInputStream(), outputStream);
261 newFile = file.toString();
262 PolicyExportAndImportController importController = new PolicyExportAndImportController();
263 importController.importRepositoryFile(newFile, request);
265 LOGGER.error("Upload error : " + e);
268 else if (!item.getName().endsWith(".xls")) {
269 LOGGER.error("Non .xls filetype uploaded: " + item.getName());
271 else { //uploaded file size is greater than allowed
272 LOGGER.error("Upload file size limit exceeded! File size (Bytes) is: " + item.getSize());
276 //File Operation Functionality
277 private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException {
278 JSONObject responseJsonObject;
279 StringBuilder sb = new StringBuilder();
280 try (BufferedReader br = request.getReader()) {
282 while ((str = br.readLine()) != null) {
285 } catch (Exception e) {
286 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While doing File Operation" + e);
287 responseJsonObject = error(e.getMessage());
288 setResponse(response, responseJsonObject);
292 JSONObject jObj = new JSONObject(sb.toString());
293 JSONObject params = jObj.getJSONObject("params");
294 Mode mode = Mode.valueOf(params.getString("mode"));
296 String userId = UserUtils.getUserSession(request).getOrgUserId();
297 LOGGER.info("****************************************Logging UserID while doing actions on Editor tab*******************************************");
298 LOGGER.info("UserId: " + userId + "Action Mode: "+ mode.toString() + "Action Params: "+params.toString());
299 LOGGER.info("***********************************************************************************************************************************");
300 responseJsonObject = operateBasedOnMode(mode, params, request);
301 } catch (Exception e) {
302 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Processing Json" + e);
303 responseJsonObject = error(e.getMessage());
305 setResponse(response, responseJsonObject);
308 private void setResponse(HttpServletResponse response, JSONObject responseJsonObject) {
309 response.setContentType(CONTENTTYPE);
310 try (PrintWriter out = response.getWriter()) {
311 out.print(responseJsonObject);
313 } catch (IOException e) {
314 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception occured while writing response" + e);
319 private JSONObject operateBasedOnMode(Mode mode, JSONObject params, HttpServletRequest request) throws ServletException{
320 JSONObject responseJsonObject;
324 responseJsonObject = addFolder(params, request);
327 responseJsonObject = copy(params, request);
330 responseJsonObject = delete(params, request);
334 responseJsonObject = editFile(params);
337 responseJsonObject = list(params, request);
340 responseJsonObject = rename(params, request);
342 case DESCRIBEPOLICYFILE:
343 responseJsonObject = describePolicy(params);
346 responseJsonObject = switchVersion(params, request);
349 responseJsonObject = searchPolicyList(params, request);
352 throw new ServletException("not implemented");
354 if (responseJsonObject == null) {
355 responseJsonObject = error("generic error : responseJsonObject is null");
357 return responseJsonObject;
361 private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) {
362 List<Object> policyData = new ArrayList<>();
363 JSONArray policyList = null;
364 if(params.has("policyList")){
365 policyList = (JSONArray) params.get("policyList");
367 PolicyController controller = getPolicyControllerInstance();
368 List<JSONObject> resultList = new ArrayList<>();
370 if (!lookupPolicyData(request, policyData, policyList, controller, resultList))
371 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
374 LOGGER.error("Exception occured while reading policy Data from Policy Version table for Policy Search Data"+e);
377 return new JSONObject().put(RESULT, resultList);
380 private boolean lookupPolicyData(HttpServletRequest request, List<Object> policyData, JSONArray policyList, PolicyController controller, List<JSONObject> resultList){
382 Set<String> scopes;//Get the Login Id of the User from Request
383 String userId = UserUtils.getUserSession(request).getOrgUserId();
384 List<Object> userRoles = controller.getRoles(userId);
385 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
388 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
389 if(scopes.isEmpty()){
392 Set<String> tempScopes = scopes;
393 for(String scope : tempScopes){
394 addScope(scopes, scope);
397 if(policyList!= null){
398 for(int i = 0; i < policyList.length(); i++){
399 String policyName = policyList.get(i).toString().replace(".xml", "");
400 String version = policyName.substring(policyName.lastIndexOf('.')+1);
401 policyName = policyName.substring(0, policyName.lastIndexOf('.')).replace(".", File.separator);
402 parsePolicyList(resultList, controller, policyName, version);
405 getPolicyDataForSUPERRoles(policyData, controller, resultList, roles, scopes);
410 private void getPolicyDataForSUPERRoles(List<Object> policyData, PolicyController controller, List<JSONObject> resultList, List<String> roles, Set<String> scopes) {
411 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ){
412 policyData = controller.getData(PolicyVersion.class);
414 List<Object> filterdatas = controller.getData(PolicyVersion.class);
415 for(Object filter : filterdatas) {
416 addFilterData(policyData, scopes, (PolicyVersion) filter);
420 if(!policyData.isEmpty()){
421 updateResultList(policyData, resultList);
425 private void addFilterData(List<Object> policyData, Set<String> scopes, PolicyVersion filter) {
427 String scopeName = filter.getPolicyName().substring(0, filter.getPolicyName().lastIndexOf(File.separator));
428 if(scopes.contains(scopeName)){
429 policyData.add(filter);
432 LOGGER.error("Exception occured while filtering policyversion data"+e);
436 private void updateResultList(List<Object> policyData, List<JSONObject> resultList) {
437 for (Object aPolicyData : policyData) {
438 PolicyVersion policy = (PolicyVersion) aPolicyData;
439 JSONObject el = new JSONObject();
440 el.put(NAME, policy.getPolicyName().replace(File.separator, FORWARD_SLASH));
441 el.put(DATE, policy.getModifiedDate());
442 el.put(VERSION, policy.getActiveVersion());
444 el.put(TYPE, "file");
445 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
446 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
451 private void parsePolicyList(List<JSONObject> resultList, PolicyController controller, String policyName, String version) {
452 if(policyName.contains(BACKSLASH)){
453 policyName = policyName.replace(BACKSLASH, ESCAPE_BACKSLASH);
455 String policyVersionQuery = "From PolicyVersion where policy_name = :policyName and active_version = :version and id >0";
456 SimpleBindings pvParams = new SimpleBindings();
457 pvParams.put("policyName", policyName);
458 pvParams.put(VERSION, version);
459 List<Object> activeData = controller.getDataByQuery(policyVersionQuery, pvParams);
460 if(!activeData.isEmpty()){
461 PolicyVersion policy = (PolicyVersion) activeData.get(0);
462 JSONObject el = new JSONObject();
463 el.put(NAME, policy.getPolicyName().replace(File.separator, FORWARD_SLASH));
464 el.put(DATE, policy.getModifiedDate());
465 el.put(VERSION, policy.getActiveVersion());
467 el.put(TYPE, "file");
468 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
469 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
474 private void addScope(Set<String> scopes, String scope) {
475 List<Object> scopesList = queryPolicyEditorScopes(scope);
476 if(!scopesList.isEmpty()){
477 for (Object aScopesList : scopesList) {
478 PolicyEditorScopes tempScope = (PolicyEditorScopes) aScopesList;
479 scopes.add(tempScope.getScopeName());
484 //Switch Version Functionality
485 private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{
486 String path = params.getString("path");
487 String userId = null;
489 userId = UserUtils.getUserSession(request).getOrgUserId();
490 } catch (Exception e) {
491 LOGGER.error("Exception Occured while reading userid from cookie" +e);
494 String removeExtension = path.replace(".xml", "");
495 if(path.startsWith(FORWARD_SLASH)){
496 policyName = removeExtension.substring(1, removeExtension.lastIndexOf('.'));
498 policyName = removeExtension.substring(0, removeExtension.lastIndexOf('.'));
502 PolicyController controller = getPolicyControllerInstance();
503 if(! params.toString().contains("activeVersion")){
504 return controller.switchVersionPolicyContent(policyName);
506 String activeVersion = params.getString("activeVersion");
507 String highestVersion = params.get("highestVersion").toString();
508 if(Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)){
509 return error("The Version shouldn't be greater than Highest Value");
511 activePolicy = policyName + "." + activeVersion + ".xml";
512 String[] splitDBCheckName = modifyPolicyName(activePolicy);
513 String peQuery = "FROM PolicyEntity where policyName = :splitDBCheckName_1 and scope = :splitDBCheckName_0";
514 SimpleBindings policyParams = new SimpleBindings();
515 policyParams.put("splitDBCheckName_1", splitDBCheckName[1]);
516 policyParams.put("splitDBCheckName_0", splitDBCheckName[0]);
517 List<Object> policyEntity = controller.getDataByQuery(peQuery, policyParams);
518 PolicyEntity pentity = (PolicyEntity) policyEntity.get(0);
519 if(pentity.isDeleted()){
520 return error("The Policy is Not Existing in Workspace");
522 if(policyName.contains(FORWARD_SLASH)){
523 policyName = policyName.replace(FORWARD_SLASH, File.separator);
525 policyName = policyName.substring(policyName.indexOf(File.separator)+1);
526 if(policyName.contains(BACKSLASH)){
527 policyName = policyName.replace(File.separator, BACKSLASH);
529 policyName = splitDBCheckName[0].replace(".", File.separator)+File.separator+policyName;
530 String watchPolicyName = policyName;
531 if(policyName.contains(FORWARD_SLASH)){
532 policyName = policyName.replace(FORWARD_SLASH, File.separator);
534 if(policyName.contains(BACKSLASH)){
535 policyName = policyName.replace(BACKSLASH, ESCAPE_BACKSLASH);
537 String query = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION +activeVersion+"' where policy_name ='"+policyName+"' and id >0";
539 controller.executeQuery(query);
540 //Policy Notification
541 PolicyVersion entity = new PolicyVersion();
542 entity.setPolicyName(watchPolicyName);
543 entity.setActiveVersion(Integer.parseInt(activeVersion));
544 entity.setModifiedBy(userId);
545 controller.watchPolicyFunction(entity, activePolicy, "SwitchVersion");
550 private JSONObject describePolicy(JSONObject params) throws ServletException{
552 String path = params.getString("path");
554 if(path.startsWith(FORWARD_SLASH)){
555 path = path.substring(1);
556 policyName = path.substring(path.lastIndexOf('/') +1);
557 path = path.replace(FORWARD_SLASH, ".");
559 path = path.replace(FORWARD_SLASH, ".");
562 if(path.contains(CONFIG2)){
563 path = path.replace(CONFIG, CONFIG1);
564 }else if(path.contains(ACTION2)){
565 path = path.replace(ACTION, ACTION1);
566 }else if(path.contains(DECISION2)){
567 path = path.replace(DECISION, DECISION1);
569 PolicyController controller = getPolicyControllerInstance();
570 String[] split = path.split(":");
571 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
572 SimpleBindings peParams = new SimpleBindings();
573 peParams.put(SPLIT_1, split[1]);
574 peParams.put(SPLIT_0, split[0]);
575 List<Object> queryData;
576 if(PolicyController.isjUnit()){
577 queryData = controller.getDataByQuery(query, null);
579 queryData = controller.getDataByQuery(query, peParams);
581 if(queryData.isEmpty()){
582 return error("Error Occured while Describing the Policy - query is empty");
584 PolicyEntity entity = (PolicyEntity) queryData.get(0);
587 temp = File.createTempFile(policyName, ".tmp");
588 } catch (IOException e) {
589 String message = "Failed to create temp file " + policyName + ".tmp";
590 LOGGER.error(message + e);
591 return error(message);
593 try (BufferedWriter bw = new BufferedWriter(new FileWriter(temp))) {
594 bw.write(entity.getPolicyData());
595 } catch (IOException e) {
596 LOGGER.error("Exception Occured while Describing the Policy"+e);
598 object = HumanPolicyComponent.DescribePolicy(temp);
600 Files.delete(temp.toPath());
601 } catch (IOException e) {
602 LOGGER.warn("Failed to delete " + temp.getName() + e);
607 //Get the List of Policies and Scopes for Showing in Editor tab
608 private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException {
610 return processPolicyList(params, request);
611 } catch (Exception e) {
612 LOGGER.error("list", e);
613 return error(e.getMessage());
617 private JSONObject processPolicyList(JSONObject params, HttpServletRequest request) throws ServletException {
618 PolicyController controller = getPolicyControllerInstance();
619 //Get the Login Id of the User from Request
620 String testUserID = getTestUserId();
621 String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId();
622 List<Object> userRoles = controller.getRoles(userId);
623 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
624 List<String> roles = pair.u;
625 Set<String> scopes = pair.t;
627 List<JSONObject> resultList = new ArrayList<>();
628 boolean onlyFolders = params.getBoolean("onlyFolders");
629 String path = params.getString("path");
630 if(path.contains("..xml")){
631 path = path.replaceAll("..xml", "").trim();
634 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
635 if(scopes.isEmpty()){
636 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
638 if(!FORWARD_SLASH.equals(path)){
639 String tempScope = path.substring(1, path.length());
640 tempScope = tempScope.replace(FORWARD_SLASH, File.separator);
641 scopes.add(tempScope);
646 if (!FORWARD_SLASH.equals(path)) {
648 String scopeName = path.substring(path.indexOf('/') +1);
649 activePolicyList(scopeName, resultList, roles, scopes, onlyFolders);
650 } catch (Exception ex) {
651 LOGGER.error("Error Occured While reading Policy Files List"+ex );
653 return new JSONObject().put(RESULT, resultList);
656 processRoles(scopes, roles, resultList);
658 return new JSONObject().put(RESULT, resultList);
661 private void processRoles(Set<String> scopes, List<String> roles, List<JSONObject> resultList) {
662 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
663 List<Object> scopesList = queryPolicyEditorScopes(null);
664 for(Object list : scopesList){
665 PolicyEditorScopes scope = (PolicyEditorScopes) list;
666 if(!(scope.getScopeName().contains(File.separator))){
667 JSONObject el = new JSONObject();
668 el.put(NAME, scope.getScopeName());
669 el.put(DATE, scope.getModifiedDate());
672 el.put(CREATED_BY, scope.getUserCreatedBy().getUserName());
673 el.put(MODIFIED_BY, scope.getUserModifiedBy().getUserName());
677 }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){
678 for(Object scope : scopes){
679 JSONObject el = new JSONObject();
680 List<Object> scopesList = queryPolicyEditorScopes(scope.toString());
681 if(!scopesList.isEmpty()){
682 PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
683 el.put(NAME, scopeById.getScopeName());
684 el.put(DATE, scopeById.getModifiedDate());
687 el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName());
688 el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName());
695 private List<Object> queryPolicyEditorScopes(String scopeName){
696 String scopeNamequery;
697 SimpleBindings params = new SimpleBindings();
698 if(scopeName == null){
699 scopeNamequery = "from PolicyEditorScopes";
701 scopeNamequery = FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME;
702 params.put(SCOPE_NAME, scopeName + "%");
704 PolicyController controller = getPolicyControllerInstance();
705 List<Object> scopesList;
706 if(PolicyController.isjUnit()){
707 scopesList = controller.getDataByQuery(scopeNamequery, null);
709 scopesList = controller.getDataByQuery(scopeNamequery, params);
714 //Get Active Policy List based on Scope Selection form Policy Version table
715 private void activePolicyList(String inScopeName, List<JSONObject> resultList, List<String> roles, Set<String> scopes, boolean onlyFolders){
716 PolicyController controller = getPolicyControllerInstance();
717 String scopeName = inScopeName;
718 if(scopeName.contains(FORWARD_SLASH)){
719 scopeName = scopeName.replace(FORWARD_SLASH, File.separator);
721 if(scopeName.contains(BACKSLASH)){
722 scopeName = scopeName.replace(BACKSLASH, ESCAPE_BACKSLASH);
724 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
725 String scopeNamequery = FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME;
727 SimpleBindings params = new SimpleBindings();
728 params.put(SCOPE_NAME, scopeName + "%");
730 List<Object> activePolicies;
731 List<Object> scopesList;
732 if(PolicyController.isjUnit()){
733 activePolicies = controller.getDataByQuery(query, null);
734 scopesList = controller.getDataByQuery(scopeNamequery, null);
736 activePolicies = controller.getDataByQuery(query, params);
737 scopesList = controller.getDataByQuery(scopeNamequery, params);
739 for(Object list : scopesList) {
740 scopeName = checkScope(resultList, scopeName, (PolicyEditorScopes) list);
742 String scopeNameCheck;
743 for (Object list : activePolicies) {
744 PolicyVersion policy = (PolicyVersion) list;
745 String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator));
746 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
747 if(scopeName.contains(ESCAPE_BACKSLASH)){
748 scopeNameCheck = scopeName.replace(ESCAPE_BACKSLASH, File.separator);
750 scopeNameCheck = scopeName;
752 if(scopeNameValue.equals(scopeNameCheck)){
753 JSONObject el = new JSONObject();
754 el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
755 el.put(DATE, policy.getModifiedDate());
756 el.put(VERSION, policy.getActiveVersion());
758 el.put(TYPE, "file");
759 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
760 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
763 }else if(!scopes.isEmpty() && scopes.contains(scopeNameValue)){
764 JSONObject el = new JSONObject();
765 el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
766 el.put(DATE, policy.getModifiedDate());
767 el.put(VERSION, policy.getActiveVersion());
769 el.put(TYPE, "file");
770 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
771 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
777 private String checkScope(List<JSONObject> resultList, String scopeName, PolicyEditorScopes scopeById) {
778 String scope = scopeById.getScopeName();
779 if(scope.contains(File.separator)){
780 String targetScope = scope.substring(0, scope.lastIndexOf(File.separator));
781 if(scopeName.contains(ESCAPE_BACKSLASH)){
782 scopeName = scopeName.replace(ESCAPE_BACKSLASH, File.separator);
784 if(scope.contains(File.separator)){
785 scope = scope.substring(targetScope.length()+1);
786 if(scope.contains(File.separator)){
787 scope = scope.substring(0, scope.indexOf(File.separator));
790 if(scopeName.equalsIgnoreCase(targetScope)){
791 JSONObject el = new JSONObject();
793 el.put(DATE, scopeById.getModifiedDate());
796 el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName());
797 el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName());
804 private String getUserName(String loginId){
805 PolicyController controller = getPolicyControllerInstance();
806 UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
807 if(userInfo == null){
810 return userInfo.getUserName();
814 private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
816 return handlePolicyRename(params, request);
817 } catch (Exception e) {
818 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
819 return error(e.getMessage());
823 private JSONObject handlePolicyRename(JSONObject params, HttpServletRequest request) throws ServletException {
824 boolean isActive = false;
825 List<String> policyActiveInPDP = new ArrayList<>();
826 Set<String> scopeOfPolicyActiveInPDP = new HashSet<>();
827 String userId = UserUtils.getUserSession(request).getOrgUserId();
828 String oldPath = params.getString("path");
829 String newPath = params.getString("newPath");
830 oldPath = oldPath.substring(oldPath.indexOf('/')+1);
831 newPath = newPath.substring(newPath.indexOf('/')+1);
832 String checkValidation;
833 if(oldPath.endsWith(".xml")){
834 checkValidation = newPath.replace(".xml", "");
835 checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf("."));
836 checkValidation = checkValidation.substring(checkValidation.lastIndexOf(FORWARD_SLASH)+1);
837 if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)){
838 return error("Policy Rename Failed. The Name contains special characters.");
840 JSONObject result = policyRename(oldPath, newPath, userId);
841 if(!(Boolean)(result.getJSONObject(RESULT).get(SUCCESS))){
845 String scopeName = oldPath;
846 String newScopeName = newPath;
847 if(scopeName.contains(FORWARD_SLASH)){
848 scopeName = scopeName.replace(FORWARD_SLASH, File.separator);
849 newScopeName = newScopeName.replace(FORWARD_SLASH, File.separator);
851 checkValidation = newScopeName.substring(newScopeName.lastIndexOf(File.separator)+1);
852 if(scopeName.contains(BACKSLASH)){
853 scopeName = scopeName.replace(BACKSLASH, BACKSLASH_8TIMES);
854 newScopeName = newScopeName.replace(BACKSLASH, BACKSLASH_8TIMES);
856 if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)){
857 return error("Scope Rename Failed. The Name contains special characters.");
859 PolicyController controller = getPolicyControllerInstance();
860 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
861 String scopeNamequery = FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME;
862 SimpleBindings pvParams = new SimpleBindings();
863 pvParams.put(SCOPE_NAME, scopeName + "%");
864 List<Object> activePolicies = controller.getDataByQuery(query, pvParams);
865 List<Object> scopesList = controller.getDataByQuery(scopeNamequery, pvParams);
866 for(Object object : activePolicies){
867 PolicyVersion activeVersion = (PolicyVersion) object;
868 String policyOldPath = activeVersion.getPolicyName().replace(File.separator, FORWARD_SLASH) + "." + activeVersion.getActiveVersion() + ".xml";
869 String policyNewPath = policyOldPath.replace(oldPath, newPath);
870 JSONObject result = policyRename(policyOldPath, policyNewPath, userId);
871 if(!(Boolean)(result.getJSONObject("result").get(SUCCESS))){
873 policyActiveInPDP.add(policyOldPath);
874 String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf('/'));
875 scopeOfPolicyActiveInPDP.add(scope.replace(FORWARD_SLASH, File.separator));
878 boolean rename = false;
879 if(activePolicies.size() != policyActiveInPDP.size()){
883 UserInfo userInfo = new UserInfo();
884 userInfo.setUserLoginId(userId);
885 if(policyActiveInPDP.isEmpty()){
886 renameScope(scopesList, scopeName, newScopeName, controller);
888 renameScope(scopesList, scopeName, newScopeName, controller);
889 for(String scope : scopeOfPolicyActiveInPDP){
890 PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes();
891 editorScopeEntity.setScopeName(scope.replace(BACKSLASH, BACKSLASH_8TIMES));
892 editorScopeEntity.setUserCreatedBy(userInfo);
893 editorScopeEntity.setUserModifiedBy(userInfo);
894 controller.saveData(editorScopeEntity);
898 return error("The Following policies rename failed. Since they are active in PDP Groups" +policyActiveInPDP);
904 private void renameScope(List<Object> scopesList, String inScopeName, String newScopeName, PolicyController controller){
905 for(Object object : scopesList){
906 PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object;
907 String scopeName = inScopeName;
908 if(scopeName.contains(BACKSLASH_8TIMES)){
909 scopeName = scopeName.replace(BACKSLASH_8TIMES, File.separator);
910 newScopeName = newScopeName.replace(BACKSLASH_8TIMES, File.separator);
912 String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName);
913 editorScopeEntity.setScopeName(scope);
914 controller.updateData(editorScopeEntity);
918 private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
921 PolicyController controller = getPolicyControllerInstance();
923 String policyVersionName = newPath.replace(".xml", "");
924 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')).replace(FORWARD_SLASH, File.separator);
926 String oldpolicyVersionName = oldPath.replace(".xml", "");
927 String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf('.')).replace(FORWARD_SLASH, File.separator);
928 String newpolicyName = newPath.replace("/", ".");
929 String[] newPolicySplit = modifyPolicyName(newPath);
931 String[] oldPolicySplit = modifyPolicyName(oldPath);
933 //Check PolicyEntity table with newPolicy Name
934 String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
935 SimpleBindings policyParams = new SimpleBindings();
936 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
937 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
938 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
939 if(!queryData.isEmpty()){
940 return error("Policy rename failed. Since, the policy with same name already exists.");
943 //Query the Policy Entity with oldPolicy Name
944 String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf('.'));
945 String oldpolicyEntityquery = "FROM PolicyEntity where policyName like :policyEntityCheck and scope = :oldPolicySplit_0";
946 SimpleBindings params = new SimpleBindings();
947 params.put("policyEntityCheck", policyEntityCheck + "%");
948 params.put("oldPolicySplit_0", oldPolicySplit[0]);
949 List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery, params);
950 if(oldEntityData.isEmpty()){
951 return error("Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin.");
954 StringBuilder groupQuery = new StringBuilder();
955 groupQuery.append("FROM PolicyGroupEntity where (");
956 SimpleBindings geParams = new SimpleBindings();
957 for(int i=0; i<oldEntityData.size(); i++){
958 entity = (PolicyEntity) oldEntityData.get(i);
960 groupQuery.append("policyid = :policyId");
961 geParams.put("policyId", entity.getPolicyId());
963 groupQuery.append(" or policyid = :policyId").append(i);
964 geParams.put("policyId" + i, entity.getPolicyId());
967 groupQuery.append(")");
968 List<Object> groupEntityData = controller.getDataByQuery(groupQuery.toString(), geParams);
969 if(! groupEntityData.isEmpty()){
970 return error("Policy rename failed. Since the policy or its version is active in PDP Groups.");
972 for (Object anOldEntityData : oldEntityData) {
973 entity = (PolicyEntity) anOldEntityData;
974 String checkEntityName = entity.getPolicyName().replace(".xml", "");
975 checkEntityName = checkEntityName.substring(0, checkEntityName.lastIndexOf('.'));
976 String originalPolicyName = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator) + 1);
977 if (checkEntityName.equals(originalPolicyName)) {
978 checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0], newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
983 } catch (Exception e) {
984 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
985 return error(e.getMessage());
989 private String[] modifyPolicyName(String pathName) {
990 return modifyPolicyName(FORWARD_SLASH, pathName);
993 private String[] modifyPolicyName(String separator, String pathName) {
994 String policyName = pathName.replace(separator, ".");
995 if(policyName.contains(CONFIG2)){
996 policyName = policyName.replace(CONFIG, CONFIG1);
997 }else if(policyName.contains(ACTION2)){
998 policyName = policyName.replace(ACTION, ACTION1);
999 }else if(policyName.contains(DECISION2)){
1000 policyName = policyName.replace(DECISION, DECISION1);
1002 return policyName.split(":");
1005 private void checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, String oldScope, String removeoldPolicyExtension,
1006 String policyName, String newpolicyName, String oldpolicyName, String userId) {
1008 ConfigurationDataEntity configEntity = entity.getConfigurationData();
1009 ActionBodyEntity actionEntity = entity.getActionBodyEntity();
1010 PolicyController controller = getPolicyControllerInstance();
1012 String oldPolicyNameWithoutExtension = removeoldPolicyExtension;
1013 String newPolicyNameWithoutExtension = removenewPolicyExtension;
1014 if(removeoldPolicyExtension.endsWith(".xml")){
1015 oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf('.'));
1016 newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf('.'));
1018 entity.setPolicyName(entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
1019 entity.setPolicyData(entity.getPolicyData().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
1020 entity.setScope(newScope);
1021 entity.setModifiedBy(userId);
1023 String oldConfigurationName = null;
1024 String newConfigurationName = null;
1025 if(newpolicyName.contains(CONFIG2)){
1026 oldConfigurationName = configEntity.getConfigurationName();
1027 configEntity.setConfigurationName(configEntity.getConfigurationName().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
1028 controller.updateData(configEntity);
1029 newConfigurationName = configEntity.getConfigurationName();
1030 File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName);
1032 File renamefile = new File(PolicyController.getConfigHome() + File.separator + newConfigurationName);
1033 file.renameTo(renamefile);
1035 }else if(newpolicyName.contains(ACTION2)){
1036 oldConfigurationName = actionEntity.getActionBodyName();
1037 actionEntity.setActionBody(actionEntity.getActionBody().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
1038 controller.updateData(actionEntity);
1039 newConfigurationName = actionEntity.getActionBodyName();
1040 File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName);
1042 File renamefile = new File(PolicyController.getActionHome() + File.separator + newConfigurationName);
1043 file.renameTo(renamefile);
1046 controller.updateData(entity);
1048 PolicyRestController restController = new PolicyRestController();
1049 restController.notifyOtherPAPSToUpdateConfigurations("rename", newConfigurationName, oldConfigurationName);
1050 PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldpolicyName);
1051 versionEntity.setPolicyName(policyName);
1052 versionEntity.setModifiedBy(userId);
1053 controller.updateData(versionEntity);
1054 String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator)+1);
1055 String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
1056 if(movePolicyCheck.equals(moveOldPolicyCheck)){
1057 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move");
1059 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename");
1061 } catch (Exception e) {
1062 LOGGER.error(EXCEPTION_OCCURED +e);
1067 private void cloneRecord(String newpolicyName, String oldScope, String inRemoveoldPolicyExtension, String newScope,
1068 String inRemovenewPolicyExtension, PolicyEntity entity, String userId) throws IOException{
1069 String queryEntityName;
1070 PolicyController controller = getPolicyControllerInstance();
1071 PolicyEntity cloneEntity = new PolicyEntity();
1072 cloneEntity.setPolicyName(newpolicyName);
1073 String removeoldPolicyExtension = inRemoveoldPolicyExtension;
1074 String removenewPolicyExtension = inRemovenewPolicyExtension;
1075 removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
1076 removenewPolicyExtension = removenewPolicyExtension.replace(".xml", "");
1077 cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope+"."+removeoldPolicyExtension, newScope+"."+removenewPolicyExtension));
1078 cloneEntity.setScope(entity.getScope());
1079 String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
1080 String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
1081 String newConfigurationName = null;
1082 if(newpolicyName.contains(CONFIG2)){
1083 ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
1084 configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1085 queryEntityName = configurationDataEntity.getConfigurationName();
1086 configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody());
1087 configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType());
1088 configurationDataEntity.setDeleted(false);
1089 configurationDataEntity.setCreatedBy(userId);
1090 configurationDataEntity.setModifiedBy(userId);
1091 controller.saveData(configurationDataEntity);
1092 ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
1093 cloneEntity.setConfigurationData(configEntiy);
1094 newConfigurationName = configEntiy.getConfigurationName();
1095 try (FileWriter fw = new FileWriter(PolicyController.getConfigHome() + File.separator + newConfigurationName);
1096 BufferedWriter bw = new BufferedWriter(fw)){
1097 bw.write(configEntiy.getConfigBody());
1098 } catch (IOException e) {
1099 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1102 }else if(newpolicyName.contains(ACTION2)){
1103 ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
1104 actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1105 queryEntityName = actionBodyEntity.getActionBodyName();
1106 actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody());
1107 actionBodyEntity.setDeleted(false);
1108 actionBodyEntity.setCreatedBy(userId);
1109 actionBodyEntity.setModifiedBy(userId);
1110 controller.saveData(actionBodyEntity);
1111 ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class, "actionBodyName", queryEntityName);
1112 cloneEntity.setActionBodyEntity(actionEntiy);
1113 newConfigurationName = actionEntiy.getActionBodyName();
1114 try (FileWriter fw = new FileWriter(PolicyController.getActionHome() + File.separator + newConfigurationName);
1115 BufferedWriter bw = new BufferedWriter(fw)){
1116 bw.write(actionEntiy.getActionBody());
1117 } catch (IOException e) {
1118 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1123 cloneEntity.setDeleted(entity.isDeleted());
1124 cloneEntity.setCreatedBy(userId);
1125 cloneEntity.setModifiedBy(userId);
1126 controller.saveData(cloneEntity);
1128 //Notify others paps regarding clone policy.
1129 PolicyRestController restController = new PolicyRestController();
1130 restController.notifyOtherPAPSToUpdateConfigurations("clonePolicy", newConfigurationName, null);
1134 private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
1136 String userId = UserUtils.getUserSession(request).getOrgUserId();
1137 String oldPath = params.getString("path");
1138 String newPath = params.getString("newPath");
1139 oldPath = oldPath.substring(oldPath.indexOf('/')+1);
1140 newPath = newPath.substring(newPath.indexOf('/')+1);
1142 String policyVersionName = newPath.replace(".xml", "");
1143 String version = policyVersionName.substring(policyVersionName.indexOf('.')+1);
1144 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')).replace(FORWARD_SLASH, File.separator);
1146 String newpolicyName = newPath.replace(FORWARD_SLASH, ".");
1148 String orignalPolicyName = oldPath.replace(FORWARD_SLASH, ".");
1150 String newPolicyCheck = newpolicyName;
1151 if(newPolicyCheck.contains(CONFIG2)){
1152 newPolicyCheck = newPolicyCheck.replace(CONFIG, CONFIG1);
1153 }else if(newPolicyCheck.contains(ACTION2)){
1154 newPolicyCheck = newPolicyCheck.replace(ACTION, ACTION1);
1155 }else if(newPolicyCheck.contains(DECISION2)){
1156 newPolicyCheck = newPolicyCheck.replace(DECISION, DECISION1);
1158 if(!newPolicyCheck.contains(":")){
1159 return error("Policy Clone Failed. The Name contains special characters.");
1161 String[] newPolicySplit = newPolicyCheck.split(":");
1163 String checkValidation = newPolicySplit[1].replace(".xml", "");
1164 checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf("."));
1165 if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)){
1166 return error("Policy Clone Failed. The Name contains special characters.");
1169 String[] oldPolicySplit = modifyPolicyName(orignalPolicyName);
1171 PolicyController controller = getPolicyControllerInstance();
1173 PolicyEntity entity = null;
1174 boolean success = false;
1176 //Check PolicyEntity table with newPolicy Name
1177 String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
1178 SimpleBindings policyParams = new SimpleBindings();
1179 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
1180 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
1181 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
1182 if(!queryData.isEmpty()){
1183 return error("Policy already exists with same name");
1186 //Query the Policy Entity with oldPolicy Name
1187 policyEntityquery = "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0";
1188 SimpleBindings peParams = new SimpleBindings();
1189 peParams.put("oldPolicySplit_1", oldPolicySplit[1]);
1190 peParams.put("oldPolicySplit_0", oldPolicySplit[0]);
1191 if(PolicyController.isjUnit()){
1192 queryData = controller.getDataByQuery(policyEntityquery, null);
1194 queryData = controller.getDataByQuery(policyEntityquery, peParams);
1196 if(!queryData.isEmpty()){
1197 entity = (PolicyEntity) queryData.get(0);
1200 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId);
1205 PolicyVersion entityItem = new PolicyVersion();
1206 entityItem.setActiveVersion(Integer.parseInt(version));
1207 entityItem.setHigherVersion(Integer.parseInt(version));
1208 entityItem.setPolicyName(policyName);
1209 entityItem.setCreatedBy(userId);
1210 entityItem.setModifiedBy(userId);
1211 entityItem.setModifiedDate(new Date());
1212 controller.saveData(entityItem);
1215 LOGGER.debug("copy from: {} to: {}" + oldPath +newPath);
1218 } catch (Exception e) {
1219 LOGGER.error("copy", e);
1220 return error(e.getMessage());
1224 //Delete Policy or Scope Functionality
1225 private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
1226 PolicyController controller = getPolicyControllerInstance();
1227 PolicyRestController restController = new PolicyRestController();
1228 PolicyEntity policyEntity = null;
1229 String policyNamewithoutExtension;
1231 String userId = UserUtils.getUserSession(request).getOrgUserId();
1232 String deleteVersion = "";
1233 String path = params.getString("path");
1234 LOGGER.debug("delete {}" +path);
1235 if(params.has("deleteVersion")){
1236 deleteVersion = params.getString("deleteVersion");
1238 path = path.substring(path.indexOf('/')+1);
1239 String policyNamewithExtension = path.replace(FORWARD_SLASH, File.separator);
1240 String policyVersionName = policyNamewithExtension.replace(".xml", "");
1242 SimpleBindings policyParams = new SimpleBindings();
1243 if(path.endsWith(".xml")){
1244 policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf('.'));
1245 String[] split = modifyPolicyName(File.separator, policyNamewithoutExtension);
1246 query = "FROM PolicyEntity where policyName like :split_1 and scope = :split_0";
1247 policyParams.put(SPLIT_1, split[1] + "%");
1248 policyParams.put(SPLIT_0, split[0]);
1250 policyNamewithoutExtension = path.replace(File.separator, ".");
1251 query = "FROM PolicyEntity where scope like :policyNamewithoutExtension";
1252 policyParams.put("policyNamewithoutExtension", policyNamewithoutExtension + "%");
1255 List<Object> policyEntityobjects = controller.getDataByQuery(query, policyParams);
1256 String activePolicyName = null;
1257 boolean pdpCheck = false;
1258 if(path.endsWith(".xml")){
1259 policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator);
1260 int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf('.')+1));
1261 if("ALL".equals(deleteVersion)){
1262 if(!policyEntityobjects.isEmpty()){
1263 for(Object object : policyEntityobjects){
1264 policyEntity = (PolicyEntity) object;
1265 String groupEntityquery = "from PolicyGroupEntity where policyid ='"+policyEntity.getPolicyId()+"'";
1266 SimpleBindings pgeParams = new SimpleBindings();
1267 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, pgeParams);
1268 if(!groupobject.isEmpty()){
1270 activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName();
1272 //Delete the entity from Elastic Search Database
1273 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1274 restController.deleteElasticData(searchFileName);
1275 //Delete the entity from Policy Entity table
1276 controller.deleteData(policyEntity);
1277 if(policyNamewithoutExtension.contains(CONFIG2)){
1278 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1279 controller.deleteData(policyEntity.getConfigurationData());
1280 restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, policyEntity.getConfigurationData().getConfigurationName());
1281 }else if(policyNamewithoutExtension.contains(ACTION2)){
1282 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1283 controller.deleteData(policyEntity.getActionBodyEntity());
1284 restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, policyEntity.getActionBodyEntity().getActionBodyName());
1289 //Policy Notification
1290 PolicyVersion versionEntity = new PolicyVersion();
1291 versionEntity.setPolicyName(policyNamewithoutExtension);
1292 versionEntity.setModifiedBy(userId);
1293 controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll");
1295 //Delete from policyVersion table
1296 String getActivePDPPolicyVersion = activePolicyName.replace(".xml", "");
1297 getActivePDPPolicyVersion = getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf('.')+1);
1298 String policyVersionQuery = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION +getActivePDPPolicyVersion+"' , highest_version='"+getActivePDPPolicyVersion+"' where policy_name ='" +policyNamewithoutExtension.replace(BACKSLASH, ESCAPE_BACKSLASH)+"' and id >0";
1299 controller.executeQuery(policyVersionQuery);
1300 return error("Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "+activePolicyName);
1302 //No Active Policy in PDP. So, deleting all entries from policyVersion table
1303 String policyVersionQuery = DELETE_POLICY_VERSION_WHERE_POLICY_NAME +policyNamewithoutExtension.replace(BACKSLASH, ESCAPE_BACKSLASH)+"' and id >0";
1304 controller.executeQuery(policyVersionQuery);
1306 }else if("CURRENT".equals(deleteVersion)){
1307 String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1);
1308 String currentVersionScope = policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator)).replace(File.separator, ".");
1309 query = "FROM PolicyEntity where policyName = :currentVersionPolicyName and scope = :currentVersionScope";
1311 SimpleBindings peParams = new SimpleBindings();
1312 peParams.put("currentVersionPolicyName", currentVersionPolicyName);
1313 peParams.put("currentVersionScope", currentVersionScope);
1315 List<Object> policyEntitys = controller.getDataByQuery(query, peParams);
1316 if(!policyEntitys.isEmpty()){
1317 policyEntity = (PolicyEntity) policyEntitys.get(0);
1319 if(policyEntity == null){
1323 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId and policyid > 0";
1324 SimpleBindings geParams = new SimpleBindings();
1325 geParams.put("policyEntityId", policyEntity.getPolicyId());
1326 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1327 if(!groupobject.isEmpty()){
1328 return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'");
1331 //Delete the entity from Elastic Search Database
1332 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1333 restController.deleteElasticData(searchFileName);
1334 //Delete the entity from Policy Entity table
1335 controller.deleteData(policyEntity);
1336 if(policyNamewithoutExtension.contains(CONFIG2)){
1337 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1338 controller.deleteData(policyEntity.getConfigurationData());
1339 restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, policyEntity.getConfigurationData().getConfigurationName());
1340 }else if(policyNamewithoutExtension.contains(ACTION2)){
1341 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1342 controller.deleteData(policyEntity.getActionBodyEntity());
1343 restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, policyEntity.getActionBodyEntity().getActionBodyName());
1347 int highestVersion = 0;
1348 if(!policyEntityobjects.isEmpty()){
1349 for(Object object : policyEntityobjects){
1350 policyEntity = (PolicyEntity) object;
1351 String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
1352 int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf('.')+1));
1353 if(policyEntityVersion > highestVersion && policyEntityVersion != version){
1354 highestVersion = policyEntityVersion;
1359 //Policy Notification
1360 PolicyVersion entity = new PolicyVersion();
1361 entity.setPolicyName(policyNamewithoutExtension);
1362 entity.setActiveVersion(highestVersion);
1363 entity.setModifiedBy(userId);
1364 controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne");
1367 if(highestVersion != 0){
1368 updatequery = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION +highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"'";
1370 updatequery = DELETE_POLICY_VERSION_WHERE_POLICY_NAME +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1372 controller.executeQuery(updatequery);
1374 String policyVersionQuery = DELETE_POLICY_VERSION_WHERE_POLICY_NAME +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1375 controller.executeQuery(policyVersionQuery);
1379 List<String> activePoliciesInPDP = new ArrayList<>();
1380 if(policyEntityobjects.isEmpty()){
1381 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace(BACKSLASH, ESCAPE_BACKSLASH)+PERCENT_AND_ID_GT_0;
1382 controller.executeQuery(policyScopeQuery);
1385 for(Object object : policyEntityobjects){
1386 policyEntity = (PolicyEntity) object;
1387 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId";
1388 SimpleBindings geParams = new SimpleBindings();
1389 geParams.put("policyEntityId", policyEntity.getPolicyId());
1390 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1391 if(!groupobject.isEmpty()){
1393 activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName());
1395 //Delete the entity from Elastic Search Database
1396 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1397 restController.deleteElasticData(searchFileName);
1398 //Delete the entity from Policy Entity table
1399 controller.deleteData(policyEntity);
1400 policyNamewithoutExtension = policyEntity.getPolicyName();
1401 if(policyNamewithoutExtension.contains(CONFIG2)){
1402 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1403 controller.deleteData(policyEntity.getConfigurationData());
1404 restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, policyEntity.getConfigurationData().getConfigurationName());
1405 }else if(policyNamewithoutExtension.contains(ACTION2)){
1406 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1407 controller.deleteData(policyEntity.getActionBodyEntity());
1408 restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, policyEntity.getActionBodyEntity().getActionBodyName());
1412 //Delete from policyVersion and policyEditor Scope table
1413 String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace(BACKSLASH, ESCAPE_BACKSLASH)+PERCENT_AND_ID_GT_0;
1414 controller.executeQuery(policyVersionQuery);
1416 //Policy Notification
1417 PolicyVersion entity = new PolicyVersion();
1418 entity.setPolicyName(path);
1419 entity.setModifiedBy(userId);
1420 controller.watchPolicyFunction(entity, path, "DeleteScope");
1422 //Add Active Policies List to PolicyVersionTable
1423 for (String anActivePoliciesInPDP : activePoliciesInPDP) {
1424 String activePDPPolicyName = anActivePoliciesInPDP.replace(".xml", "");
1425 int activePDPPolicyVersion = Integer.parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf('.') + 1));
1426 activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf('.')).replace(".", File.separator);
1427 PolicyVersion insertactivePDPVersion = new PolicyVersion();
1428 insertactivePDPVersion.setPolicyName(activePDPPolicyName);
1429 insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion);
1430 insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion);
1431 insertactivePDPVersion.setCreatedBy(userId);
1432 insertactivePDPVersion.setModifiedBy(userId);
1433 controller.saveData(insertactivePDPVersion);
1436 return error("All the Policies has been deleted in Scope. Except the following list of Policies:"+activePoliciesInPDP);
1438 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace(BACKSLASH, ESCAPE_BACKSLASH)+PERCENT_AND_ID_GT_0;
1439 controller.executeQuery(policyScopeQuery);
1444 } catch (Exception e) {
1445 LOGGER.error(DELETE, e);
1446 return error(e.getMessage());
1451 private JSONObject editFile(JSONObject params) throws ServletException {
1454 PolicyController controller = getPolicyControllerInstance();
1455 String mode = params.getString("mode");
1456 String path = params.getString("path");
1457 LOGGER.debug("editFile path: {}"+ path);
1459 String domain = path.substring(1, path.lastIndexOf('/'));
1460 domain = domain.replace(FORWARD_SLASH, ".");
1462 path = path.substring(1);
1463 path = path.replace(FORWARD_SLASH, ".");
1465 String[] split = modifyPolicyName(path);
1467 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
1468 SimpleBindings peParams = new SimpleBindings();
1469 peParams.put(SPLIT_1, split[1]);
1470 peParams.put(SPLIT_0, split[0]);
1471 List<Object> queryData;
1472 if(PolicyController.isjUnit()){
1473 queryData = controller.getDataByQuery(query, null);
1475 queryData = controller.getDataByQuery(query, peParams);
1477 PolicyEntity entity = (PolicyEntity) queryData.get(0);
1478 InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
1481 Object policy = XACMLPolicyScanner.readPolicy(stream);
1482 PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
1483 policyAdapter.setData(policy);
1485 if("viewPolicy".equalsIgnoreCase(mode)){
1486 policyAdapter.setReadOnly(true);
1487 policyAdapter.setEditPolicy(false);
1489 policyAdapter.setReadOnly(false);
1490 policyAdapter.setEditPolicy(true);
1493 policyAdapter.setDomainDir(domain);
1494 policyAdapter.setPolicyData(policy);
1495 String policyName = path.replace(".xml", "");
1496 policyName = policyName.substring(0, policyName.lastIndexOf('.'));
1497 policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf('.')+1));
1499 PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance();
1500 Objects.requireNonNull(setpolicyAdapter).configure(policyAdapter,entity);
1502 policyAdapter.setParentPath(null);
1503 ObjectMapper mapper = new ObjectMapper();
1504 String json = mapper.writeValueAsString(policyAdapter);
1505 JsonNode jsonNode = mapper.readTree(json);
1507 return new JSONObject().put(RESULT, jsonNode);
1508 } catch (Exception e) {
1509 LOGGER.error("editFile", e);
1510 return error(e.getMessage());
1515 private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
1516 PolicyController controller = getPolicyControllerInstance();
1519 String userId = UserUtils.getUserSession(request).getOrgUserId();
1520 String path = params.getString("path");
1522 if(params.has(SUB_SCOPENAME)){
1523 if(! "".equals(params.getString(SUB_SCOPENAME))) {
1524 name = params.getString("path").replace(FORWARD_SLASH, File.separator) + File.separator +params.getString(SUB_SCOPENAME);
1527 name = params.getString(NAME);
1529 }catch(Exception e){
1530 name = params.getString(NAME);
1531 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e);
1533 String validateName;
1534 if(name.contains(File.separator)){
1535 validateName = name.substring(name.lastIndexOf(File.separator)+1);
1537 validateName = name;
1539 if(!name.isEmpty()){
1540 String validate = PolicyUtils.policySpecialCharValidator(validateName);
1541 if(!validate.contains(SUCCESS)){
1542 return error(validate);
1545 LOGGER.debug("addFolder path: {} name: {}" + path +name);
1546 if(! "".equals(name)){
1547 if(name.startsWith(File.separator)){
1548 name = name.substring(1);
1550 PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, SCOPE_NAME, name);
1552 UserInfo userInfo = new UserInfo();
1553 userInfo.setUserLoginId(userId);
1554 PolicyEditorScopes newScope = new PolicyEditorScopes();
1555 newScope.setScopeName(name);
1556 newScope.setUserCreatedBy(userInfo);
1557 newScope.setUserModifiedBy(userInfo);
1558 controller.saveData(newScope);
1560 return error("Scope Already Exists");
1564 } catch (Exception e) {
1565 LOGGER.error("addFolder", e);
1566 return error(e.getMessage());
1570 //Return Error Object
1571 private JSONObject error(String msg) throws ServletException {
1573 JSONObject result = new JSONObject();
1574 result.put(SUCCESS, false);
1575 result.put("error", msg);
1576 return new JSONObject().put(RESULT, result);
1577 } catch (JSONException e) {
1578 throw new ServletException(e);
1582 //Return Success Object
1583 private JSONObject success() throws ServletException {
1585 JSONObject result = new JSONObject();
1586 result.put(SUCCESS, true);
1587 result.put("error", (Object) null);
1588 return new JSONObject().put(RESULT, result);
1589 } catch (JSONException e) {
1590 throw new ServletException(e);
1594 private PolicyController getPolicyControllerInstance(){
1595 return policyController != null ? getPolicyController() : new PolicyController();
1598 private String getTestUserId() {
1602 public static void setTestUserId(String testUserId) {
1603 PolicyManagerServlet.testUserId = testUserId;