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;
39 import java.util.ArrayList;
40 import java.util.Date;
41 import java.util.HashMap;
42 import java.util.HashSet;
43 import java.util.List;
47 import javax.json.Json;
48 import javax.json.JsonArray;
49 import javax.json.JsonReader;
50 import javax.script.SimpleBindings;
51 import javax.servlet.ServletConfig;
52 import javax.servlet.ServletException;
53 import javax.servlet.annotation.WebInitParam;
54 import javax.servlet.annotation.WebServlet;
55 import javax.servlet.http.HttpServlet;
56 import javax.servlet.http.HttpServletRequest;
57 import javax.servlet.http.HttpServletResponse;
59 import org.apache.commons.compress.utils.IOUtils;
60 import org.apache.commons.fileupload.FileItem;
61 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
62 import org.apache.commons.fileupload.servlet.ServletFileUpload;
63 import org.apache.http.HttpStatus;
64 import org.json.JSONArray;
65 import org.json.JSONException;
66 import org.json.JSONObject;
67 import org.onap.policy.common.logging.flexlogger.FlexLogger;
68 import org.onap.policy.common.logging.flexlogger.Logger;
69 import org.onap.policy.components.HumanPolicyComponent;
70 import org.onap.policy.controller.PolicyController;
71 import org.onap.policy.controller.PolicyExportAndImportController;
72 import org.onap.policy.rest.XACMLRest;
73 import org.onap.policy.rest.XACMLRestProperties;
74 import org.onap.policy.rest.adapter.PolicyRestAdapter;
75 import org.onap.policy.rest.jpa.ActionBodyEntity;
76 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
77 import org.onap.policy.rest.jpa.PolicyEditorScopes;
78 import org.onap.policy.rest.jpa.PolicyEntity;
79 import org.onap.policy.rest.jpa.PolicyVersion;
80 import org.onap.policy.rest.jpa.UserInfo;
81 import org.onap.policy.utils.PolicyUtils;
82 import org.onap.policy.utils.UserUtils.Pair;
83 import org.onap.policy.xacml.api.XACMLErrorConstants;
84 import org.onap.policy.xacml.util.XACMLPolicyScanner;
85 import org.onap.portalsdk.core.web.support.UserUtils;
87 import com.att.research.xacml.util.XACMLProperties;
88 import com.fasterxml.jackson.databind.JsonNode;
89 import com.fasterxml.jackson.databind.ObjectMapper;
92 @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.") })
93 public class PolicyManagerServlet extends HttpServlet {
94 private static final Logger LOGGER = FlexLogger.getLogger(PolicyManagerServlet.class);
95 private static final long serialVersionUID = -8453502699403909016L;
96 private static final String VERSION = "version";;
97 private static final String NAME = "name";
98 private static final String DATE = "date";
99 private static final String SIZE = "size";
100 private static final String TYPE = "type";
101 private static final String CREATED_BY = "createdBy";
102 private static final String MODIFIED_BY = "modifiedBy";
103 private static final String CONTENTTYPE = "application/json";
104 private static final String SUPERADMIN = "super-admin";
105 private static final String SUPEREDITOR = "super-editor";
106 private static final String SUPERGUEST = "super-guest";
107 private static final String ADMIN = "admin";
108 private static final String EDITOR = "editor";
109 private static final String GUEST = "guest";
110 private static final String RESULT = "result";
111 private static final String EXCEPTION_OCCURED = "Exception Occured";
112 private static final String CONFIG = ".Config_";
113 private static final String CONFIG1 = ":Config_";
114 private static final String ACTION = ".Action_";
115 private static final String ACTION1 = ":Action_";
116 private static final String DECISION = ".Decision_";
117 private static final String DECISION1 = ":Decision_";
118 private static final String CONFIG_ = "Config_";
119 private static final String ACTION_ = "Action_";
120 private static final String DECISION_ = "Decision_";
121 private static final String FORWARD_SLASH = "/";
122 private static final String BACKSLASH = "\\";
123 private static final String ESCAPE_BACKSLASH = "\\\\";
124 private static final String BACKSLASH_8TIMES = "\\\\\\\\";
125 private static List<String> serviceTypeNamesList = new ArrayList<>();
129 LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT, SEARCHLIST
132 private static PolicyController policyController;
133 public synchronized PolicyController getPolicyController() {
134 return policyController;
137 public static synchronized void setPolicyController(PolicyController policyController) {
138 PolicyManagerServlet.policyController = policyController;
141 private static Path closedLoopJsonLocation;
142 private static JsonArray policyNames;
143 private static String testUserId = null;
145 public static JsonArray getPolicyNames() {
149 public static void setPolicyNames(JsonArray policyNames) {
150 PolicyManagerServlet.policyNames = policyNames;
153 public static List<String> getServiceTypeNamesList() {
154 return serviceTypeNamesList;
158 public void init(ServletConfig servletConfig) throws ServletException {
159 super.init(servletConfig);
161 // Common initialization
163 XACMLRest.xacmlInit(servletConfig);
165 //Initialize ClosedLoop JSON
167 PolicyManagerServlet.initializeJSONLoad();
170 protected static void initializeJSONLoad() {
171 closedLoopJsonLocation = Paths.get(XACMLProperties
172 .getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP));
173 String location = closedLoopJsonLocation.toString();
174 if (! location.endsWith("json")) {
175 LOGGER.warn("JSONConfig file does not end with extension .json");
178 try (FileInputStream inputStream = new FileInputStream(location);
179 JsonReader jsonReader = Json.createReader(inputStream)) {
180 policyNames = jsonReader.readArray();
181 serviceTypeNamesList = new ArrayList<>();
182 for (int i = 0; i < policyNames.size(); i++) {
183 javax.json.JsonObject policyName = policyNames.getJsonObject(i);
184 String name = policyName.getJsonString("serviceTypePolicyName").getString();
185 serviceTypeNamesList.add(name);
187 } catch (IOException e) {
188 LOGGER.error("Exception Occured while initializing the JSONConfig file"+e);
193 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
194 LOGGER.debug("doPost");
196 // if request contains multipart-form-data
197 if (ServletFileUpload.isMultipartContent(request)) {
198 uploadFile(request, response);
200 // all other post request has json params in body
202 fileOperation(request, response);
204 } catch (Exception e) {
206 setError(e, response);
207 }catch(Exception e1){
208 LOGGER.error(EXCEPTION_OCCURED +e1);
213 //Set Error Message for Exception
214 private void setError(Exception t, HttpServletResponse response) throws IOException {
216 JSONObject responseJsonObject = error(t.getMessage());
217 response.setContentType(CONTENTTYPE);
218 PrintWriter out = response.getWriter();
219 out.print(responseJsonObject);
221 } catch (Exception x) {
222 LOGGER.error(EXCEPTION_OCCURED +x);
223 response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage());
227 //Policy Import Functionality
228 private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException {
230 Map<String, InputStream> files = new HashMap<>();
232 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
233 for (FileItem item : items) {
234 if (!item.isFormField()) {
235 // Process form file field (input type="file").
236 files.put(item.getName(), item.getInputStream());
237 processFormFile(request, item);
241 JSONObject responseJsonObject;
242 responseJsonObject = this.success();
243 response.setContentType(CONTENTTYPE);
244 PrintWriter out = response.getWriter();
245 out.print(responseJsonObject);
247 } catch (Exception e) {
248 LOGGER.debug("Cannot write file");
249 throw new ServletException("Cannot write file", e);
253 private void processFormFile(HttpServletRequest request, FileItem item) {
255 if(item.getName().endsWith(".xls") && item.getSize() <= PolicyController.getFileSizeLimit()){
256 File file = new File(item.getName());
257 try (OutputStream outputStream = new FileOutputStream(file);)
259 IOUtils.copy(item.getInputStream(), outputStream);
260 newFile = file.toString();
261 PolicyExportAndImportController importController = new PolicyExportAndImportController();
262 importController.importRepositoryFile(newFile, request);
264 LOGGER.error("Upload error : " + e);
267 else if (!item.getName().endsWith(".xls")) {
268 LOGGER.error("Non .xls filetype uploaded: " + item.getName());
270 else { //uploaded file size is greater than allowed
271 LOGGER.error("Upload file size limit exceeded! File size (Bytes) is: " + item.getSize());
275 //File Operation Functionality
276 private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
277 JSONObject responseJsonObject = null;
278 StringBuilder sb = new StringBuilder();
279 try (BufferedReader br = request.getReader()) {
281 while ((str = br.readLine()) != null) {
284 } catch (Exception e) {
285 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While doing File Operation" + e);
286 responseJsonObject = error(e.getMessage());
287 setResponse(response, responseJsonObject);
291 JSONObject jObj = new JSONObject(sb.toString());
292 JSONObject params = jObj.getJSONObject("params");
293 Mode mode = Mode.valueOf(params.getString("mode"));
295 String userId = UserUtils.getUserSession(request).getOrgUserId();
296 LOGGER.info("****************************************Logging UserID while doing actions on Editor tab*******************************************");
297 LOGGER.info("UserId: " + userId + "Action Mode: "+ mode.toString() + "Action Params: "+params.toString());
298 LOGGER.info("***********************************************************************************************************************************");
299 responseJsonObject = operateBasedOnMode(mode, params, request);
300 } catch (Exception e) {
301 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Processing Json" + e);
302 responseJsonObject = error(e.getMessage());
304 setResponse(response, responseJsonObject);
307 private void setResponse(HttpServletResponse response, JSONObject responseJsonObject) {
308 response.setContentType(CONTENTTYPE);
309 try (PrintWriter out = response.getWriter()) {
310 out.print(responseJsonObject);
312 } catch (IOException e) {
313 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception occured while writing response" + e);
318 private JSONObject operateBasedOnMode(Mode mode, JSONObject params, HttpServletRequest request) throws ServletException{
319 JSONObject responseJsonObject = null;
323 responseJsonObject = addFolder(params, request);
326 responseJsonObject = copy(params, request);
329 responseJsonObject = delete(params, request);
333 responseJsonObject = editFile(params);
336 responseJsonObject = list(params, request);
339 responseJsonObject = rename(params, request);
341 case DESCRIBEPOLICYFILE:
342 responseJsonObject = describePolicy(params);
345 responseJsonObject = switchVersion(params, request);
348 responseJsonObject = searchPolicyList(params, request);
351 throw new ServletException("not implemented");
353 if (responseJsonObject == null) {
354 responseJsonObject = error("generic error : responseJsonObject is null");
356 return responseJsonObject;
360 private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) {
361 List<Object> policyData = new ArrayList<>();
362 JSONArray policyList = null;
363 if(params.has("policyList")){
364 policyList = (JSONArray) params.get("policyList");
366 PolicyController controller = getPolicyControllerInstance();
367 List<JSONObject> resultList = new ArrayList<>();
369 if (!lookupPolicyData(request, policyData, policyList, controller, resultList))
370 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
373 LOGGER.error("Exception occured while reading policy Data from Policy Version table for Policy Search Data"+e);
376 return new JSONObject().put(RESULT, resultList);
379 private boolean lookupPolicyData(HttpServletRequest request, List<Object> policyData, JSONArray policyList, PolicyController controller, List<JSONObject> resultList){
381 Set<String> scopes;//Get the Login Id of the User from Request
382 String userId = UserUtils.getUserSession(request).getOrgUserId();
383 List<Object> userRoles = controller.getRoles(userId);
384 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
387 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
388 if(scopes.isEmpty()){
391 Set<String> tempScopes = scopes;
392 for(String scope : tempScopes){
393 addScope(scopes, scope);
396 if(policyList!= null){
397 for(int i = 0; i < policyList.length(); i++){
398 String policyName = policyList.get(i).toString().replace(".xml", "");
399 String version = policyName.substring(policyName.lastIndexOf('.')+1);
400 policyName = policyName.substring(0, policyName.lastIndexOf('.')).replace(".", File.separator);
401 parsePolicyList(resultList, controller, policyName, version);
404 getPolicyDataForSUPERRoles(policyData, controller, resultList, roles, scopes);
409 private void getPolicyDataForSUPERRoles(List<Object> policyData, PolicyController controller, List<JSONObject> resultList, List<String> roles, Set<String> scopes) {
410 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ){
411 policyData = controller.getData(PolicyVersion.class);
413 List<Object> filterdatas = controller.getData(PolicyVersion.class);
414 for(Object filter : filterdatas) {
415 addFilterData(policyData, scopes, (PolicyVersion) filter);
419 if(!policyData.isEmpty()){
420 updateResultList(policyData, resultList);
424 private void addFilterData(List<Object> policyData, Set<String> scopes, PolicyVersion filter) {
426 String scopeName = filter.getPolicyName().substring(0, filter.getPolicyName().lastIndexOf(File.separator));
427 if(scopes.contains(scopeName)){
428 policyData.add(filter);
431 LOGGER.error("Exception occured while filtering policyversion data"+e);
435 private void updateResultList(List<Object> policyData, List<JSONObject> resultList) {
436 for(int i =0; i < policyData.size(); i++){
437 PolicyVersion policy = (PolicyVersion) policyData.get(i);
438 JSONObject el = new JSONObject();
439 el.put(NAME, policy.getPolicyName().replace(File.separator, FORWARD_SLASH));
440 el.put(DATE, policy.getModifiedDate());
441 el.put(VERSION, policy.getActiveVersion());
443 el.put(TYPE, "file");
444 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
445 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
450 private void parsePolicyList(List<JSONObject> resultList, PolicyController controller, String policyName, String version) {
451 if(policyName.contains(BACKSLASH)){
452 policyName = policyName.replace(BACKSLASH, ESCAPE_BACKSLASH);
454 String policyVersionQuery = "From PolicyVersion where policy_name = :policyName and active_version = :version and id >0";
455 SimpleBindings pvParams = new SimpleBindings();
456 pvParams.put("policyName", policyName);
457 pvParams.put(VERSION, version);
458 List<Object> activeData = controller.getDataByQuery(policyVersionQuery, pvParams);
459 if(!activeData.isEmpty()){
460 PolicyVersion policy = (PolicyVersion) activeData.get(0);
461 JSONObject el = new JSONObject();
462 el.put(NAME, policy.getPolicyName().replace(File.separator, FORWARD_SLASH));
463 el.put(DATE, policy.getModifiedDate());
464 el.put(VERSION, policy.getActiveVersion());
466 el.put(TYPE, "file");
467 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
468 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
473 private void addScope(Set<String> scopes, String scope) {
474 List<Object> scopesList = queryPolicyEditorScopes(scope);
475 if(!scopesList.isEmpty()){
476 for(int i = 0; i < scopesList.size(); i++){
477 PolicyEditorScopes tempScope = (PolicyEditorScopes) scopesList.get(i);
478 scopes.add(tempScope.getScopeName());
483 //Switch Version Functionality
484 private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{
485 String path = params.getString("path");
486 String userId = null;
488 userId = UserUtils.getUserSession(request).getOrgUserId();
489 } catch (Exception e) {
490 LOGGER.error("Exception Occured while reading userid from cookie" +e);
493 String removeExtension = path.replace(".xml", "");
494 if(path.startsWith(FORWARD_SLASH)){
495 policyName = removeExtension.substring(1, removeExtension.lastIndexOf('.'));
497 policyName = removeExtension.substring(0, removeExtension.lastIndexOf('.'));
501 PolicyController controller = getPolicyControllerInstance();
502 if(! params.toString().contains("activeVersion")){
503 return controller.switchVersionPolicyContent(policyName);
505 String activeVersion = params.getString("activeVersion");
506 String highestVersion = params.get("highestVersion").toString();
507 if(Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)){
508 return error("The Version shouldn't be greater than Highest Value");
510 activePolicy = policyName + "." + activeVersion + ".xml";
511 String[] splitDBCheckName = modifyPolicyName(activePolicy);
512 String peQuery = "FROM PolicyEntity where policyName = :splitDBCheckName_1 and scope = :splitDBCheckName_0";
513 SimpleBindings policyParams = new SimpleBindings();
514 policyParams.put("splitDBCheckName_1", splitDBCheckName[1]);
515 policyParams.put("splitDBCheckName_0", splitDBCheckName[0]);
516 List<Object> policyEntity = controller.getDataByQuery(peQuery, policyParams);
517 PolicyEntity pentity = (PolicyEntity) policyEntity.get(0);
518 if(pentity.isDeleted()){
519 return error("The Policy is Not Existing in Workspace");
521 if(policyName.contains(FORWARD_SLASH)){
522 policyName = policyName.replace(FORWARD_SLASH, File.separator);
524 policyName = policyName.substring(policyName.indexOf(File.separator)+1);
525 if(policyName.contains(BACKSLASH)){
526 policyName = policyName.replace(File.separator, BACKSLASH);
528 policyName = splitDBCheckName[0].replace(".", File.separator)+File.separator+policyName;
529 String watchPolicyName = policyName;
530 if(policyName.contains(FORWARD_SLASH)){
531 policyName = policyName.replace(FORWARD_SLASH, File.separator);
533 if(policyName.contains(BACKSLASH)){
534 policyName = policyName.replace(BACKSLASH, ESCAPE_BACKSLASH);
536 String query = "update PolicyVersion set active_version='"+activeVersion+"' where policy_name ='"+policyName+"' and id >0";
538 controller.executeQuery(query);
539 //Policy Notification
540 PolicyVersion entity = new PolicyVersion();
541 entity.setPolicyName(watchPolicyName);
542 entity.setActiveVersion(Integer.parseInt(activeVersion));
543 entity.setModifiedBy(userId);
544 controller.watchPolicyFunction(entity, activePolicy, "SwitchVersion");
549 private JSONObject describePolicy(JSONObject params) throws ServletException{
550 JSONObject object = null;
551 String path = params.getString("path");
552 String policyName = null;
553 if(path.startsWith(FORWARD_SLASH)){
554 path = path.substring(1);
555 policyName = path.substring(path.lastIndexOf('/') +1);
556 path = path.replace(FORWARD_SLASH, ".");
558 path = path.replace(FORWARD_SLASH, ".");
561 if(path.contains(CONFIG_)){
562 path = path.replace(CONFIG, CONFIG1);
563 }else if(path.contains(ACTION_)){
564 path = path.replace(ACTION, ACTION1);
565 }else if(path.contains(DECISION_)){
566 path = path.replace(DECISION, DECISION1);
568 PolicyController controller = getPolicyControllerInstance();
569 String[] split = path.split(":");
570 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
571 SimpleBindings peParams = new SimpleBindings();
572 peParams.put("split_1", split[1]);
573 peParams.put("split_0", split[0]);
574 List<Object> queryData = null;
575 if(PolicyController.isjUnit()){
576 queryData = controller.getDataByQuery(query, null);
578 queryData = controller.getDataByQuery(query, peParams);
580 if(queryData.isEmpty()){
581 return error("Error Occured while Describing the Policy - query is empty");
583 PolicyEntity entity = (PolicyEntity) queryData.get(0);
586 temp = File.createTempFile(policyName, ".tmp");
587 } catch (IOException e) {
588 String message = "Failed to create temp file " + policyName + ".tmp";
589 LOGGER.error(message + e);
590 return error(message);
592 try (BufferedWriter bw = new BufferedWriter(new FileWriter(temp))) {
593 bw.write(entity.getPolicyData());
594 } catch (IOException e) {
595 LOGGER.error("Exception Occured while Describing the Policy"+e);
597 object = HumanPolicyComponent.DescribePolicy(temp);
600 Files.delete(temp.toPath());
601 } catch (IOException e) {
602 LOGGER.warn("Failed to delete " + temp.getName() + e);
608 //Get the List of Policies and Scopes for Showing in Editor tab
609 private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException {
611 return processPolicyList(params, request);
612 } catch (Exception e) {
613 LOGGER.error("list", e);
614 return error(e.getMessage());
618 private JSONObject processPolicyList(JSONObject params, HttpServletRequest request) throws ServletException {
619 PolicyController controller = getPolicyControllerInstance();
620 //Get the Login Id of the User from Request
621 String testUserID = getTestUserId();
622 String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId();
623 List<Object> userRoles = controller.getRoles(userId);
624 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
625 List<String> roles = pair.u;
626 Set<String> scopes = pair.t;
628 List<JSONObject> resultList = new ArrayList<>();
629 boolean onlyFolders = params.getBoolean("onlyFolders");
630 String path = params.getString("path");
631 if(path.contains("..xml")){
632 path = path.replaceAll("..xml", "").trim();
635 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
636 if(scopes.isEmpty()){
637 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
639 if(!FORWARD_SLASH.equals(path)){
640 String tempScope = path.substring(1, path.length());
641 tempScope = tempScope.replace(FORWARD_SLASH, File.separator);
642 scopes.add(tempScope);
647 if (!FORWARD_SLASH.equals(path)) {
649 String scopeName = path.substring(path.indexOf('/') +1);
650 activePolicyList(scopeName, resultList, roles, scopes, onlyFolders);
651 } catch (Exception ex) {
652 LOGGER.error("Error Occured While reading Policy Files List"+ex );
654 return new JSONObject().put(RESULT, resultList);
657 processRoles(scopes, roles, resultList);
659 return new JSONObject().put(RESULT, resultList);
662 private void processRoles(Set<String> scopes, List<String> roles, List<JSONObject> resultList) {
663 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
664 List<Object> scopesList = queryPolicyEditorScopes(null);
665 for(Object list : scopesList){
666 PolicyEditorScopes scope = (PolicyEditorScopes) list;
667 if(!(scope.getScopeName().contains(File.separator))){
668 JSONObject el = new JSONObject();
669 el.put(NAME, scope.getScopeName());
670 el.put(DATE, scope.getModifiedDate());
673 el.put(CREATED_BY, scope.getUserCreatedBy().getUserName());
674 el.put(MODIFIED_BY, scope.getUserModifiedBy().getUserName());
678 }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){
679 for(Object scope : scopes){
680 JSONObject el = new JSONObject();
681 List<Object> scopesList = queryPolicyEditorScopes(scope.toString());
682 if(!scopesList.isEmpty()){
683 PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
684 el.put(NAME, scopeById.getScopeName());
685 el.put(DATE, scopeById.getModifiedDate());
688 el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName());
689 el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName());
696 private List<Object> queryPolicyEditorScopes(String scopeName){
697 String scopeNamequery;
698 SimpleBindings params = new SimpleBindings();
699 if(scopeName == null){
700 scopeNamequery = "from PolicyEditorScopes";
702 scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
703 params.put("scopeName", scopeName + "%");
705 PolicyController controller = getPolicyControllerInstance();
706 List<Object> scopesList;
707 if(PolicyController.isjUnit()){
708 scopesList = controller.getDataByQuery(scopeNamequery, null);
710 scopesList = controller.getDataByQuery(scopeNamequery, params);
715 //Get Active Policy List based on Scope Selection form Policy Version table
716 private void activePolicyList(String inScopeName, List<JSONObject> resultList, List<String> roles, Set<String> scopes, boolean onlyFolders){
717 PolicyController controller = getPolicyControllerInstance();
718 String scopeName = inScopeName;
719 if(scopeName.contains(FORWARD_SLASH)){
720 scopeName = scopeName.replace(FORWARD_SLASH, File.separator);
722 if(scopeName.contains(BACKSLASH)){
723 scopeName = scopeName.replace(BACKSLASH, ESCAPE_BACKSLASH);
725 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
726 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
728 SimpleBindings params = new SimpleBindings();
729 params.put("scopeName", scopeName + "%");
731 List<Object> activePolicies;
732 List<Object> scopesList;
733 if(PolicyController.isjUnit()){
734 activePolicies = controller.getDataByQuery(query, null);
735 scopesList = controller.getDataByQuery(scopeNamequery, null);
737 activePolicies = controller.getDataByQuery(query, params);
738 scopesList = controller.getDataByQuery(scopeNamequery, params);
740 for(Object list : scopesList) {
741 scopeName = checkScope(resultList, scopeName, (PolicyEditorScopes) list);
743 String scopeNameCheck;
744 for (Object list : activePolicies) {
745 PolicyVersion policy = (PolicyVersion) list;
746 String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator));
747 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
748 if(scopeName.contains(ESCAPE_BACKSLASH)){
749 scopeNameCheck = scopeName.replace(ESCAPE_BACKSLASH, File.separator);
751 scopeNameCheck = scopeName;
753 if(scopeNameValue.equals(scopeNameCheck)){
754 JSONObject el = new JSONObject();
755 el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
756 el.put(DATE, policy.getModifiedDate());
757 el.put(VERSION, policy.getActiveVersion());
759 el.put(TYPE, "file");
760 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
761 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
764 }else if(!scopes.isEmpty() && scopes.contains(scopeNameValue)){
765 JSONObject el = new JSONObject();
766 el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
767 el.put(DATE, policy.getModifiedDate());
768 el.put(VERSION, policy.getActiveVersion());
770 el.put(TYPE, "file");
771 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
772 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
778 private String checkScope(List<JSONObject> resultList, String scopeName, PolicyEditorScopes scopeById) {
779 String scope = scopeById.getScopeName();
780 if(scope.contains(File.separator)){
781 String targetScope = scope.substring(0, scope.lastIndexOf(File.separator));
782 if(scopeName.contains(ESCAPE_BACKSLASH)){
783 scopeName = scopeName.replace(ESCAPE_BACKSLASH, File.separator);
785 if(scope.contains(File.separator)){
786 scope = scope.substring(targetScope.length()+1);
787 if(scope.contains(File.separator)){
788 scope = scope.substring(0, scope.indexOf(File.separator));
791 if(scopeName.equalsIgnoreCase(targetScope)){
792 JSONObject el = new JSONObject();
794 el.put(DATE, scopeById.getModifiedDate());
797 el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName());
798 el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName());
805 private String getUserName(String loginId){
806 PolicyController controller = getPolicyControllerInstance();
807 UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
808 if(userInfo == null){
811 return userInfo.getUserName();
815 private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
817 return handlePolicyRename(params, request);
818 } catch (Exception e) {
819 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
820 return error(e.getMessage());
824 private JSONObject handlePolicyRename(JSONObject params, HttpServletRequest request) throws ServletException {
825 boolean isActive = false;
826 List<String> policyActiveInPDP = new ArrayList<>();
827 Set<String> scopeOfPolicyActiveInPDP = new HashSet<>();
828 String userId = UserUtils.getUserSession(request).getOrgUserId();
829 String oldPath = params.getString("path");
830 String newPath = params.getString("newPath");
831 oldPath = oldPath.substring(oldPath.indexOf('/')+1);
832 newPath = newPath.substring(newPath.indexOf('/')+1);
833 String checkValidation = null;
834 if(oldPath.endsWith(".xml")){
835 checkValidation = newPath.replace(".xml", "");
836 checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf("."));
837 checkValidation = checkValidation.substring(checkValidation.lastIndexOf(FORWARD_SLASH)+1);
838 if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains("success")){
839 return error("Policy Rename Failed. The Name contains special characters.");
841 JSONObject result = policyRename(oldPath, newPath, userId);
842 if(!(Boolean)(result.getJSONObject("result").get("success"))){
846 String scopeName = oldPath;
847 String newScopeName = newPath;
848 if(scopeName.contains(FORWARD_SLASH)){
849 scopeName = scopeName.replace(FORWARD_SLASH, File.separator);
850 newScopeName = newScopeName.replace(FORWARD_SLASH, File.separator);
852 checkValidation = newScopeName.substring(newScopeName.lastIndexOf(File.separator)+1);
853 if(scopeName.contains(BACKSLASH)){
854 scopeName = scopeName.replace(BACKSLASH, BACKSLASH_8TIMES);
855 newScopeName = newScopeName.replace(BACKSLASH, BACKSLASH_8TIMES);
857 if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains("success")){
858 return error("Scope Rename Failed. The Name contains special characters.");
860 PolicyController controller = getPolicyControllerInstance();
861 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
862 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
863 SimpleBindings pvParams = new SimpleBindings();
864 pvParams.put("scopeName", scopeName + "%");
865 List<Object> activePolicies = controller.getDataByQuery(query, pvParams);
866 List<Object> scopesList = controller.getDataByQuery(scopeNamequery, pvParams);
867 for(Object object : activePolicies){
868 PolicyVersion activeVersion = (PolicyVersion) object;
869 String policyOldPath = activeVersion.getPolicyName().replace(File.separator, FORWARD_SLASH) + "." + activeVersion.getActiveVersion() + ".xml";
870 String policyNewPath = policyOldPath.replace(oldPath, newPath);
871 JSONObject result = policyRename(policyOldPath, policyNewPath, userId);
872 if(!(Boolean)(result.getJSONObject("result").get("success"))){
874 policyActiveInPDP.add(policyOldPath);
875 String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf('/'));
876 scopeOfPolicyActiveInPDP.add(scope.replace(FORWARD_SLASH, File.separator));
879 boolean rename = false;
880 if(activePolicies.size() != policyActiveInPDP.size()){
884 UserInfo userInfo = new UserInfo();
885 userInfo.setUserLoginId(userId);
886 if(policyActiveInPDP.isEmpty()){
887 renameScope(scopesList, scopeName, newScopeName, controller);
889 renameScope(scopesList, scopeName, newScopeName, controller);
890 for(String scope : scopeOfPolicyActiveInPDP){
891 PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes();
892 editorScopeEntity.setScopeName(scope.replace(BACKSLASH, BACKSLASH_8TIMES));
893 editorScopeEntity.setUserCreatedBy(userInfo);
894 editorScopeEntity.setUserModifiedBy(userInfo);
895 controller.saveData(editorScopeEntity);
899 return error("The Following policies rename failed. Since they are active in PDP Groups" +policyActiveInPDP);
905 private void renameScope(List<Object> scopesList, String inScopeName, String newScopeName, PolicyController controller){
906 for(Object object : scopesList){
907 PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object;
908 String scopeName = inScopeName;
909 if(scopeName.contains(BACKSLASH_8TIMES)){
910 scopeName = scopeName.replace(BACKSLASH_8TIMES, File.separator);
911 newScopeName = newScopeName.replace(BACKSLASH_8TIMES, File.separator);
913 String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName);
914 editorScopeEntity.setScopeName(scope);
915 controller.updateData(editorScopeEntity);
919 private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
922 PolicyController controller = getPolicyControllerInstance();
924 String policyVersionName = newPath.replace(".xml", "");
925 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')).replace(FORWARD_SLASH, File.separator);
927 String oldpolicyVersionName = oldPath.replace(".xml", "");
928 String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf('.')).replace(FORWARD_SLASH, File.separator);
929 String newpolicyName = newPath.replace("/", ".");
930 String[] newPolicySplit = modifyPolicyName(newPath);
932 String[] oldPolicySplit = modifyPolicyName(oldPath);
934 //Check PolicyEntity table with newPolicy Name
935 String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
936 SimpleBindings policyParams = new SimpleBindings();
937 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
938 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
939 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
940 if(!queryData.isEmpty()){
941 return error("Policy rename failed. Since, the policy with same name already exists.");
944 //Query the Policy Entity with oldPolicy Name
945 String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf('.'));
946 String oldpolicyEntityquery = "FROM PolicyEntity where policyName like :policyEntityCheck and scope = :oldPolicySplit_0";
947 SimpleBindings params = new SimpleBindings();
948 params.put("policyEntityCheck", policyEntityCheck + "%");
949 params.put("oldPolicySplit_0", oldPolicySplit[0]);
950 List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery, params);
951 if(oldEntityData.isEmpty()){
952 return error("Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin.");
955 StringBuilder groupQuery = new StringBuilder();
956 groupQuery.append("FROM PolicyGroupEntity where (");
957 SimpleBindings geParams = new SimpleBindings();
958 for(int i=0; i<oldEntityData.size(); i++){
959 entity = (PolicyEntity) oldEntityData.get(i);
961 groupQuery.append("policyid = :policyId");
962 geParams.put("policyId", entity.getPolicyId());
964 groupQuery.append(" or policyid = :policyId" + i);
965 geParams.put("policyId" + i, entity.getPolicyId());
968 groupQuery.append(")");
969 List<Object> groupEntityData = controller.getDataByQuery(groupQuery.toString(), geParams);
970 if(! groupEntityData.isEmpty()){
971 return error("Policy rename failed. Since the policy or its version is active in PDP Groups.");
973 for(int i=0; i<oldEntityData.size(); i++){
974 entity = (PolicyEntity) oldEntityData.get(i);
975 String checkEntityName = entity.getPolicyName().replace(".xml", "");
976 checkEntityName = checkEntityName.substring(0, checkEntityName.lastIndexOf('.'));
977 String originalPolicyName = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
978 if(checkEntityName.equals(originalPolicyName)){
979 checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0] , newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
984 } catch (Exception e) {
985 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
986 return error(e.getMessage());
990 private String[] modifyPolicyName(String pathName) {
991 return modifyPolicyName(FORWARD_SLASH, pathName);
994 private String[] modifyPolicyName(String separator, String pathName) {
995 String policyName = pathName.replace(separator, ".");
996 if(policyName.contains(CONFIG_)){
997 policyName = policyName.replace(CONFIG, CONFIG1);
998 }else if(policyName.contains(ACTION_)){
999 policyName = policyName.replace(ACTION, ACTION1);
1000 }else if(policyName.contains(DECISION_)){
1001 policyName = policyName.replace(DECISION, DECISION1);
1003 return policyName.split(":");
1006 private JSONObject checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, String oldScope, String removeoldPolicyExtension,
1007 String policyName, String newpolicyName, String oldpolicyName, String userId) throws ServletException{
1009 ConfigurationDataEntity configEntity = entity.getConfigurationData();
1010 ActionBodyEntity actionEntity = entity.getActionBodyEntity();
1011 PolicyController controller = getPolicyControllerInstance();
1013 String oldPolicyNameWithoutExtension = removeoldPolicyExtension;
1014 String newPolicyNameWithoutExtension = removenewPolicyExtension;
1015 if(removeoldPolicyExtension.endsWith(".xml")){
1016 oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf('.'));
1017 newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf('.'));
1019 entity.setPolicyName(entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
1020 entity.setPolicyData(entity.getPolicyData().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
1021 entity.setScope(newScope);
1022 entity.setModifiedBy(userId);
1024 String oldConfigurationName = null;
1025 String newConfigurationName = null;
1026 if(newpolicyName.contains(CONFIG_)){
1027 oldConfigurationName = configEntity.getConfigurationName();
1028 configEntity.setConfigurationName(configEntity.getConfigurationName().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
1029 controller.updateData(configEntity);
1030 newConfigurationName = configEntity.getConfigurationName();
1031 File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName);
1033 File renamefile = new File(PolicyController.getConfigHome() + File.separator + newConfigurationName);
1034 file.renameTo(renamefile);
1036 }else if(newpolicyName.contains(ACTION_)){
1037 oldConfigurationName = actionEntity.getActionBodyName();
1038 actionEntity.setActionBody(actionEntity.getActionBody().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
1039 controller.updateData(actionEntity);
1040 newConfigurationName = actionEntity.getActionBodyName();
1041 File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName);
1043 File renamefile = new File(PolicyController.getActionHome() + File.separator + newConfigurationName);
1044 file.renameTo(renamefile);
1047 controller.updateData(entity);
1049 PolicyRestController restController = new PolicyRestController();
1050 restController.notifyOtherPAPSToUpdateConfigurations("rename", newConfigurationName, oldConfigurationName);
1051 PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldpolicyName);
1052 versionEntity.setPolicyName(policyName);
1053 versionEntity.setModifiedBy(userId);
1054 controller.updateData(versionEntity);
1055 String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator)+1);
1056 String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
1057 if(movePolicyCheck.equals(moveOldPolicyCheck)){
1058 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move");
1060 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename");
1063 } catch (Exception e) {
1064 LOGGER.error(EXCEPTION_OCCURED +e);
1065 return error(e.getMessage());
1069 private JSONObject cloneRecord(String newpolicyName, String oldScope, String inRemoveoldPolicyExtension, String newScope, String inRemovenewPolicyExtension, PolicyEntity entity, String userId) throws ServletException{
1070 String queryEntityName;
1071 PolicyController controller = getPolicyControllerInstance();
1072 PolicyEntity cloneEntity = new PolicyEntity();
1073 cloneEntity.setPolicyName(newpolicyName);
1074 String removeoldPolicyExtension = inRemoveoldPolicyExtension;
1075 String removenewPolicyExtension = inRemovenewPolicyExtension;
1076 removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
1077 removenewPolicyExtension = removenewPolicyExtension.replace(".xml", "");
1078 cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope+"."+removeoldPolicyExtension, newScope+"."+removenewPolicyExtension));
1079 cloneEntity.setScope(entity.getScope());
1080 String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
1081 String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
1082 String newConfigurationName = null;
1083 if(newpolicyName.contains(CONFIG_)){
1084 ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
1085 configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1086 queryEntityName = configurationDataEntity.getConfigurationName();
1087 configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody());
1088 configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType());
1089 configurationDataEntity.setDeleted(false);
1090 configurationDataEntity.setCreatedBy(userId);
1091 configurationDataEntity.setModifiedBy(userId);
1092 controller.saveData(configurationDataEntity);
1093 ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
1094 cloneEntity.setConfigurationData(configEntiy);
1095 newConfigurationName = configEntiy.getConfigurationName();
1096 try (FileWriter fw = new FileWriter(PolicyController.getConfigHome() + File.separator + newConfigurationName);
1097 BufferedWriter bw = new BufferedWriter(fw)){
1098 bw.write(configEntiy.getConfigBody());
1099 } catch (IOException e) {
1100 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1102 }else if(newpolicyName.contains(ACTION_)){
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);
1122 cloneEntity.setDeleted(entity.isDeleted());
1123 cloneEntity.setCreatedBy(userId);
1124 cloneEntity.setModifiedBy(userId);
1125 controller.saveData(cloneEntity);
1127 //Notify others paps regarding clone policy.
1128 PolicyRestController restController = new PolicyRestController();
1129 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(CONFIG_)){
1152 newPolicyCheck = newPolicyCheck.replace(CONFIG, CONFIG1);
1153 }else if(newPolicyCheck.contains(ACTION_)){
1154 newPolicyCheck = newPolicyCheck.replace(ACTION, ACTION1);
1155 }else if(newPolicyCheck.contains(DECISION_)){
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(CONFIG_)){
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(ACTION_)){
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 PolicyVersion 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 from PolicyVersion 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(CONFIG_)){
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(ACTION_)){
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");
1366 String updatequery = "";
1367 if(highestVersion != 0){
1368 updatequery = "update PolicyVersion set active_version='"+highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"'";
1370 updatequery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1372 controller.executeQuery(updatequery);
1374 String policyVersionQuery = "delete from PolicyVersion 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)+"%' and id >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(CONFIG_)){
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(ACTION_)){
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)+"%' and id >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(int i =0; i < activePoliciesInPDP.size(); i++){
1424 String activePDPPolicyName = activePoliciesInPDP.get(i).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)+"%' and id >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 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("subScopename")){
1523 if(! "".equals(params.getString("subScopename"))) {
1524 name = params.getString("path").replace(FORWARD_SLASH, File.separator) + File.separator +params.getString("subScopename");
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, "scopeName", 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 public String getTestUserId() {
1602 public static void setTestUserId(String testUserId) {
1603 PolicyManagerServlet.testUserId = testUserId;