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";
105 LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT, SEARCHLIST
108 private static PolicyController policyController;
109 public synchronized PolicyController getPolicyController() {
110 return policyController;
113 public static synchronized void setPolicyController(PolicyController policyController) {
114 PolicyManagerServlet.policyController = policyController;
117 private static String CONTENTTYPE = "application/json";
118 private static String SUPERADMIN = "super-admin";
119 private static String SUPEREDITOR = "super-editor";
120 private static String SUPERGUEST = "super-guest";
121 private static String ADMIN = "admin";
122 private static String EDITOR = "editor";
123 private static String GUEST = "guest";
124 private static String RESULT = "result";
126 private static Path closedLoopJsonLocation;
127 private static JsonArray policyNames;
128 private static String testUserId = null;
130 public static JsonArray getPolicyNames() {
134 public static void setPolicyNames(JsonArray policyNames) {
135 PolicyManagerServlet.policyNames = policyNames;
138 private static List<String> serviceTypeNamesList = new ArrayList<>();
140 public static List<String> getServiceTypeNamesList() {
141 return serviceTypeNamesList;
145 public void init(ServletConfig servletConfig) throws ServletException {
146 super.init(servletConfig);
148 // Common initialization
150 XACMLRest.xacmlInit(servletConfig);
152 //Initialize ClosedLoop JSON
154 PolicyManagerServlet.initializeJSONLoad();
157 protected static void initializeJSONLoad() {
158 closedLoopJsonLocation = Paths.get(XACMLProperties
159 .getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP));
160 String location = closedLoopJsonLocation.toString();
161 if (! location.endsWith("json")) {
162 LOGGER.warn("JSONConfig file does not end with extension .json");
165 try (FileInputStream inputStream = new FileInputStream(location);
166 JsonReader jsonReader = Json.createReader(inputStream)) {
167 policyNames = jsonReader.readArray();
168 serviceTypeNamesList = new ArrayList<>();
169 for (int i = 0; i < policyNames.size(); i++) {
170 javax.json.JsonObject policyName = policyNames.getJsonObject(i);
171 String name = policyName.getJsonString("serviceTypePolicyName").getString();
172 serviceTypeNamesList.add(name);
174 } catch (IOException e) {
175 LOGGER.error("Exception Occured while initializing the JSONConfig file"+e);
180 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
181 LOGGER.debug("doPost");
183 // if request contains multipart-form-data
184 if (ServletFileUpload.isMultipartContent(request)) {
185 uploadFile(request, response);
187 // all other post request has json params in body
189 fileOperation(request, response);
191 } catch (Exception e) {
193 setError(e, response);
194 }catch(Exception e1){
195 LOGGER.error("Exception Occured"+e1);
200 //Set Error Message for Exception
201 private void setError(Exception t, HttpServletResponse response) throws IOException {
203 JSONObject responseJsonObject = error(t.getMessage());
204 response.setContentType(CONTENTTYPE);
205 PrintWriter out = response.getWriter();
206 out.print(responseJsonObject);
208 } catch (Exception x) {
209 LOGGER.error("Exception Occured"+x);
210 response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage());
214 //Policy Import Functionality
215 private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException {
217 Map<String, InputStream> files = new HashMap<>();
219 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
220 for (FileItem item : items) {
221 if (!item.isFormField()) {
222 // Process form file field (input type="file").
223 files.put(item.getName(), item.getInputStream());
224 processFormFile(request, item);
228 JSONObject responseJsonObject;
229 responseJsonObject = this.success();
230 response.setContentType(CONTENTTYPE);
231 PrintWriter out = response.getWriter();
232 out.print(responseJsonObject);
234 } catch (Exception e) {
235 LOGGER.debug("Cannot write file");
236 throw new ServletException("Cannot write file", e);
240 private void processFormFile(HttpServletRequest request, FileItem item) {
242 if(item.getName().endsWith(".xls") && item.getSize() <= PolicyController.getFileSizeLimit()){
243 File file = new File(item.getName());
244 try (OutputStream outputStream = new FileOutputStream(file);)
246 IOUtils.copy(item.getInputStream(), outputStream);
247 newFile = file.toString();
248 PolicyExportAndImportController importController = new PolicyExportAndImportController();
249 importController.importRepositoryFile(newFile, request);
251 LOGGER.error("Upload error : " + e);
254 else if (!item.getName().endsWith(".xls")) {
255 LOGGER.error("Non .xls filetype uploaded: " + item.getName());
257 else { //uploaded file size is greater than allowed
258 LOGGER.error("Upload file size limit exceeded! File size (Bytes) is: " + item.getSize());
262 //File Operation Functionality
263 private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
264 JSONObject responseJsonObject = null;
266 StringBuilder sb = new StringBuilder();
267 BufferedReader br = request.getReader();
269 while ((str = br.readLine()) != null) {
273 JSONObject jObj = new JSONObject(sb.toString());
274 JSONObject params = jObj.getJSONObject("params");
275 Mode mode = Mode.valueOf(params.getString("mode"));
277 String userId = UserUtils.getUserSession(request).getOrgUserId();
278 LOGGER.info("****************************************Logging UserID while doing actions on Editor tab*******************************************");
279 LOGGER.info("UserId: " + userId + "Action Mode: "+ mode.toString() + "Action Params: "+params.toString());
280 LOGGER.info("***********************************************************************************************************************************");
285 responseJsonObject = addFolder(params, request);
288 responseJsonObject = copy(params, request);
291 responseJsonObject = delete(params, request);
295 responseJsonObject = editFile(params);
298 responseJsonObject = list(params, request);
301 responseJsonObject = rename(params, request);
303 case DESCRIBEPOLICYFILE:
304 responseJsonObject = describePolicy(params);
307 responseJsonObject = switchVersion(params, request);
310 responseJsonObject = searchPolicyList(params, request);
313 throw new ServletException("not implemented");
315 if (responseJsonObject == null) {
316 responseJsonObject = error("generic error : responseJsonObject is null");
318 } catch (Exception e) {
319 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While doing File Operation" + e);
320 responseJsonObject = error(e.getMessage());
322 response.setContentType(CONTENTTYPE);
323 PrintWriter out = response.getWriter();
324 out.print(responseJsonObject);
328 private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) {
329 List<Object> policyData = new ArrayList<>();
330 JSONArray policyList = null;
331 if(params.has("policyList")){
332 policyList = (JSONArray) params.get("policyList");
334 PolicyController controller = getPolicyControllerInstance();
335 List<JSONObject> resultList = new ArrayList<>();
337 if (!lookupPolicyData(request, policyData, policyList, controller, resultList))
338 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
341 LOGGER.error("Exception occured while reading policy Data from Policy Version table for Policy Search Data"+e);
344 return new JSONObject().put(RESULT, resultList);
347 private boolean lookupPolicyData(HttpServletRequest request, List<Object> policyData, JSONArray policyList, PolicyController controller, List<JSONObject> resultList) throws ServletException {
349 Set<String> scopes;//Get the Login Id of the User from Request
350 String userId = UserUtils.getUserSession(request).getOrgUserId();
351 List<Object> userRoles = controller.getRoles(userId);
352 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
355 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
356 if(scopes.isEmpty()){
359 Set<String> tempScopes = scopes;
360 for(String scope : tempScopes){
361 addScope(scopes, scope);
364 if(policyList!= null){
365 for(int i = 0; i < policyList.length(); i++){
366 String policyName = policyList.get(i).toString().replace(".xml", "");
367 String version = policyName.substring(policyName.lastIndexOf('.')+1);
368 policyName = policyName.substring(0, policyName.lastIndexOf('.')).replace(".", File.separator);
369 parsePolicyList(resultList, controller, policyName, version);
372 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ){
373 policyData = controller.getData(PolicyVersion.class);
375 List<Object> filterdatas = controller.getData(PolicyVersion.class);
376 for(Object filter : filterdatas) {
377 addFilterData(policyData, scopes, (PolicyVersion) filter);
381 if(!policyData.isEmpty()){
382 updateResultList(policyData, resultList);
388 private void addFilterData(List<Object> policyData, Set<String> scopes, PolicyVersion filter) {
390 String scopeName = filter.getPolicyName().substring(0, filter.getPolicyName().lastIndexOf(File.separator));
391 if(scopes.contains(scopeName)){
392 policyData.add(filter);
395 LOGGER.error("Exception occured while filtering policyversion data"+e);
399 private void updateResultList(List<Object> policyData, List<JSONObject> resultList) {
400 for(int i =0; i < policyData.size(); i++){
401 PolicyVersion policy = (PolicyVersion) policyData.get(i);
402 JSONObject el = new JSONObject();
403 el.put(NAME, policy.getPolicyName().replace(File.separator, "/"));
404 el.put(DATE, policy.getModifiedDate());
405 el.put(VERSION, policy.getActiveVersion());
407 el.put(TYPE, "file");
408 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
409 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
414 private void parsePolicyList(List<JSONObject> resultList, PolicyController controller, String policyName, String version) {
415 if(policyName.contains("\\")){
416 policyName = policyName.replace("\\", "\\\\");
418 String policyVersionQuery = "From PolicyVersion where policy_name = :policyName and active_version = :version and id >0";
419 SimpleBindings pvParams = new SimpleBindings();
420 pvParams.put("policyName", policyName);
421 pvParams.put(VERSION, version);
422 List<Object> activeData = controller.getDataByQuery(policyVersionQuery, pvParams);
423 if(!activeData.isEmpty()){
424 PolicyVersion policy = (PolicyVersion) activeData.get(0);
425 JSONObject el = new JSONObject();
426 el.put(NAME, policy.getPolicyName().replace(File.separator, "/"));
427 el.put(DATE, policy.getModifiedDate());
428 el.put(VERSION, policy.getActiveVersion());
430 el.put(TYPE, "file");
431 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
432 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
437 private void addScope(Set<String> scopes, String scope) {
438 List<Object> scopesList = queryPolicyEditorScopes(scope);
439 if(!scopesList.isEmpty()){
440 for(int i = 0; i < scopesList.size(); i++){
441 PolicyEditorScopes tempScope = (PolicyEditorScopes) scopesList.get(i);
442 scopes.add(tempScope.getScopeName());
447 //Switch Version Functionality
448 private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{
449 String path = params.getString("path");
450 String userId = null;
452 userId = UserUtils.getUserSession(request).getOrgUserId();
453 } catch (Exception e) {
454 LOGGER.error("Exception Occured while reading userid from cookie" +e);
457 String removeExtension = path.replace(".xml", "");
458 if(path.startsWith("/")){
459 policyName = removeExtension.substring(1, removeExtension.lastIndexOf('.'));
461 policyName = removeExtension.substring(0, removeExtension.lastIndexOf('.'));
465 PolicyController controller = getPolicyControllerInstance();
466 if(! params.toString().contains("activeVersion")){
467 return controller.switchVersionPolicyContent(policyName);
469 String activeVersion = params.getString("activeVersion");
470 String highestVersion = params.get("highestVersion").toString();
471 if(Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)){
472 return error("The Version shouldn't be greater than Highest Value");
474 activePolicy = policyName + "." + activeVersion + ".xml";
475 String dbCheckName = activePolicy.replace("/", ".");
476 if(dbCheckName.contains("Config_")){
477 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
478 }else if(dbCheckName.contains("Action_")){
479 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
480 }else if(dbCheckName.contains("Decision_")){
481 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
483 String[] splitDBCheckName = dbCheckName.split(":");
484 String peQuery = "FROM PolicyEntity where policyName = :splitDBCheckName_1 and scope = :splitDBCheckName_0";
485 SimpleBindings policyParams = new SimpleBindings();
486 policyParams.put("splitDBCheckName_1", splitDBCheckName[1]);
487 policyParams.put("splitDBCheckName_0", splitDBCheckName[0]);
488 List<Object> policyEntity = controller.getDataByQuery(peQuery, policyParams);
489 PolicyEntity pentity = (PolicyEntity) policyEntity.get(0);
490 if(pentity.isDeleted()){
491 return error("The Policy is Not Existing in Workspace");
493 if(policyName.contains("/")){
494 policyName = policyName.replace("/", File.separator);
496 policyName = policyName.substring(policyName.indexOf(File.separator)+1);
497 if(policyName.contains("\\")){
498 policyName = policyName.replace(File.separator, "\\");
500 policyName = splitDBCheckName[0].replace(".", File.separator)+File.separator+policyName;
501 String watchPolicyName = policyName;
502 if(policyName.contains("/")){
503 policyName = policyName.replace("/", File.separator);
505 if(policyName.contains("\\")){
506 policyName = policyName.replace("\\", "\\\\");
508 String query = "update PolicyVersion set active_version='"+activeVersion+"' where policy_name ='"+policyName+"' and id >0";
510 controller.executeQuery(query);
511 //Policy Notification
512 PolicyVersion entity = new PolicyVersion();
513 entity.setPolicyName(watchPolicyName);
514 entity.setActiveVersion(Integer.parseInt(activeVersion));
515 entity.setModifiedBy(userId);
516 controller.watchPolicyFunction(entity, activePolicy, "SwitchVersion");
521 private JSONObject describePolicy(JSONObject params) throws ServletException{
522 JSONObject object = null;
523 String path = params.getString("path");
524 String policyName = null;
525 if(path.startsWith("/")){
526 path = path.substring(1);
527 policyName = path.substring(path.lastIndexOf('/') +1);
528 path = path.replace("/", ".");
530 path = path.replace("/", ".");
533 if(path.contains("Config_")){
534 path = path.replace(".Config_", ":Config_");
535 }else if(path.contains("Action_")){
536 path = path.replace(".Action_", ":Action_");
537 }else if(path.contains("Decision_")){
538 path = path.replace(".Decision_", ":Decision_");
540 PolicyController controller = getPolicyControllerInstance();
541 String[] split = path.split(":");
542 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
543 SimpleBindings peParams = new SimpleBindings();
544 peParams.put("split_1", split[1]);
545 peParams.put("split_0", split[0]);
546 List<Object> queryData = null;
547 if(PolicyController.isjUnit()){
548 queryData = controller.getDataByQuery(query, null);
550 queryData = controller.getDataByQuery(query, peParams);
552 if(queryData.isEmpty()){
553 return error("Error Occured while Describing the Policy - query is empty");
555 PolicyEntity entity = (PolicyEntity) queryData.get(0);
558 temp = File.createTempFile(policyName, ".tmp");
559 } catch (IOException e) {
560 String message = "Failed to create temp file " + policyName + ".tmp";
561 LOGGER.error(message + e);
562 return error(message);
564 try (BufferedWriter bw = new BufferedWriter(new FileWriter(temp))) {
565 bw.write(entity.getPolicyData());
566 } catch (IOException e) {
567 LOGGER.error("Exception Occured while Describing the Policy"+e);
569 object = HumanPolicyComponent.DescribePolicy(temp);
572 Files.delete(temp.toPath());
573 } catch (IOException e) {
574 LOGGER.warn("Failed to delete " + temp.getName() + e);
580 //Get the List of Policies and Scopes for Showing in Editor tab
581 private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException {
583 return processPolicyList(params, request);
584 } catch (Exception e) {
585 LOGGER.error("list", e);
586 return error(e.getMessage());
590 private JSONObject processPolicyList(JSONObject params, HttpServletRequest request) throws ServletException {
592 Set<String> scopes;PolicyController controller = getPolicyControllerInstance();
593 //Get the Login Id of the User from Request
594 String testUserID = getTestUserId();
595 String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId();
596 List<Object> userRoles = controller.getRoles(userId);
597 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
601 List<JSONObject> resultList = new ArrayList<>();
602 boolean onlyFolders = params.getBoolean("onlyFolders");
603 String path = params.getString("path");
604 if(path.contains("..xml")){
605 path = path.replaceAll("..xml", "").trim();
608 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
609 if(scopes.isEmpty()){
610 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
612 if(!"/".equals(path)){
613 String tempScope = path.substring(1, path.length());
614 tempScope = tempScope.replace("/", File.separator);
615 scopes.add(tempScope);
620 if (!"/".equals(path)) {
622 String scopeName = path.substring(path.indexOf('/') +1);
623 activePolicyList(scopeName, resultList, roles, scopes, onlyFolders);
624 } catch (Exception ex) {
625 LOGGER.error("Error Occured While reading Policy Files List"+ex );
627 return new JSONObject().put(RESULT, resultList);
630 processRoles(scopes, roles, resultList);
632 return new JSONObject().put(RESULT, resultList);
635 private void processRoles(Set<String> scopes, List<String> roles, List<JSONObject> resultList) {
636 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
637 List<Object> scopesList = queryPolicyEditorScopes(null);
638 for(Object list : scopesList){
639 PolicyEditorScopes scope = (PolicyEditorScopes) list;
640 if(!(scope.getScopeName().contains(File.separator))){
641 JSONObject el = new JSONObject();
642 el.put(NAME, scope.getScopeName());
643 el.put(DATE, scope.getModifiedDate());
646 el.put(CREATED_BY, scope.getUserCreatedBy().getUserName());
647 el.put(MODIFIED_BY, scope.getUserModifiedBy().getUserName());
651 }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){
652 for(Object scope : scopes){
653 JSONObject el = new JSONObject();
654 List<Object> scopesList = queryPolicyEditorScopes(scope.toString());
655 if(!scopesList.isEmpty()){
656 PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
657 el.put(NAME, scopeById.getScopeName());
658 el.put(DATE, scopeById.getModifiedDate());
661 el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName());
662 el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName());
669 private List<Object> queryPolicyEditorScopes(String scopeName){
670 String scopeNamequery;
671 SimpleBindings params = new SimpleBindings();
672 if(scopeName == null){
673 scopeNamequery = "from PolicyEditorScopes";
675 scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
676 params.put("scopeName", scopeName + "%");
678 PolicyController controller = getPolicyControllerInstance();
679 List<Object> scopesList;
680 if(PolicyController.isjUnit()){
681 scopesList = controller.getDataByQuery(scopeNamequery, null);
683 scopesList = controller.getDataByQuery(scopeNamequery, params);
688 //Get Active Policy List based on Scope Selection form Policy Version table
689 private void activePolicyList(String inScopeName, List<JSONObject> resultList, List<String> roles, Set<String> scopes, boolean onlyFolders){
690 PolicyController controller = getPolicyControllerInstance();
691 String scopeName = inScopeName;
692 if(scopeName.contains("/")){
693 scopeName = scopeName.replace("/", File.separator);
695 if(scopeName.contains("\\")){
696 scopeName = scopeName.replace("\\", "\\\\");
698 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
699 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
701 SimpleBindings params = new SimpleBindings();
702 params.put("scopeName", scopeName + "%");
704 List<Object> activePolicies;
705 List<Object> scopesList;
706 if(PolicyController.isjUnit()){
707 activePolicies = controller.getDataByQuery(query, null);
708 scopesList = controller.getDataByQuery(scopeNamequery, null);
710 activePolicies = controller.getDataByQuery(query, params);
711 scopesList = controller.getDataByQuery(scopeNamequery, params);
713 for(Object list : scopesList) {
714 scopeName = checkScope(resultList, scopeName, (PolicyEditorScopes) list);
716 String scopeNameCheck;
717 for (Object list : activePolicies) {
718 PolicyVersion policy = (PolicyVersion) list;
719 String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator));
720 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
721 if(scopeName.contains("\\\\")){
722 scopeNameCheck = scopeName.replace("\\\\", File.separator);
724 scopeNameCheck = scopeName;
726 if(scopeNameValue.equals(scopeNameCheck)){
727 JSONObject el = new JSONObject();
728 el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
729 el.put(DATE, policy.getModifiedDate());
730 el.put(VERSION, policy.getActiveVersion());
732 el.put(TYPE, "file");
733 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
734 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
737 }else if(!scopes.isEmpty() && scopes.contains(scopeNameValue)){
738 JSONObject el = new JSONObject();
739 el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
740 el.put(DATE, policy.getModifiedDate());
741 el.put(VERSION, policy.getActiveVersion());
743 el.put(TYPE, "file");
744 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
745 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
751 private String checkScope(List<JSONObject> resultList, String scopeName, PolicyEditorScopes scopeById) {
752 String scope = scopeById.getScopeName();
753 if(scope.contains(File.separator)){
754 String targetScope = scope.substring(0, scope.lastIndexOf(File.separator));
755 if(scopeName.contains("\\\\")){
756 scopeName = scopeName.replace("\\\\", File.separator);
758 if(scope.contains(File.separator)){
759 scope = scope.substring(targetScope.length()+1);
760 if(scope.contains(File.separator)){
761 scope = scope.substring(0, scope.indexOf(File.separator));
764 if(scopeName.equalsIgnoreCase(targetScope)){
765 JSONObject el = new JSONObject();
767 el.put(DATE, scopeById.getModifiedDate());
770 el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName());
771 el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName());
778 private String getUserName(String loginId){
779 PolicyController controller = getPolicyControllerInstance();
780 UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
781 if(userInfo == null){
784 return userInfo.getUserName();
788 private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
790 return handlePolicyRename(params, request);
791 } catch (Exception e) {
792 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
793 return error(e.getMessage());
797 private JSONObject handlePolicyRename(JSONObject params, HttpServletRequest request) throws ServletException {
798 boolean isActive = false;
799 List<String> policyActiveInPDP = new ArrayList<>();
800 Set<String> scopeOfPolicyActiveInPDP = new HashSet<>();
801 String userId = UserUtils.getUserSession(request).getOrgUserId();
802 String oldPath = params.getString("path");
803 String newPath = params.getString("newPath");
804 oldPath = oldPath.substring(oldPath.indexOf('/')+1);
805 newPath = newPath.substring(newPath.indexOf('/')+1);
806 String checkValidation = null;
807 if(oldPath.endsWith(".xml")){
808 checkValidation = newPath.replace(".xml", "");
809 checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf("."));
810 checkValidation = checkValidation.substring(checkValidation.lastIndexOf("/")+1);
811 if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains("success")){
812 return error("Policy Rename Failed. The Name contains special characters.");
814 JSONObject result = policyRename(oldPath, newPath, userId);
815 if(!(Boolean)(result.getJSONObject("result").get("success"))){
819 String scopeName = oldPath;
820 String newScopeName = newPath;
821 if(scopeName.contains("/")){
822 scopeName = scopeName.replace("/", File.separator);
823 newScopeName = newScopeName.replace("/", File.separator);
825 checkValidation = newScopeName.substring(newScopeName.lastIndexOf(File.separator)+1);
826 if(scopeName.contains("\\")){
827 scopeName = scopeName.replace("\\", "\\\\\\\\");
828 newScopeName = newScopeName.replace("\\", "\\\\\\\\");
830 if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains("success")){
831 return error("Scope Rename Failed. The Name contains special characters.");
833 PolicyController controller = getPolicyControllerInstance();
834 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
835 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
836 SimpleBindings pvParams = new SimpleBindings();
837 pvParams.put("scopeName", scopeName + "%");
838 List<Object> activePolicies = controller.getDataByQuery(query, pvParams);
839 List<Object> scopesList = controller.getDataByQuery(scopeNamequery, pvParams);
840 for(Object object : activePolicies){
841 PolicyVersion activeVersion = (PolicyVersion) object;
842 String policyOldPath = activeVersion.getPolicyName().replace(File.separator, "/") + "." + activeVersion.getActiveVersion() + ".xml";
843 String policyNewPath = policyOldPath.replace(oldPath, newPath);
844 JSONObject result = policyRename(policyOldPath, policyNewPath, userId);
845 if(!(Boolean)(result.getJSONObject("result").get("success"))){
847 policyActiveInPDP.add(policyOldPath);
848 String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf('/'));
849 scopeOfPolicyActiveInPDP.add(scope.replace("/", File.separator));
852 boolean rename = false;
853 if(activePolicies.size() != policyActiveInPDP.size()){
857 UserInfo userInfo = new UserInfo();
858 userInfo.setUserLoginId(userId);
859 if(policyActiveInPDP.isEmpty()){
860 renameScope(scopesList, scopeName, newScopeName, controller);
862 renameScope(scopesList, scopeName, newScopeName, controller);
863 for(String scope : scopeOfPolicyActiveInPDP){
864 PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes();
865 editorScopeEntity.setScopeName(scope.replace("\\", "\\\\\\\\"));
866 editorScopeEntity.setUserCreatedBy(userInfo);
867 editorScopeEntity.setUserModifiedBy(userInfo);
868 controller.saveData(editorScopeEntity);
872 return error("The Following policies rename failed. Since they are active in PDP Groups" +policyActiveInPDP);
878 private void renameScope(List<Object> scopesList, String inScopeName, String newScopeName, PolicyController controller){
879 for(Object object : scopesList){
880 PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object;
881 String scopeName = inScopeName;
882 if(scopeName.contains("\\\\\\\\")){
883 scopeName = scopeName.replace("\\\\\\\\", File.separator);
884 newScopeName = newScopeName.replace("\\\\\\\\", File.separator);
886 String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName);
887 editorScopeEntity.setScopeName(scope);
888 controller.updateData(editorScopeEntity);
892 private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
895 PolicyController controller = getPolicyControllerInstance();
897 String policyVersionName = newPath.replace(".xml", "");
898 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')).replace("/", File.separator);
900 String oldpolicyVersionName = oldPath.replace(".xml", "");
901 String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf('.')).replace("/", File.separator);
903 String newpolicyName = newPath.replace("/", ".");
904 String newPolicyCheck = newpolicyName;
905 if(newPolicyCheck.contains("Config_")){
906 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
907 }else if(newPolicyCheck.contains("Action_")){
908 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
909 }else if(newPolicyCheck.contains("Decision_")){
910 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
912 String[] newPolicySplit = newPolicyCheck.split(":");
914 String orignalPolicyName = oldPath.replace("/", ".");
915 String oldPolicyCheck = orignalPolicyName;
916 if(oldPolicyCheck.contains("Config_")){
917 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
918 }else if(oldPolicyCheck.contains("Action_")){
919 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
920 }else if(oldPolicyCheck.contains("Decision_")){
921 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
923 String[] oldPolicySplit = oldPolicyCheck.split(":");
925 //Check PolicyEntity table with newPolicy Name
926 String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
927 SimpleBindings policyParams = new SimpleBindings();
928 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
929 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
930 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
931 if(!queryData.isEmpty()){
932 return error("Policy rename failed. Since, the policy with same name already exists.");
935 //Query the Policy Entity with oldPolicy Name
936 String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf('.'));
937 String oldpolicyEntityquery = "FROM PolicyEntity where policyName like :policyEntityCheck and scope = :oldPolicySplit_0";
938 SimpleBindings params = new SimpleBindings();
939 params.put("policyEntityCheck", policyEntityCheck + "%");
940 params.put("oldPolicySplit_0", oldPolicySplit[0]);
941 List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery, params);
942 if(!oldEntityData.isEmpty()){
943 StringBuilder groupQuery = new StringBuilder();
944 groupQuery.append("FROM PolicyGroupEntity where (");
945 SimpleBindings geParams = new SimpleBindings();
946 for(int i=0; i<oldEntityData.size(); i++){
947 entity = (PolicyEntity) oldEntityData.get(i);
949 groupQuery.append("policyid = :policyId");
950 geParams.put("policyId", entity.getPolicyId());
952 groupQuery.append(" or policyid = :policyId" + i);
953 geParams.put("policyId" + i, entity.getPolicyId());
956 groupQuery.append(")");
957 List<Object> groupEntityData = controller.getDataByQuery(groupQuery.toString(), geParams);
958 if(! groupEntityData.isEmpty()){
959 return error("Policy rename failed. Since the policy or its version is active in PDP Groups.");
961 for(int i=0; i<oldEntityData.size(); i++){
962 entity = (PolicyEntity) oldEntityData.get(i);
963 String checkEntityName = entity.getPolicyName().replace(".xml", "");
964 checkEntityName = checkEntityName.substring(0, checkEntityName.lastIndexOf('.'));
965 String originalPolicyName = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
966 if(checkEntityName.equals(originalPolicyName)){
967 checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0] , newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
971 return error("Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin.");
975 } catch (Exception e) {
976 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
977 return error(e.getMessage());
981 private JSONObject checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, String oldScope, String removeoldPolicyExtension,
982 String policyName, String newpolicyName, String oldpolicyName, String userId) throws ServletException{
984 ConfigurationDataEntity configEntity = entity.getConfigurationData();
985 ActionBodyEntity actionEntity = entity.getActionBodyEntity();
986 PolicyController controller = getPolicyControllerInstance();
988 String oldPolicyNameWithoutExtension = removeoldPolicyExtension;
989 String newPolicyNameWithoutExtension = removenewPolicyExtension;
990 if(removeoldPolicyExtension.endsWith(".xml")){
991 oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf('.'));
992 newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf('.'));
994 entity.setPolicyName(entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
995 entity.setPolicyData(entity.getPolicyData().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
996 entity.setScope(newScope);
997 entity.setModifiedBy(userId);
999 String oldConfigurationName = null;
1000 String newConfigurationName = null;
1001 if(newpolicyName.contains("Config_")){
1002 oldConfigurationName = configEntity.getConfigurationName();
1003 configEntity.setConfigurationName(configEntity.getConfigurationName().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
1004 controller.updateData(configEntity);
1005 newConfigurationName = configEntity.getConfigurationName();
1006 File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName);
1008 File renamefile = new File(PolicyController.getConfigHome() + File.separator + newConfigurationName);
1009 file.renameTo(renamefile);
1011 }else if(newpolicyName.contains("Action_")){
1012 oldConfigurationName = actionEntity.getActionBodyName();
1013 actionEntity.setActionBody(actionEntity.getActionBody().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
1014 controller.updateData(actionEntity);
1015 newConfigurationName = actionEntity.getActionBodyName();
1016 File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName);
1018 File renamefile = new File(PolicyController.getActionHome() + File.separator + newConfigurationName);
1019 file.renameTo(renamefile);
1022 controller.updateData(entity);
1024 PolicyRestController restController = new PolicyRestController();
1025 restController.notifyOtherPAPSToUpdateConfigurations("rename", newConfigurationName, oldConfigurationName);
1026 PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldpolicyName);
1027 versionEntity.setPolicyName(policyName);
1028 versionEntity.setModifiedBy(userId);
1029 controller.updateData(versionEntity);
1030 String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator)+1);
1031 String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
1032 if(movePolicyCheck.equals(moveOldPolicyCheck)){
1033 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move");
1035 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename");
1038 } catch (Exception e) {
1039 LOGGER.error("Exception Occured"+e);
1040 return error(e.getMessage());
1044 private JSONObject cloneRecord(String newpolicyName, String oldScope, String inRemoveoldPolicyExtension, String newScope, String inRemovenewPolicyExtension, PolicyEntity entity, String userId) throws ServletException{
1045 String queryEntityName;
1046 PolicyController controller = getPolicyControllerInstance();
1047 PolicyEntity cloneEntity = new PolicyEntity();
1048 cloneEntity.setPolicyName(newpolicyName);
1049 String removeoldPolicyExtension = inRemoveoldPolicyExtension;
1050 String removenewPolicyExtension = inRemovenewPolicyExtension;
1051 removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
1052 removenewPolicyExtension = removenewPolicyExtension.replace(".xml", "");
1053 cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope+"."+removeoldPolicyExtension, newScope+"."+removenewPolicyExtension));
1054 cloneEntity.setScope(entity.getScope());
1055 String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
1056 String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
1057 String newConfigurationName = null;
1058 if(newpolicyName.contains("Config_")){
1059 ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
1060 configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1061 queryEntityName = configurationDataEntity.getConfigurationName();
1062 configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody());
1063 configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType());
1064 configurationDataEntity.setDeleted(false);
1065 configurationDataEntity.setCreatedBy(userId);
1066 configurationDataEntity.setModifiedBy(userId);
1067 controller.saveData(configurationDataEntity);
1068 ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
1069 cloneEntity.setConfigurationData(configEntiy);
1070 newConfigurationName = configEntiy.getConfigurationName();
1071 try (FileWriter fw = new FileWriter(PolicyController.getConfigHome() + File.separator + newConfigurationName);
1072 BufferedWriter bw = new BufferedWriter(fw)){
1073 bw.write(configEntiy.getConfigBody());
1074 } catch (IOException e) {
1075 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1077 }else if(newpolicyName.contains("Action_")){
1078 ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
1079 actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1080 queryEntityName = actionBodyEntity.getActionBodyName();
1081 actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody());
1082 actionBodyEntity.setDeleted(false);
1083 actionBodyEntity.setCreatedBy(userId);
1084 actionBodyEntity.setModifiedBy(userId);
1085 controller.saveData(actionBodyEntity);
1086 ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class, "actionBodyName", queryEntityName);
1087 cloneEntity.setActionBodyEntity(actionEntiy);
1088 newConfigurationName = actionEntiy.getActionBodyName();
1089 try (FileWriter fw = new FileWriter(PolicyController.getActionHome() + File.separator + newConfigurationName);
1090 BufferedWriter bw = new BufferedWriter(fw)){
1091 bw.write(actionEntiy.getActionBody());
1092 } catch (IOException e) {
1093 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1097 cloneEntity.setDeleted(entity.isDeleted());
1098 cloneEntity.setCreatedBy(userId);
1099 cloneEntity.setModifiedBy(userId);
1100 controller.saveData(cloneEntity);
1102 //Notify others paps regarding clone policy.
1103 PolicyRestController restController = new PolicyRestController();
1104 restController.notifyOtherPAPSToUpdateConfigurations("clonePolicy", newConfigurationName, null);
1109 private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
1111 String userId = UserUtils.getUserSession(request).getOrgUserId();
1112 String oldPath = params.getString("path");
1113 String newPath = params.getString("newPath");
1114 oldPath = oldPath.substring(oldPath.indexOf('/')+1);
1115 newPath = newPath.substring(newPath.indexOf('/')+1);
1117 String policyVersionName = newPath.replace(".xml", "");
1118 String version = policyVersionName.substring(policyVersionName.indexOf('.')+1);
1119 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')).replace("/", File.separator);
1121 String newpolicyName = newPath.replace("/", ".");
1123 String orignalPolicyName = oldPath.replace("/", ".");
1125 String newPolicyCheck = newpolicyName;
1126 if(newPolicyCheck.contains("Config_")){
1127 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
1128 }else if(newPolicyCheck.contains("Action_")){
1129 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
1130 }else if(newPolicyCheck.contains("Decision_")){
1131 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
1133 if(!newPolicyCheck.contains(":")){
1134 return error("Policy Clone Failed. The Name contains special characters.");
1136 String[] newPolicySplit = newPolicyCheck.split(":");
1138 String checkValidation = newPolicySplit[1].replace(".xml", "");
1139 checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf("."));
1140 if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains("success")){
1141 return error("Policy Clone Failed. The Name contains special characters.");
1144 String oldPolicyCheck = orignalPolicyName;
1145 if(oldPolicyCheck.contains("Config_")){
1146 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
1147 }else if(oldPolicyCheck.contains("Action_")){
1148 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
1149 }else if(oldPolicyCheck.contains("Decision_")){
1150 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
1152 String[] oldPolicySplit = oldPolicyCheck.split(":");
1154 PolicyController controller = getPolicyControllerInstance();
1156 PolicyEntity entity = null;
1157 boolean success = false;
1159 //Check PolicyEntity table with newPolicy Name
1160 String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
1161 SimpleBindings policyParams = new SimpleBindings();
1162 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
1163 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
1164 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
1165 if(!queryData.isEmpty()){
1166 return error("Policy already exists with same name");
1169 //Query the Policy Entity with oldPolicy Name
1170 policyEntityquery = "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0";
1171 SimpleBindings peParams = new SimpleBindings();
1172 peParams.put("oldPolicySplit_1", oldPolicySplit[1]);
1173 peParams.put("oldPolicySplit_0", oldPolicySplit[0]);
1174 if(PolicyController.isjUnit()){
1175 queryData = controller.getDataByQuery(policyEntityquery, null);
1177 queryData = controller.getDataByQuery(policyEntityquery, peParams);
1179 if(!queryData.isEmpty()){
1180 entity = (PolicyEntity) queryData.get(0);
1183 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId);
1188 PolicyVersion entityItem = new PolicyVersion();
1189 entityItem.setActiveVersion(Integer.parseInt(version));
1190 entityItem.setHigherVersion(Integer.parseInt(version));
1191 entityItem.setPolicyName(policyName);
1192 entityItem.setCreatedBy(userId);
1193 entityItem.setModifiedBy(userId);
1194 entityItem.setModifiedDate(new Date());
1195 controller.saveData(entityItem);
1198 LOGGER.debug("copy from: {} to: {}" + oldPath +newPath);
1201 } catch (Exception e) {
1202 LOGGER.error("copy", e);
1203 return error(e.getMessage());
1207 //Delete Policy or Scope Functionality
1208 private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
1209 PolicyController controller = getPolicyControllerInstance();
1210 PolicyRestController restController = new PolicyRestController();
1211 PolicyEntity policyEntity = null;
1212 String policyNamewithoutExtension;
1214 String userId = UserUtils.getUserSession(request).getOrgUserId();
1215 String deleteVersion = "";
1216 String path = params.getString("path");
1217 LOGGER.debug("delete {}" +path);
1218 if(params.has("deleteVersion")){
1219 deleteVersion = params.getString("deleteVersion");
1221 path = path.substring(path.indexOf('/')+1);
1222 String policyNamewithExtension = path.replace("/", File.separator);
1223 String policyVersionName = policyNamewithExtension.replace(".xml", "");
1225 SimpleBindings policyParams = new SimpleBindings();
1226 if(path.endsWith(".xml")){
1227 policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf('.'));
1228 policyNamewithoutExtension = policyNamewithoutExtension.replace(File.separator, ".");
1229 String splitPolicyName = null;
1230 if(policyNamewithoutExtension.contains("Config_")){
1231 splitPolicyName = policyNamewithoutExtension.replace(".Config_", ":Config_");
1232 }else if(policyNamewithoutExtension.contains("Action_")){
1233 splitPolicyName = policyNamewithoutExtension.replace(".Action_", ":Action_");
1234 }else if(policyNamewithoutExtension.contains("Decision_")){
1235 splitPolicyName = policyNamewithoutExtension.replace(".Decision_", ":Decision_");
1237 String[] split = splitPolicyName.split(":");
1239 query = "FROM PolicyEntity where policyName like :split_1 and scope = :split_0";
1240 policyParams.put("split_1", split[1] + "%");
1241 policyParams.put("split_0", split[0]);
1243 policyNamewithoutExtension = path.replace(File.separator, ".");
1244 query = "FROM PolicyEntity where scope like :policyNamewithoutExtension";
1245 policyParams.put("policyNamewithoutExtension", policyNamewithoutExtension + "%");
1248 List<Object> policyEntityobjects = controller.getDataByQuery(query, policyParams);
1249 String activePolicyName = null;
1250 boolean pdpCheck = false;
1251 if(path.endsWith(".xml")){
1252 policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator);
1253 int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf('.')+1));
1254 if("ALL".equals(deleteVersion)){
1255 if(!policyEntityobjects.isEmpty()){
1256 for(Object object : policyEntityobjects){
1257 policyEntity = (PolicyEntity) object;
1258 String groupEntityquery = "from PolicyGroupEntity where policyid ='"+policyEntity.getPolicyId()+"'";
1259 SimpleBindings pgeParams = new SimpleBindings();
1260 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, pgeParams);
1261 if(!groupobject.isEmpty()){
1263 activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName();
1265 //Delete the entity from Elastic Search Database
1266 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1267 restController.deleteElasticData(searchFileName);
1268 //Delete the entity from Policy Entity table
1269 controller.deleteData(policyEntity);
1270 if(policyNamewithoutExtension.contains("Config_")){
1271 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1272 controller.deleteData(policyEntity.getConfigurationData());
1273 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getConfigurationData().getConfigurationName());
1274 }else if(policyNamewithoutExtension.contains("Action_")){
1275 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1276 controller.deleteData(policyEntity.getActionBodyEntity());
1277 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getActionBodyEntity().getActionBodyName());
1282 //Policy Notification
1283 PolicyVersion versionEntity = new PolicyVersion();
1284 versionEntity.setPolicyName(policyNamewithoutExtension);
1285 versionEntity.setModifiedBy(userId);
1286 controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll");
1288 //Delete from policyVersion table
1289 String getActivePDPPolicyVersion = activePolicyName.replace(".xml", "");
1290 getActivePDPPolicyVersion = getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf('.')+1);
1291 String policyVersionQuery = "update PolicyVersion set active_version='"+getActivePDPPolicyVersion+"' , highest_version='"+getActivePDPPolicyVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1292 if(policyVersionQuery != null){
1293 controller.executeQuery(policyVersionQuery);
1295 return error("Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "+activePolicyName);
1297 //No Active Policy in PDP. So, deleting all entries from policyVersion table
1298 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1299 if(policyVersionQuery != null){
1300 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){
1317 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId and policyid > 0";
1318 SimpleBindings geParams = new SimpleBindings();
1319 geParams.put("policyEntityId", policyEntity.getPolicyId());
1320 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1321 if(groupobject.isEmpty()){
1322 //Delete the entity from Elastic Search Database
1323 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1324 restController.deleteElasticData(searchFileName);
1325 //Delete the entity from Policy Entity table
1326 controller.deleteData(policyEntity);
1327 if(policyNamewithoutExtension.contains("Config_")){
1328 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1329 controller.deleteData(policyEntity.getConfigurationData());
1330 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getConfigurationData().getConfigurationName());
1331 }else if(policyNamewithoutExtension.contains("Action_")){
1332 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1333 controller.deleteData(policyEntity.getActionBodyEntity());
1334 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getActionBodyEntity().getActionBodyName());
1338 int highestVersion = 0;
1339 if(!policyEntityobjects.isEmpty()){
1340 for(Object object : policyEntityobjects){
1341 policyEntity = (PolicyEntity) object;
1342 String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
1343 int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf('.')+1));
1344 if(policyEntityVersion > highestVersion && policyEntityVersion != version){
1345 highestVersion = policyEntityVersion;
1350 //Policy Notification
1351 PolicyVersion entity = new PolicyVersion();
1352 entity.setPolicyName(policyNamewithoutExtension);
1353 entity.setActiveVersion(highestVersion);
1354 entity.setModifiedBy(userId);
1355 controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne");
1357 String updatequery = "";
1358 if(highestVersion != 0){
1359 updatequery = "update PolicyVersion set active_version='"+highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"'";
1361 updatequery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1363 controller.executeQuery(updatequery);
1365 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1366 if(policyVersionQuery != null){
1367 controller.executeQuery(policyVersionQuery);
1371 return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'");
1376 List<String> activePoliciesInPDP = new ArrayList<>();
1377 if(!policyEntityobjects.isEmpty()){
1378 for(Object object : policyEntityobjects){
1379 policyEntity = (PolicyEntity) object;
1380 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId";
1381 SimpleBindings geParams = new SimpleBindings();
1382 geParams.put("policyEntityId", policyEntity.getPolicyId());
1383 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1384 if(!groupobject.isEmpty()){
1386 activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName());
1388 //Delete the entity from Elastic Search Database
1389 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1390 restController.deleteElasticData(searchFileName);
1391 //Delete the entity from Policy Entity table
1392 controller.deleteData(policyEntity);
1393 policyNamewithoutExtension = policyEntity.getPolicyName();
1394 if(policyNamewithoutExtension.contains("Config_")){
1395 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1396 controller.deleteData(policyEntity.getConfigurationData());
1397 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getConfigurationData().getConfigurationName());
1398 }else if(policyNamewithoutExtension.contains("Action_")){
1399 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1400 controller.deleteData(policyEntity.getActionBodyEntity());
1401 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getActionBodyEntity().getActionBodyName());
1405 //Delete from policyVersion and policyEditor Scope table
1406 String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1407 controller.executeQuery(policyVersionQuery);
1409 //Policy Notification
1410 PolicyVersion entity = new PolicyVersion();
1411 entity.setPolicyName(path);
1412 entity.setModifiedBy(userId);
1413 controller.watchPolicyFunction(entity, path, "DeleteScope");
1415 //Add Active Policies List to PolicyVersionTable
1416 for(int i =0; i < activePoliciesInPDP.size(); i++){
1417 String activePDPPolicyName = activePoliciesInPDP.get(i).replace(".xml", "");
1418 int activePDPPolicyVersion = Integer.parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf('.')+1));
1419 activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf('.')).replace(".", File.separator);
1420 PolicyVersion insertactivePDPVersion = new PolicyVersion();
1421 insertactivePDPVersion.setPolicyName(activePDPPolicyName);
1422 insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion);
1423 insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion);
1424 insertactivePDPVersion.setCreatedBy(userId);
1425 insertactivePDPVersion.setModifiedBy(userId);
1426 controller.saveData(insertactivePDPVersion);
1429 return error("All the Policies has been deleted in Scope. Except the following list of Policies:"+activePoliciesInPDP);
1431 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1432 controller.executeQuery(policyScopeQuery);
1435 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1436 controller.executeQuery(policyScopeQuery);
1440 } catch (Exception e) {
1441 LOGGER.error("delete", e);
1442 return error(e.getMessage());
1447 private JSONObject editFile(JSONObject params) throws ServletException {
1450 PolicyController controller = getPolicyControllerInstance();
1451 String mode = params.getString("mode");
1452 String path = params.getString("path");
1453 LOGGER.debug("editFile path: {}"+ path);
1455 String domain = path.substring(1, path.lastIndexOf('/'));
1456 domain = domain.replace("/", ".");
1458 path = path.substring(1);
1459 path = path.replace("/", ".");
1460 String dbCheckName = path;
1461 if(dbCheckName.contains("Config_")){
1462 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
1463 }else if(dbCheckName.contains("Action_")){
1464 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
1465 }else if(dbCheckName.contains("Decision_")){
1466 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
1469 String[] split = dbCheckName.split(":");
1470 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
1471 SimpleBindings peParams = new SimpleBindings();
1472 peParams.put("split_1", split[1]);
1473 peParams.put("split_0", split[0]);
1474 List<Object> queryData;
1475 if(PolicyController.isjUnit()){
1476 queryData = controller.getDataByQuery(query, null);
1478 queryData = controller.getDataByQuery(query, peParams);
1480 PolicyEntity entity = (PolicyEntity) queryData.get(0);
1481 InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
1484 Object policy = XACMLPolicyScanner.readPolicy(stream);
1485 PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
1486 policyAdapter.setData(policy);
1488 if("viewPolicy".equalsIgnoreCase(mode)){
1489 policyAdapter.setReadOnly(true);
1490 policyAdapter.setEditPolicy(false);
1492 policyAdapter.setReadOnly(false);
1493 policyAdapter.setEditPolicy(true);
1496 policyAdapter.setDomainDir(domain);
1497 policyAdapter.setPolicyData(policy);
1498 String policyName = path.replace(".xml", "");
1499 policyName = policyName.substring(0, policyName.lastIndexOf('.'));
1500 policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf('.')+1));
1502 PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance();
1503 setpolicyAdapter.configure(policyAdapter,entity);
1505 policyAdapter.setParentPath(null);
1506 ObjectMapper mapper = new ObjectMapper();
1507 String json = mapper.writeValueAsString(policyAdapter);
1508 JsonNode jsonNode = mapper.readTree(json);
1510 return new JSONObject().put(RESULT, jsonNode);
1511 } catch (Exception e) {
1512 LOGGER.error("editFile", e);
1513 return error(e.getMessage());
1518 private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
1519 PolicyController controller = getPolicyControllerInstance();
1522 String userId = UserUtils.getUserSession(request).getOrgUserId();
1523 String path = params.getString("path");
1525 if(params.has("subScopename")){
1526 if(! "".equals(params.getString("subScopename"))) {
1527 name = params.getString("path").replace("/", File.separator) + File.separator +params.getString("subScopename");
1530 name = params.getString(NAME);
1532 }catch(Exception e){
1533 name = params.getString(NAME);
1534 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e);
1536 String validateName;
1537 if(name.contains(File.separator)){
1538 validateName = name.substring(name.lastIndexOf(File.separator)+1);
1540 validateName = name;
1542 if(!name.isEmpty()){
1543 String validate = PolicyUtils.policySpecialCharValidator(validateName);
1544 if(!validate.contains("success")){
1545 return error(validate);
1548 LOGGER.debug("addFolder path: {} name: {}" + path +name);
1549 if(! "".equals(name)){
1550 if(name.startsWith(File.separator)){
1551 name = name.substring(1);
1553 PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, "scopeName", name);
1555 UserInfo userInfo = new UserInfo();
1556 userInfo.setUserLoginId(userId);
1557 PolicyEditorScopes newScope = new PolicyEditorScopes();
1558 newScope.setScopeName(name);
1559 newScope.setUserCreatedBy(userInfo);
1560 newScope.setUserModifiedBy(userInfo);
1561 controller.saveData(newScope);
1563 return error("Scope Already Exists");
1567 } catch (Exception e) {
1568 LOGGER.error("addFolder", e);
1569 return error(e.getMessage());
1573 //Return Error Object
1574 private JSONObject error(String msg) throws ServletException {
1576 JSONObject result = new JSONObject();
1577 result.put("success", false);
1578 result.put("error", msg);
1579 return new JSONObject().put(RESULT, result);
1580 } catch (JSONException e) {
1581 throw new ServletException(e);
1585 //Return Success Object
1586 private JSONObject success() throws ServletException {
1588 JSONObject result = new JSONObject();
1589 result.put("success", true);
1590 result.put("error", (Object) null);
1591 return new JSONObject().put(RESULT, result);
1592 } catch (JSONException e) {
1593 throw new ServletException(e);
1597 private PolicyController getPolicyControllerInstance(){
1598 return policyController != null ? getPolicyController() : new PolicyController();
1601 public String getTestUserId() {
1605 public static void setTestUserId(String testUserId) {
1606 PolicyManagerServlet.testUserId = testUserId;