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 EXCEPTION_OCCURED = "Exception Occured";
106 private static final String CONFIG = ".Config_";
107 private static final String CONFIG1 = ":Config_";
108 private static final String ACTION = ".Action_";
109 private static final String ACTION1 = ":Action_";
110 private static final String DECISION = ".Decision_";
111 private static final String DECISION1 = ":Decision_";
112 private static final String CONFIG2 = "Config_";
113 private static final String ACTION2 = "Action_";
114 private static final String DECISION2 = "Decision_";
115 private static final String FORWARD_SLASH = "/";
116 private static final String BACKSLASH = "\\";
117 private static final String ESCAPE_BACKSLASH = "\\\\";
118 private static final String BACKSLASH_8TIMES = "\\\\\\\\";
119 private static final String UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION = "update PolicyVersion set active_version='";
120 private static final String SPLIT_1 = "split_1";
121 private static final String SPLIT_0 = "split_0";
122 private static final String FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME = "from PolicyEditorScopes where SCOPENAME like :scopeName";
123 private static final String SCOPE_NAME = "scopeName";
124 private static final String SUCCESS = "success";
125 private static final String SUB_SCOPENAME = "subScopename";
126 private static List<String> serviceTypeNamesList = new ArrayList<>();
127 private static JsonArray policyNames;
128 private static String testUserId = null;
131 LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT, SEARCHLIST
134 private static PolicyController policyController;
135 private synchronized PolicyController getPolicyController() {
136 return policyController;
139 public static synchronized void setPolicyController(PolicyController policyController) {
140 PolicyManagerServlet.policyController = policyController;
143 public static JsonArray getPolicyNames() {
147 public static void setPolicyNames(JsonArray policyNames) {
148 PolicyManagerServlet.policyNames = policyNames;
151 public static List<String> getServiceTypeNamesList() {
152 return serviceTypeNamesList;
156 public void init(ServletConfig servletConfig) throws ServletException {
157 super.init(servletConfig);
159 // Common initialization
161 XACMLRest.xacmlInit(servletConfig);
163 //Initialize ClosedLoop JSON
165 PolicyManagerServlet.initializeJSONLoad();
168 private static void initializeJSONLoad() {
169 Path closedLoopJsonLocation = Paths.get(XACMLProperties
170 .getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP));
171 String location = closedLoopJsonLocation.toString();
172 if (! location.endsWith("json")) {
173 LOGGER.warn("JSONConfig file does not end with extension .json");
176 try (FileInputStream inputStream = new FileInputStream(location);
177 JsonReader jsonReader = Json.createReader(inputStream)) {
178 policyNames = jsonReader.readArray();
179 serviceTypeNamesList = new ArrayList<>();
180 for (int i = 0; i < policyNames.size(); i++) {
181 javax.json.JsonObject policyName = policyNames.getJsonObject(i);
182 String name = policyName.getJsonString("serviceTypePolicyName").getString();
183 serviceTypeNamesList.add(name);
185 } catch (IOException e) {
186 LOGGER.error("Exception Occured while initializing the JSONConfig file"+e);
191 protected void doPost(HttpServletRequest request, HttpServletResponse response) {
192 LOGGER.debug("doPost");
194 // if request contains multipart-form-data
195 if (ServletFileUpload.isMultipartContent(request)) {
196 uploadFile(request, response);
198 // all other post request has json params in body
200 fileOperation(request, response);
202 } catch (Exception e) {
204 setError(e, response);
205 }catch(Exception e1){
206 LOGGER.error(EXCEPTION_OCCURED +e1);
211 //Set Error Message for Exception
212 private void setError(Exception t, HttpServletResponse response) throws IOException {
214 JSONObject responseJsonObject = error(t.getMessage());
215 response.setContentType(CONTENTTYPE);
216 PrintWriter out = response.getWriter();
217 out.print(responseJsonObject);
219 } catch (Exception x) {
220 LOGGER.error(EXCEPTION_OCCURED +x);
221 response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage());
225 //Policy Import Functionality
226 private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException {
228 Map<String, InputStream> files = new HashMap<>();
230 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
231 for (FileItem item : items) {
232 if (!item.isFormField()) {
233 // Process form file field (input type="file").
234 files.put(item.getName(), item.getInputStream());
235 processFormFile(request, item);
239 JSONObject responseJsonObject;
240 responseJsonObject = this.success();
241 response.setContentType(CONTENTTYPE);
242 PrintWriter out = response.getWriter();
243 out.print(responseJsonObject);
245 } catch (Exception e) {
246 LOGGER.debug("Cannot write file");
247 throw new ServletException("Cannot write file", e);
251 private void processFormFile(HttpServletRequest request, FileItem item) {
253 if(item.getName().endsWith(".xls") && item.getSize() <= PolicyController.getFileSizeLimit()){
254 File file = new File(item.getName());
255 try (OutputStream outputStream = new FileOutputStream(file))
257 IOUtils.copy(item.getInputStream(), outputStream);
258 newFile = file.toString();
259 PolicyExportAndImportController importController = new PolicyExportAndImportController();
260 importController.importRepositoryFile(newFile, request);
262 LOGGER.error("Upload error : " + e);
265 else if (!item.getName().endsWith(".xls")) {
266 LOGGER.error("Non .xls filetype uploaded: " + item.getName());
268 else { //uploaded file size is greater than allowed
269 LOGGER.error("Upload file size limit exceeded! File size (Bytes) is: " + item.getSize());
273 //File Operation Functionality
274 private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException {
275 JSONObject responseJsonObject;
276 StringBuilder sb = new StringBuilder();
277 try (BufferedReader br = request.getReader()) {
279 while ((str = br.readLine()) != null) {
282 } catch (Exception e) {
283 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While doing File Operation" + e);
284 responseJsonObject = error(e.getMessage());
285 setResponse(response, responseJsonObject);
289 JSONObject jObj = new JSONObject(sb.toString());
290 JSONObject params = jObj.getJSONObject("params");
291 Mode mode = Mode.valueOf(params.getString("mode"));
293 String userId = UserUtils.getUserSession(request).getOrgUserId();
294 LOGGER.info("****************************************Logging UserID while doing actions on Editor tab*******************************************");
295 LOGGER.info("UserId: " + userId + "Action Mode: "+ mode.toString() + "Action Params: "+params.toString());
296 LOGGER.info("***********************************************************************************************************************************");
297 responseJsonObject = operateBasedOnMode(mode, params, request);
298 } catch (Exception e) {
299 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Processing Json" + e);
300 responseJsonObject = error(e.getMessage());
302 setResponse(response, responseJsonObject);
305 private void setResponse(HttpServletResponse response, JSONObject responseJsonObject) {
306 response.setContentType(CONTENTTYPE);
307 try (PrintWriter out = response.getWriter()) {
308 out.print(responseJsonObject);
310 } catch (IOException e) {
311 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception occured while writing response" + e);
316 private JSONObject operateBasedOnMode(Mode mode, JSONObject params, HttpServletRequest request) throws ServletException{
317 JSONObject responseJsonObject;
321 responseJsonObject = addFolder(params, request);
324 responseJsonObject = copy(params, request);
327 responseJsonObject = delete(params, request);
331 responseJsonObject = editFile(params);
334 responseJsonObject = list(params, request);
337 responseJsonObject = rename(params, request);
339 case DESCRIBEPOLICYFILE:
340 responseJsonObject = describePolicy(params);
343 responseJsonObject = switchVersion(params, request);
346 responseJsonObject = searchPolicyList(params, request);
349 throw new ServletException("not implemented");
351 if (responseJsonObject == null) {
352 responseJsonObject = error("generic error : responseJsonObject is null");
354 return responseJsonObject;
358 private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) {
359 List<Object> policyData = new ArrayList<>();
360 JSONArray policyList = null;
361 if(params.has("policyList")){
362 policyList = (JSONArray) params.get("policyList");
364 PolicyController controller = getPolicyControllerInstance();
365 List<JSONObject> resultList = new ArrayList<>();
367 if (!lookupPolicyData(request, policyData, policyList, controller, resultList))
368 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
371 LOGGER.error("Exception occured while reading policy Data from Policy Version table for Policy Search Data"+e);
374 return new JSONObject().put(RESULT, resultList);
377 private boolean lookupPolicyData(HttpServletRequest request, List<Object> policyData, JSONArray policyList, PolicyController controller, List<JSONObject> resultList){
379 Set<String> scopes;//Get the Login Id of the User from Request
380 String userId = UserUtils.getUserSession(request).getOrgUserId();
381 List<Object> userRoles = controller.getRoles(userId);
382 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
385 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
386 if(scopes.isEmpty()){
389 Set<String> tempScopes = scopes;
390 for(String scope : tempScopes){
391 addScope(scopes, scope);
394 if(policyList!= null){
395 for(int i = 0; i < policyList.length(); i++){
396 String policyName = policyList.get(i).toString().replace(".xml", "");
397 String version = policyName.substring(policyName.lastIndexOf('.')+1);
398 policyName = policyName.substring(0, policyName.lastIndexOf('.')).replace(".", File.separator);
399 parsePolicyList(resultList, controller, policyName, version);
402 getPolicyDataForSUPERRoles(policyData, controller, resultList, roles, scopes);
407 private void getPolicyDataForSUPERRoles(List<Object> policyData, PolicyController controller, List<JSONObject> resultList, List<String> roles, Set<String> scopes) {
408 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ){
409 policyData = controller.getData(PolicyVersion.class);
411 List<Object> filterdatas = controller.getData(PolicyVersion.class);
412 for(Object filter : filterdatas) {
413 addFilterData(policyData, scopes, (PolicyVersion) filter);
417 if(!policyData.isEmpty()){
418 updateResultList(policyData, resultList);
422 private void addFilterData(List<Object> policyData, Set<String> scopes, PolicyVersion filter) {
424 String scopeName = filter.getPolicyName().substring(0, filter.getPolicyName().lastIndexOf(File.separator));
425 if(scopes.contains(scopeName)){
426 policyData.add(filter);
429 LOGGER.error("Exception occured while filtering policyversion data"+e);
433 private void updateResultList(List<Object> policyData, List<JSONObject> resultList) {
434 for (Object aPolicyData : policyData) {
435 PolicyVersion policy = (PolicyVersion) aPolicyData;
436 JSONObject el = new JSONObject();
437 el.put(NAME, policy.getPolicyName().replace(File.separator, FORWARD_SLASH));
438 el.put(DATE, policy.getModifiedDate());
439 el.put(VERSION, policy.getActiveVersion());
441 el.put(TYPE, "file");
442 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
443 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
448 private void parsePolicyList(List<JSONObject> resultList, PolicyController controller, String policyName, String version) {
449 if(policyName.contains(BACKSLASH)){
450 policyName = policyName.replace(BACKSLASH, ESCAPE_BACKSLASH);
452 String policyVersionQuery = "From PolicyVersion where policy_name = :policyName and active_version = :version and id >0";
453 SimpleBindings pvParams = new SimpleBindings();
454 pvParams.put("policyName", policyName);
455 pvParams.put(VERSION, version);
456 List<Object> activeData = controller.getDataByQuery(policyVersionQuery, pvParams);
457 if(!activeData.isEmpty()){
458 PolicyVersion policy = (PolicyVersion) activeData.get(0);
459 JSONObject el = new JSONObject();
460 el.put(NAME, policy.getPolicyName().replace(File.separator, FORWARD_SLASH));
461 el.put(DATE, policy.getModifiedDate());
462 el.put(VERSION, policy.getActiveVersion());
464 el.put(TYPE, "file");
465 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
466 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
471 private void addScope(Set<String> scopes, String scope) {
472 List<Object> scopesList = queryPolicyEditorScopes(scope);
473 if(!scopesList.isEmpty()){
474 for (Object aScopesList : scopesList) {
475 PolicyEditorScopes tempScope = (PolicyEditorScopes) aScopesList;
476 scopes.add(tempScope.getScopeName());
481 //Switch Version Functionality
482 private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{
483 String path = params.getString("path");
484 String userId = null;
486 userId = UserUtils.getUserSession(request).getOrgUserId();
487 } catch (Exception e) {
488 LOGGER.error("Exception Occured while reading userid from cookie" +e);
491 String removeExtension = path.replace(".xml", "");
492 if(path.startsWith(FORWARD_SLASH)){
493 policyName = removeExtension.substring(1, removeExtension.lastIndexOf('.'));
495 policyName = removeExtension.substring(0, removeExtension.lastIndexOf('.'));
499 PolicyController controller = getPolicyControllerInstance();
500 if(! params.toString().contains("activeVersion")){
501 return controller.switchVersionPolicyContent(policyName);
503 String activeVersion = params.getString("activeVersion");
504 String highestVersion = params.get("highestVersion").toString();
505 if(Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)){
506 return error("The Version shouldn't be greater than Highest Value");
508 activePolicy = policyName + "." + activeVersion + ".xml";
509 String[] splitDBCheckName = modifyPolicyName(activePolicy);
510 String peQuery = "FROM PolicyEntity where policyName = :splitDBCheckName_1 and scope = :splitDBCheckName_0";
511 SimpleBindings policyParams = new SimpleBindings();
512 policyParams.put("splitDBCheckName_1", splitDBCheckName[1]);
513 policyParams.put("splitDBCheckName_0", splitDBCheckName[0]);
514 List<Object> policyEntity = controller.getDataByQuery(peQuery, policyParams);
515 PolicyEntity pentity = (PolicyEntity) policyEntity.get(0);
516 if(pentity.isDeleted()){
517 return error("The Policy is Not Existing in Workspace");
519 if(policyName.contains(FORWARD_SLASH)){
520 policyName = policyName.replace(FORWARD_SLASH, File.separator);
522 policyName = policyName.substring(policyName.indexOf(File.separator)+1);
523 if(policyName.contains(BACKSLASH)){
524 policyName = policyName.replace(File.separator, BACKSLASH);
526 policyName = splitDBCheckName[0].replace(".", File.separator)+File.separator+policyName;
527 String watchPolicyName = policyName;
528 if(policyName.contains(FORWARD_SLASH)){
529 policyName = policyName.replace(FORWARD_SLASH, File.separator);
531 if(policyName.contains(BACKSLASH)){
532 policyName = policyName.replace(BACKSLASH, ESCAPE_BACKSLASH);
534 String query = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION +activeVersion+"' where policy_name ='"+policyName+"' and id >0";
536 controller.executeQuery(query);
537 //Policy Notification
538 PolicyVersion entity = new PolicyVersion();
539 entity.setPolicyName(watchPolicyName);
540 entity.setActiveVersion(Integer.parseInt(activeVersion));
541 entity.setModifiedBy(userId);
542 controller.watchPolicyFunction(entity, activePolicy, "SwitchVersion");
547 private JSONObject describePolicy(JSONObject params) throws ServletException{
549 String path = params.getString("path");
551 if(path.startsWith(FORWARD_SLASH)){
552 path = path.substring(1);
553 policyName = path.substring(path.lastIndexOf('/') +1);
554 path = path.replace(FORWARD_SLASH, ".");
556 path = path.replace(FORWARD_SLASH, ".");
559 if(path.contains(CONFIG2)){
560 path = path.replace(CONFIG, CONFIG1);
561 }else if(path.contains(ACTION2)){
562 path = path.replace(ACTION, ACTION1);
563 }else if(path.contains(DECISION2)){
564 path = path.replace(DECISION, DECISION1);
566 PolicyController controller = getPolicyControllerInstance();
567 String[] split = path.split(":");
568 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
569 SimpleBindings peParams = new SimpleBindings();
570 peParams.put(SPLIT_1, split[1]);
571 peParams.put(SPLIT_0, split[0]);
572 List<Object> queryData;
573 if(PolicyController.isjUnit()){
574 queryData = controller.getDataByQuery(query, null);
576 queryData = controller.getDataByQuery(query, peParams);
578 if(queryData.isEmpty()){
579 return error("Error Occured while Describing the Policy - query is empty");
581 PolicyEntity entity = (PolicyEntity) queryData.get(0);
584 temp = File.createTempFile(policyName, ".tmp");
585 } catch (IOException e) {
586 String message = "Failed to create temp file " + policyName + ".tmp";
587 LOGGER.error(message + e);
588 return error(message);
590 try (BufferedWriter bw = new BufferedWriter(new FileWriter(temp))) {
591 bw.write(entity.getPolicyData());
592 } catch (IOException e) {
593 LOGGER.error("Exception Occured while Describing the Policy"+e);
595 object = HumanPolicyComponent.DescribePolicy(temp);
597 Files.delete(temp.toPath());
598 } catch (IOException e) {
599 LOGGER.warn("Failed to delete " + temp.getName() + e);
604 //Get the List of Policies and Scopes for Showing in Editor tab
605 private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException {
607 return processPolicyList(params, request);
608 } catch (Exception e) {
609 LOGGER.error("list", e);
610 return error(e.getMessage());
614 private JSONObject processPolicyList(JSONObject params, HttpServletRequest request) throws ServletException {
615 PolicyController controller = getPolicyControllerInstance();
616 //Get the Login Id of the User from Request
617 String testUserID = getTestUserId();
618 String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId();
619 List<Object> userRoles = controller.getRoles(userId);
620 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
621 List<String> roles = pair.u;
622 Set<String> scopes = pair.t;
624 List<JSONObject> resultList = new ArrayList<>();
625 boolean onlyFolders = params.getBoolean("onlyFolders");
626 String path = params.getString("path");
627 if(path.contains("..xml")){
628 path = path.replaceAll("..xml", "").trim();
631 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
632 if(scopes.isEmpty()){
633 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
635 if(!FORWARD_SLASH.equals(path)){
636 String tempScope = path.substring(1, path.length());
637 tempScope = tempScope.replace(FORWARD_SLASH, File.separator);
638 scopes.add(tempScope);
643 if (!FORWARD_SLASH.equals(path)) {
645 String scopeName = path.substring(path.indexOf('/') +1);
646 activePolicyList(scopeName, resultList, roles, scopes, onlyFolders);
647 } catch (Exception ex) {
648 LOGGER.error("Error Occured While reading Policy Files List"+ex );
650 return new JSONObject().put(RESULT, resultList);
653 processRoles(scopes, roles, resultList);
655 return new JSONObject().put(RESULT, resultList);
658 private void processRoles(Set<String> scopes, List<String> roles, List<JSONObject> resultList) {
659 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
660 List<Object> scopesList = queryPolicyEditorScopes(null);
661 for(Object list : scopesList){
662 PolicyEditorScopes scope = (PolicyEditorScopes) list;
663 if(!(scope.getScopeName().contains(File.separator))){
664 JSONObject el = new JSONObject();
665 el.put(NAME, scope.getScopeName());
666 el.put(DATE, scope.getModifiedDate());
669 el.put(CREATED_BY, scope.getUserCreatedBy().getUserName());
670 el.put(MODIFIED_BY, scope.getUserModifiedBy().getUserName());
674 }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){
675 for(Object scope : scopes){
676 JSONObject el = new JSONObject();
677 List<Object> scopesList = queryPolicyEditorScopes(scope.toString());
678 if(!scopesList.isEmpty()){
679 PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
680 el.put(NAME, scopeById.getScopeName());
681 el.put(DATE, scopeById.getModifiedDate());
684 el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName());
685 el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName());
692 private List<Object> queryPolicyEditorScopes(String scopeName){
693 String scopeNamequery;
694 SimpleBindings params = new SimpleBindings();
695 if(scopeName == null){
696 scopeNamequery = "from PolicyEditorScopes";
698 scopeNamequery = FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME;
699 params.put(SCOPE_NAME, scopeName + "%");
701 PolicyController controller = getPolicyControllerInstance();
702 List<Object> scopesList;
703 if(PolicyController.isjUnit()){
704 scopesList = controller.getDataByQuery(scopeNamequery, null);
706 scopesList = controller.getDataByQuery(scopeNamequery, params);
711 //Get Active Policy List based on Scope Selection form Policy Version table
712 private void activePolicyList(String inScopeName, List<JSONObject> resultList, List<String> roles, Set<String> scopes, boolean onlyFolders){
713 PolicyController controller = getPolicyControllerInstance();
714 String scopeName = inScopeName;
715 if(scopeName.contains(FORWARD_SLASH)){
716 scopeName = scopeName.replace(FORWARD_SLASH, File.separator);
718 if(scopeName.contains(BACKSLASH)){
719 scopeName = scopeName.replace(BACKSLASH, ESCAPE_BACKSLASH);
721 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
722 String scopeNamequery = FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME;
724 SimpleBindings params = new SimpleBindings();
725 params.put(SCOPE_NAME, scopeName + "%");
727 List<Object> activePolicies;
728 List<Object> scopesList;
729 if(PolicyController.isjUnit()){
730 activePolicies = controller.getDataByQuery(query, null);
731 scopesList = controller.getDataByQuery(scopeNamequery, null);
733 activePolicies = controller.getDataByQuery(query, params);
734 scopesList = controller.getDataByQuery(scopeNamequery, params);
736 for(Object list : scopesList) {
737 scopeName = checkScope(resultList, scopeName, (PolicyEditorScopes) list);
739 String scopeNameCheck;
740 for (Object list : activePolicies) {
741 PolicyVersion policy = (PolicyVersion) list;
742 String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator));
743 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
744 if(scopeName.contains(ESCAPE_BACKSLASH)){
745 scopeNameCheck = scopeName.replace(ESCAPE_BACKSLASH, File.separator);
747 scopeNameCheck = scopeName;
749 if(scopeNameValue.equals(scopeNameCheck)){
750 JSONObject el = new JSONObject();
751 el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
752 el.put(DATE, policy.getModifiedDate());
753 el.put(VERSION, policy.getActiveVersion());
755 el.put(TYPE, "file");
756 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
757 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
760 }else if(!scopes.isEmpty() && scopes.contains(scopeNameValue)){
761 JSONObject el = new JSONObject();
762 el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
763 el.put(DATE, policy.getModifiedDate());
764 el.put(VERSION, policy.getActiveVersion());
766 el.put(TYPE, "file");
767 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
768 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
774 private String checkScope(List<JSONObject> resultList, String scopeName, PolicyEditorScopes scopeById) {
775 String scope = scopeById.getScopeName();
776 if(scope.contains(File.separator)){
777 String targetScope = scope.substring(0, scope.lastIndexOf(File.separator));
778 if(scopeName.contains(ESCAPE_BACKSLASH)){
779 scopeName = scopeName.replace(ESCAPE_BACKSLASH, File.separator);
781 if(scope.contains(File.separator)){
782 scope = scope.substring(targetScope.length()+1);
783 if(scope.contains(File.separator)){
784 scope = scope.substring(0, scope.indexOf(File.separator));
787 if(scopeName.equalsIgnoreCase(targetScope)){
788 JSONObject el = new JSONObject();
790 el.put(DATE, scopeById.getModifiedDate());
793 el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName());
794 el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName());
801 private String getUserName(String loginId){
802 PolicyController controller = getPolicyControllerInstance();
803 UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
804 if(userInfo == null){
807 return userInfo.getUserName();
811 private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
813 return handlePolicyRename(params, request);
814 } catch (Exception e) {
815 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
816 return error(e.getMessage());
820 private JSONObject handlePolicyRename(JSONObject params, HttpServletRequest request) throws ServletException {
821 boolean isActive = false;
822 List<String> policyActiveInPDP = new ArrayList<>();
823 Set<String> scopeOfPolicyActiveInPDP = new HashSet<>();
824 String userId = UserUtils.getUserSession(request).getOrgUserId();
825 String oldPath = params.getString("path");
826 String newPath = params.getString("newPath");
827 oldPath = oldPath.substring(oldPath.indexOf('/')+1);
828 newPath = newPath.substring(newPath.indexOf('/')+1);
829 String checkValidation;
830 if(oldPath.endsWith(".xml")){
831 checkValidation = newPath.replace(".xml", "");
832 checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf("."));
833 checkValidation = checkValidation.substring(checkValidation.lastIndexOf(FORWARD_SLASH)+1);
834 if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)){
835 return error("Policy Rename Failed. The Name contains special characters.");
837 JSONObject result = policyRename(oldPath, newPath, userId);
838 if(!(Boolean)(result.getJSONObject("result").get(SUCCESS))){
842 String scopeName = oldPath;
843 String newScopeName = newPath;
844 if(scopeName.contains(FORWARD_SLASH)){
845 scopeName = scopeName.replace(FORWARD_SLASH, File.separator);
846 newScopeName = newScopeName.replace(FORWARD_SLASH, File.separator);
848 checkValidation = newScopeName.substring(newScopeName.lastIndexOf(File.separator)+1);
849 if(scopeName.contains(BACKSLASH)){
850 scopeName = scopeName.replace(BACKSLASH, BACKSLASH_8TIMES);
851 newScopeName = newScopeName.replace(BACKSLASH, BACKSLASH_8TIMES);
853 if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)){
854 return error("Scope Rename Failed. The Name contains special characters.");
856 PolicyController controller = getPolicyControllerInstance();
857 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
858 String scopeNamequery = FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME;
859 SimpleBindings pvParams = new SimpleBindings();
860 pvParams.put(SCOPE_NAME, scopeName + "%");
861 List<Object> activePolicies = controller.getDataByQuery(query, pvParams);
862 List<Object> scopesList = controller.getDataByQuery(scopeNamequery, pvParams);
863 for(Object object : activePolicies){
864 PolicyVersion activeVersion = (PolicyVersion) object;
865 String policyOldPath = activeVersion.getPolicyName().replace(File.separator, FORWARD_SLASH) + "." + activeVersion.getActiveVersion() + ".xml";
866 String policyNewPath = policyOldPath.replace(oldPath, newPath);
867 JSONObject result = policyRename(policyOldPath, policyNewPath, userId);
868 if(!(Boolean)(result.getJSONObject("result").get(SUCCESS))){
870 policyActiveInPDP.add(policyOldPath);
871 String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf('/'));
872 scopeOfPolicyActiveInPDP.add(scope.replace(FORWARD_SLASH, File.separator));
875 boolean rename = false;
876 if(activePolicies.size() != policyActiveInPDP.size()){
880 UserInfo userInfo = new UserInfo();
881 userInfo.setUserLoginId(userId);
882 if(policyActiveInPDP.isEmpty()){
883 renameScope(scopesList, scopeName, newScopeName, controller);
885 renameScope(scopesList, scopeName, newScopeName, controller);
886 for(String scope : scopeOfPolicyActiveInPDP){
887 PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes();
888 editorScopeEntity.setScopeName(scope.replace(BACKSLASH, BACKSLASH_8TIMES));
889 editorScopeEntity.setUserCreatedBy(userInfo);
890 editorScopeEntity.setUserModifiedBy(userInfo);
891 controller.saveData(editorScopeEntity);
895 return error("The Following policies rename failed. Since they are active in PDP Groups" +policyActiveInPDP);
901 private void renameScope(List<Object> scopesList, String inScopeName, String newScopeName, PolicyController controller){
902 for(Object object : scopesList){
903 PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object;
904 String scopeName = inScopeName;
905 if(scopeName.contains(BACKSLASH_8TIMES)){
906 scopeName = scopeName.replace(BACKSLASH_8TIMES, File.separator);
907 newScopeName = newScopeName.replace(BACKSLASH_8TIMES, File.separator);
909 String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName);
910 editorScopeEntity.setScopeName(scope);
911 controller.updateData(editorScopeEntity);
915 private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
918 PolicyController controller = getPolicyControllerInstance();
920 String policyVersionName = newPath.replace(".xml", "");
921 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')).replace(FORWARD_SLASH, File.separator);
923 String oldpolicyVersionName = oldPath.replace(".xml", "");
924 String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf('.')).replace(FORWARD_SLASH, File.separator);
925 String newpolicyName = newPath.replace("/", ".");
926 String[] newPolicySplit = modifyPolicyName(newPath);
928 String[] oldPolicySplit = modifyPolicyName(oldPath);
930 //Check PolicyEntity table with newPolicy Name
931 String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
932 SimpleBindings policyParams = new SimpleBindings();
933 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
934 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
935 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
936 if(!queryData.isEmpty()){
937 return error("Policy rename failed. Since, the policy with same name already exists.");
940 //Query the Policy Entity with oldPolicy Name
941 String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf('.'));
942 String oldpolicyEntityquery = "FROM PolicyEntity where policyName like :policyEntityCheck and scope = :oldPolicySplit_0";
943 SimpleBindings params = new SimpleBindings();
944 params.put("policyEntityCheck", policyEntityCheck + "%");
945 params.put("oldPolicySplit_0", oldPolicySplit[0]);
946 List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery, params);
947 if(oldEntityData.isEmpty()){
948 return error("Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin.");
951 StringBuilder groupQuery = new StringBuilder();
952 groupQuery.append("FROM PolicyGroupEntity where (");
953 SimpleBindings geParams = new SimpleBindings();
954 for(int i=0; i<oldEntityData.size(); i++){
955 entity = (PolicyEntity) oldEntityData.get(i);
957 groupQuery.append("policyid = :policyId");
958 geParams.put("policyId", entity.getPolicyId());
960 groupQuery.append(" or policyid = :policyId").append(i);
961 geParams.put("policyId" + i, entity.getPolicyId());
964 groupQuery.append(")");
965 List<Object> groupEntityData = controller.getDataByQuery(groupQuery.toString(), geParams);
966 if(! groupEntityData.isEmpty()){
967 return error("Policy rename failed. Since the policy or its version is active in PDP Groups.");
969 for (Object anOldEntityData : oldEntityData) {
970 entity = (PolicyEntity) anOldEntityData;
971 String checkEntityName = entity.getPolicyName().replace(".xml", "");
972 checkEntityName = checkEntityName.substring(0, checkEntityName.lastIndexOf('.'));
973 String originalPolicyName = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator) + 1);
974 if (checkEntityName.equals(originalPolicyName)) {
975 checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0], newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
980 } catch (Exception e) {
981 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
982 return error(e.getMessage());
986 private String[] modifyPolicyName(String pathName) {
987 return modifyPolicyName(FORWARD_SLASH, pathName);
990 private String[] modifyPolicyName(String separator, String pathName) {
991 String policyName = pathName.replace(separator, ".");
992 if(policyName.contains(CONFIG2)){
993 policyName = policyName.replace(CONFIG, CONFIG1);
994 }else if(policyName.contains(ACTION2)){
995 policyName = policyName.replace(ACTION, ACTION1);
996 }else if(policyName.contains(DECISION2)){
997 policyName = policyName.replace(DECISION, DECISION1);
999 return policyName.split(":");
1002 private void checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, String oldScope, String removeoldPolicyExtension,
1003 String policyName, String newpolicyName, String oldpolicyName, String userId) {
1005 ConfigurationDataEntity configEntity = entity.getConfigurationData();
1006 ActionBodyEntity actionEntity = entity.getActionBodyEntity();
1007 PolicyController controller = getPolicyControllerInstance();
1009 String oldPolicyNameWithoutExtension = removeoldPolicyExtension;
1010 String newPolicyNameWithoutExtension = removenewPolicyExtension;
1011 if(removeoldPolicyExtension.endsWith(".xml")){
1012 oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf('.'));
1013 newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf('.'));
1015 entity.setPolicyName(entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
1016 entity.setPolicyData(entity.getPolicyData().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
1017 entity.setScope(newScope);
1018 entity.setModifiedBy(userId);
1020 String oldConfigurationName = null;
1021 String newConfigurationName = null;
1022 if(newpolicyName.contains(CONFIG2)){
1023 oldConfigurationName = configEntity.getConfigurationName();
1024 configEntity.setConfigurationName(configEntity.getConfigurationName().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
1025 controller.updateData(configEntity);
1026 newConfigurationName = configEntity.getConfigurationName();
1027 File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName);
1029 File renamefile = new File(PolicyController.getConfigHome() + File.separator + newConfigurationName);
1030 file.renameTo(renamefile);
1032 }else if(newpolicyName.contains(ACTION2)){
1033 oldConfigurationName = actionEntity.getActionBodyName();
1034 actionEntity.setActionBody(actionEntity.getActionBody().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
1035 controller.updateData(actionEntity);
1036 newConfigurationName = actionEntity.getActionBodyName();
1037 File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName);
1039 File renamefile = new File(PolicyController.getActionHome() + File.separator + newConfigurationName);
1040 file.renameTo(renamefile);
1043 controller.updateData(entity);
1045 PolicyRestController restController = new PolicyRestController();
1046 restController.notifyOtherPAPSToUpdateConfigurations("rename", newConfigurationName, oldConfigurationName);
1047 PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldpolicyName);
1048 versionEntity.setPolicyName(policyName);
1049 versionEntity.setModifiedBy(userId);
1050 controller.updateData(versionEntity);
1051 String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator)+1);
1052 String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
1053 if(movePolicyCheck.equals(moveOldPolicyCheck)){
1054 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move");
1056 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename");
1058 } catch (Exception e) {
1059 LOGGER.error(EXCEPTION_OCCURED +e);
1064 private void cloneRecord(String newpolicyName, String oldScope, String inRemoveoldPolicyExtension, String newScope,
1065 String inRemovenewPolicyExtension, PolicyEntity entity, String userId) throws IOException{
1066 String queryEntityName;
1067 PolicyController controller = getPolicyControllerInstance();
1068 PolicyEntity cloneEntity = new PolicyEntity();
1069 cloneEntity.setPolicyName(newpolicyName);
1070 String removeoldPolicyExtension = inRemoveoldPolicyExtension;
1071 String removenewPolicyExtension = inRemovenewPolicyExtension;
1072 removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
1073 removenewPolicyExtension = removenewPolicyExtension.replace(".xml", "");
1074 cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope+"."+removeoldPolicyExtension, newScope+"."+removenewPolicyExtension));
1075 cloneEntity.setScope(entity.getScope());
1076 String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
1077 String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
1078 String newConfigurationName = null;
1079 if(newpolicyName.contains(CONFIG2)){
1080 ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
1081 configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1082 queryEntityName = configurationDataEntity.getConfigurationName();
1083 configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody());
1084 configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType());
1085 configurationDataEntity.setDeleted(false);
1086 configurationDataEntity.setCreatedBy(userId);
1087 configurationDataEntity.setModifiedBy(userId);
1088 controller.saveData(configurationDataEntity);
1089 ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
1090 cloneEntity.setConfigurationData(configEntiy);
1091 newConfigurationName = configEntiy.getConfigurationName();
1092 try (FileWriter fw = new FileWriter(PolicyController.getConfigHome() + File.separator + newConfigurationName);
1093 BufferedWriter bw = new BufferedWriter(fw)){
1094 bw.write(configEntiy.getConfigBody());
1095 } catch (IOException e) {
1096 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1099 }else if(newpolicyName.contains(ACTION2)){
1100 ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
1101 actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1102 queryEntityName = actionBodyEntity.getActionBodyName();
1103 actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody());
1104 actionBodyEntity.setDeleted(false);
1105 actionBodyEntity.setCreatedBy(userId);
1106 actionBodyEntity.setModifiedBy(userId);
1107 controller.saveData(actionBodyEntity);
1108 ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class, "actionBodyName", queryEntityName);
1109 cloneEntity.setActionBodyEntity(actionEntiy);
1110 newConfigurationName = actionEntiy.getActionBodyName();
1111 try (FileWriter fw = new FileWriter(PolicyController.getActionHome() + File.separator + newConfigurationName);
1112 BufferedWriter bw = new BufferedWriter(fw)){
1113 bw.write(actionEntiy.getActionBody());
1114 } catch (IOException e) {
1115 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1120 cloneEntity.setDeleted(entity.isDeleted());
1121 cloneEntity.setCreatedBy(userId);
1122 cloneEntity.setModifiedBy(userId);
1123 controller.saveData(cloneEntity);
1125 //Notify others paps regarding clone policy.
1126 PolicyRestController restController = new PolicyRestController();
1127 restController.notifyOtherPAPSToUpdateConfigurations("clonePolicy", newConfigurationName, null);
1131 private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
1133 String userId = UserUtils.getUserSession(request).getOrgUserId();
1134 String oldPath = params.getString("path");
1135 String newPath = params.getString("newPath");
1136 oldPath = oldPath.substring(oldPath.indexOf('/')+1);
1137 newPath = newPath.substring(newPath.indexOf('/')+1);
1139 String policyVersionName = newPath.replace(".xml", "");
1140 String version = policyVersionName.substring(policyVersionName.indexOf('.')+1);
1141 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')).replace(FORWARD_SLASH, File.separator);
1143 String newpolicyName = newPath.replace(FORWARD_SLASH, ".");
1145 String orignalPolicyName = oldPath.replace(FORWARD_SLASH, ".");
1147 String newPolicyCheck = newpolicyName;
1148 if(newPolicyCheck.contains(CONFIG2)){
1149 newPolicyCheck = newPolicyCheck.replace(CONFIG, CONFIG1);
1150 }else if(newPolicyCheck.contains(ACTION2)){
1151 newPolicyCheck = newPolicyCheck.replace(ACTION, ACTION1);
1152 }else if(newPolicyCheck.contains(DECISION2)){
1153 newPolicyCheck = newPolicyCheck.replace(DECISION, DECISION1);
1155 if(!newPolicyCheck.contains(":")){
1156 return error("Policy Clone Failed. The Name contains special characters.");
1158 String[] newPolicySplit = newPolicyCheck.split(":");
1160 String checkValidation = newPolicySplit[1].replace(".xml", "");
1161 checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf("."));
1162 if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)){
1163 return error("Policy Clone Failed. The Name contains special characters.");
1166 String[] oldPolicySplit = modifyPolicyName(orignalPolicyName);
1168 PolicyController controller = getPolicyControllerInstance();
1170 PolicyEntity entity = null;
1171 boolean success = false;
1173 //Check PolicyEntity table with newPolicy Name
1174 String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
1175 SimpleBindings policyParams = new SimpleBindings();
1176 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
1177 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
1178 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
1179 if(!queryData.isEmpty()){
1180 return error("Policy already exists with same name");
1183 //Query the Policy Entity with oldPolicy Name
1184 policyEntityquery = "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0";
1185 SimpleBindings peParams = new SimpleBindings();
1186 peParams.put("oldPolicySplit_1", oldPolicySplit[1]);
1187 peParams.put("oldPolicySplit_0", oldPolicySplit[0]);
1188 if(PolicyController.isjUnit()){
1189 queryData = controller.getDataByQuery(policyEntityquery, null);
1191 queryData = controller.getDataByQuery(policyEntityquery, peParams);
1193 if(!queryData.isEmpty()){
1194 entity = (PolicyEntity) queryData.get(0);
1197 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId);
1202 PolicyVersion entityItem = new PolicyVersion();
1203 entityItem.setActiveVersion(Integer.parseInt(version));
1204 entityItem.setHigherVersion(Integer.parseInt(version));
1205 entityItem.setPolicyName(policyName);
1206 entityItem.setCreatedBy(userId);
1207 entityItem.setModifiedBy(userId);
1208 entityItem.setModifiedDate(new Date());
1209 controller.saveData(entityItem);
1212 LOGGER.debug("copy from: {} to: {}" + oldPath +newPath);
1215 } catch (Exception e) {
1216 LOGGER.error("copy", e);
1217 return error(e.getMessage());
1221 //Delete Policy or Scope Functionality
1222 private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
1223 PolicyController controller = getPolicyControllerInstance();
1224 PolicyRestController restController = new PolicyRestController();
1225 PolicyEntity policyEntity = null;
1226 String policyNamewithoutExtension;
1228 String userId = UserUtils.getUserSession(request).getOrgUserId();
1229 String deleteVersion = "";
1230 String path = params.getString("path");
1231 LOGGER.debug("delete {}" +path);
1232 if(params.has("deleteVersion")){
1233 deleteVersion = params.getString("deleteVersion");
1235 path = path.substring(path.indexOf('/')+1);
1236 String policyNamewithExtension = path.replace(FORWARD_SLASH, File.separator);
1237 String policyVersionName = policyNamewithExtension.replace(".xml", "");
1239 SimpleBindings policyParams = new SimpleBindings();
1240 if(path.endsWith(".xml")){
1241 policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf('.'));
1242 String[] split = modifyPolicyName(File.separator, policyNamewithoutExtension);
1243 query = "FROM PolicyEntity where policyName like :split_1 and scope = :split_0";
1244 policyParams.put(SPLIT_1, split[1] + "%");
1245 policyParams.put(SPLIT_0, split[0]);
1247 policyNamewithoutExtension = path.replace(File.separator, ".");
1248 query = "FROM PolicyEntity where scope like :policyNamewithoutExtension";
1249 policyParams.put("policyNamewithoutExtension", policyNamewithoutExtension + "%");
1252 List<Object> policyEntityobjects = controller.getDataByQuery(query, policyParams);
1253 String activePolicyName = null;
1254 boolean pdpCheck = false;
1255 if(path.endsWith(".xml")){
1256 policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator);
1257 int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf('.')+1));
1258 if("ALL".equals(deleteVersion)){
1259 if(!policyEntityobjects.isEmpty()){
1260 for(Object object : policyEntityobjects){
1261 policyEntity = (PolicyEntity) object;
1262 String groupEntityquery = "from PolicyGroupEntity where policyid ='"+policyEntity.getPolicyId()+"'";
1263 SimpleBindings pgeParams = new SimpleBindings();
1264 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, pgeParams);
1265 if(!groupobject.isEmpty()){
1267 activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName();
1269 //Delete the entity from Elastic Search Database
1270 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1271 restController.deleteElasticData(searchFileName);
1272 //Delete the entity from Policy Entity table
1273 controller.deleteData(policyEntity);
1274 if(policyNamewithoutExtension.contains(CONFIG2)){
1275 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1276 controller.deleteData(policyEntity.getConfigurationData());
1277 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getConfigurationData().getConfigurationName());
1278 }else if(policyNamewithoutExtension.contains(ACTION2)){
1279 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1280 controller.deleteData(policyEntity.getActionBodyEntity());
1281 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getActionBodyEntity().getActionBodyName());
1286 //Policy Notification
1287 PolicyVersion versionEntity = new PolicyVersion();
1288 versionEntity.setPolicyName(policyNamewithoutExtension);
1289 versionEntity.setModifiedBy(userId);
1290 controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll");
1292 //Delete from policyVersion table
1293 String getActivePDPPolicyVersion = activePolicyName.replace(".xml", "");
1294 getActivePDPPolicyVersion = getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf('.')+1);
1295 String policyVersionQuery = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION +getActivePDPPolicyVersion+"' , highest_version='"+getActivePDPPolicyVersion+"' where policy_name ='" +policyNamewithoutExtension.replace(BACKSLASH, ESCAPE_BACKSLASH)+"' and id >0";
1296 controller.executeQuery(policyVersionQuery);
1297 return error("Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "+activePolicyName);
1299 //No Active Policy in PDP. So, deleting all entries from policyVersion table
1300 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace(BACKSLASH, ESCAPE_BACKSLASH)+"' and id >0";
1301 controller.executeQuery(policyVersionQuery);
1303 }else if("CURRENT".equals(deleteVersion)){
1304 String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1);
1305 String currentVersionScope = policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator)).replace(File.separator, ".");
1306 query = "FROM PolicyEntity where policyName = :currentVersionPolicyName and scope = :currentVersionScope";
1308 SimpleBindings peParams = new SimpleBindings();
1309 peParams.put("currentVersionPolicyName", currentVersionPolicyName);
1310 peParams.put("currentVersionScope", currentVersionScope);
1312 List<Object> policyEntitys = controller.getDataByQuery(query, peParams);
1313 if(!policyEntitys.isEmpty()){
1314 policyEntity = (PolicyEntity) policyEntitys.get(0);
1316 if(policyEntity == null){
1320 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId and policyid > 0";
1321 SimpleBindings geParams = new SimpleBindings();
1322 geParams.put("policyEntityId", policyEntity.getPolicyId());
1323 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1324 if(!groupobject.isEmpty()){
1325 return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'");
1328 //Delete the entity from Elastic Search Database
1329 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1330 restController.deleteElasticData(searchFileName);
1331 //Delete the entity from Policy Entity table
1332 controller.deleteData(policyEntity);
1333 if(policyNamewithoutExtension.contains(CONFIG2)){
1334 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1335 controller.deleteData(policyEntity.getConfigurationData());
1336 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getConfigurationData().getConfigurationName());
1337 }else if(policyNamewithoutExtension.contains(ACTION2)){
1338 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1339 controller.deleteData(policyEntity.getActionBodyEntity());
1340 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getActionBodyEntity().getActionBodyName());
1344 int highestVersion = 0;
1345 if(!policyEntityobjects.isEmpty()){
1346 for(Object object : policyEntityobjects){
1347 policyEntity = (PolicyEntity) object;
1348 String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
1349 int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf('.')+1));
1350 if(policyEntityVersion > highestVersion && policyEntityVersion != version){
1351 highestVersion = policyEntityVersion;
1356 //Policy Notification
1357 PolicyVersion entity = new PolicyVersion();
1358 entity.setPolicyName(policyNamewithoutExtension);
1359 entity.setActiveVersion(highestVersion);
1360 entity.setModifiedBy(userId);
1361 controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne");
1364 if(highestVersion != 0){
1365 updatequery = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION +highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"'";
1367 updatequery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1369 controller.executeQuery(updatequery);
1371 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1372 controller.executeQuery(policyVersionQuery);
1376 List<String> activePoliciesInPDP = new ArrayList<>();
1377 if(policyEntityobjects.isEmpty()){
1378 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace(BACKSLASH, ESCAPE_BACKSLASH)+"%' and id >0";
1379 controller.executeQuery(policyScopeQuery);
1382 for(Object object : policyEntityobjects){
1383 policyEntity = (PolicyEntity) object;
1384 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId";
1385 SimpleBindings geParams = new SimpleBindings();
1386 geParams.put("policyEntityId", policyEntity.getPolicyId());
1387 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1388 if(!groupobject.isEmpty()){
1390 activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName());
1392 //Delete the entity from Elastic Search Database
1393 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1394 restController.deleteElasticData(searchFileName);
1395 //Delete the entity from Policy Entity table
1396 controller.deleteData(policyEntity);
1397 policyNamewithoutExtension = policyEntity.getPolicyName();
1398 if(policyNamewithoutExtension.contains(CONFIG2)){
1399 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1400 controller.deleteData(policyEntity.getConfigurationData());
1401 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getConfigurationData().getConfigurationName());
1402 }else if(policyNamewithoutExtension.contains(ACTION2)){
1403 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1404 controller.deleteData(policyEntity.getActionBodyEntity());
1405 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getActionBodyEntity().getActionBodyName());
1409 //Delete from policyVersion and policyEditor Scope table
1410 String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace(BACKSLASH, ESCAPE_BACKSLASH)+"%' and id >0";
1411 controller.executeQuery(policyVersionQuery);
1413 //Policy Notification
1414 PolicyVersion entity = new PolicyVersion();
1415 entity.setPolicyName(path);
1416 entity.setModifiedBy(userId);
1417 controller.watchPolicyFunction(entity, path, "DeleteScope");
1419 //Add Active Policies List to PolicyVersionTable
1420 for (String anActivePoliciesInPDP : activePoliciesInPDP) {
1421 String activePDPPolicyName = anActivePoliciesInPDP.replace(".xml", "");
1422 int activePDPPolicyVersion = Integer.parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf('.') + 1));
1423 activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf('.')).replace(".", File.separator);
1424 PolicyVersion insertactivePDPVersion = new PolicyVersion();
1425 insertactivePDPVersion.setPolicyName(activePDPPolicyName);
1426 insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion);
1427 insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion);
1428 insertactivePDPVersion.setCreatedBy(userId);
1429 insertactivePDPVersion.setModifiedBy(userId);
1430 controller.saveData(insertactivePDPVersion);
1433 return error("All the Policies has been deleted in Scope. Except the following list of Policies:"+activePoliciesInPDP);
1435 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace(BACKSLASH, ESCAPE_BACKSLASH)+"%' and id >0";
1436 controller.executeQuery(policyScopeQuery);
1441 } catch (Exception e) {
1442 LOGGER.error("delete", e);
1443 return error(e.getMessage());
1448 private JSONObject editFile(JSONObject params) throws ServletException {
1451 PolicyController controller = getPolicyControllerInstance();
1452 String mode = params.getString("mode");
1453 String path = params.getString("path");
1454 LOGGER.debug("editFile path: {}"+ path);
1456 String domain = path.substring(1, path.lastIndexOf('/'));
1457 domain = domain.replace(FORWARD_SLASH, ".");
1459 path = path.substring(1);
1460 path = path.replace(FORWARD_SLASH, ".");
1462 String[] split = modifyPolicyName(path);
1464 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
1465 SimpleBindings peParams = new SimpleBindings();
1466 peParams.put(SPLIT_1, split[1]);
1467 peParams.put(SPLIT_0, split[0]);
1468 List<Object> queryData;
1469 if(PolicyController.isjUnit()){
1470 queryData = controller.getDataByQuery(query, null);
1472 queryData = controller.getDataByQuery(query, peParams);
1474 PolicyEntity entity = (PolicyEntity) queryData.get(0);
1475 InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
1478 Object policy = XACMLPolicyScanner.readPolicy(stream);
1479 PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
1480 policyAdapter.setData(policy);
1482 if("viewPolicy".equalsIgnoreCase(mode)){
1483 policyAdapter.setReadOnly(true);
1484 policyAdapter.setEditPolicy(false);
1486 policyAdapter.setReadOnly(false);
1487 policyAdapter.setEditPolicy(true);
1490 policyAdapter.setDomainDir(domain);
1491 policyAdapter.setPolicyData(policy);
1492 String policyName = path.replace(".xml", "");
1493 policyName = policyName.substring(0, policyName.lastIndexOf('.'));
1494 policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf('.')+1));
1496 PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance();
1497 Objects.requireNonNull(setpolicyAdapter).configure(policyAdapter,entity);
1499 policyAdapter.setParentPath(null);
1500 ObjectMapper mapper = new ObjectMapper();
1501 String json = mapper.writeValueAsString(policyAdapter);
1502 JsonNode jsonNode = mapper.readTree(json);
1504 return new JSONObject().put(RESULT, jsonNode);
1505 } catch (Exception e) {
1506 LOGGER.error("editFile", e);
1507 return error(e.getMessage());
1512 private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
1513 PolicyController controller = getPolicyControllerInstance();
1516 String userId = UserUtils.getUserSession(request).getOrgUserId();
1517 String path = params.getString("path");
1519 if(params.has(SUB_SCOPENAME)){
1520 if(! "".equals(params.getString(SUB_SCOPENAME))) {
1521 name = params.getString("path").replace(FORWARD_SLASH, File.separator) + File.separator +params.getString(SUB_SCOPENAME);
1524 name = params.getString(NAME);
1526 }catch(Exception e){
1527 name = params.getString(NAME);
1528 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e);
1530 String validateName;
1531 if(name.contains(File.separator)){
1532 validateName = name.substring(name.lastIndexOf(File.separator)+1);
1534 validateName = name;
1536 if(!name.isEmpty()){
1537 String validate = PolicyUtils.policySpecialCharValidator(validateName);
1538 if(!validate.contains(SUCCESS)){
1539 return error(validate);
1542 LOGGER.debug("addFolder path: {} name: {}" + path +name);
1543 if(! "".equals(name)){
1544 if(name.startsWith(File.separator)){
1545 name = name.substring(1);
1547 PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, SCOPE_NAME, name);
1549 UserInfo userInfo = new UserInfo();
1550 userInfo.setUserLoginId(userId);
1551 PolicyEditorScopes newScope = new PolicyEditorScopes();
1552 newScope.setScopeName(name);
1553 newScope.setUserCreatedBy(userInfo);
1554 newScope.setUserModifiedBy(userInfo);
1555 controller.saveData(newScope);
1557 return error("Scope Already Exists");
1561 } catch (Exception e) {
1562 LOGGER.error("addFolder", e);
1563 return error(e.getMessage());
1567 //Return Error Object
1568 private JSONObject error(String msg) throws ServletException {
1570 JSONObject result = new JSONObject();
1571 result.put(SUCCESS, false);
1572 result.put("error", msg);
1573 return new JSONObject().put(RESULT, result);
1574 } catch (JSONException e) {
1575 throw new ServletException(e);
1579 //Return Success Object
1580 private JSONObject success() throws ServletException {
1582 JSONObject result = new JSONObject();
1583 result.put(SUCCESS, true);
1584 result.put("error", (Object) null);
1585 return new JSONObject().put(RESULT, result);
1586 } catch (JSONException e) {
1587 throw new ServletException(e);
1591 private PolicyController getPolicyControllerInstance(){
1592 return policyController != null ? getPolicyController() : new PolicyController();
1595 private String getTestUserId() {
1599 public static void setTestUserId(String testUserId) {
1600 PolicyManagerServlet.testUserId = testUserId;