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;
98 LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT, SEARCHLIST
101 private static PolicyController policyController;
102 public synchronized PolicyController getPolicyController() {
103 return policyController;
106 public static synchronized void setPolicyController(PolicyController policyController) {
107 PolicyManagerServlet.policyController = policyController;
110 private static String CONTENTTYPE = "application/json";
111 private static String SUPERADMIN = "super-admin";
112 private static String SUPEREDITOR = "super-editor";
113 private static String SUPERGUEST = "super-guest";
114 private static String ADMIN = "admin";
115 private static String EDITOR = "editor";
116 private static String GUEST = "guest";
117 private static String RESULT = "result";
119 private static Path closedLoopJsonLocation;
120 private static JsonArray policyNames;
121 private static String testUserId = null;
123 public static JsonArray getPolicyNames() {
127 public static void setPolicyNames(JsonArray policyNames) {
128 PolicyManagerServlet.policyNames = policyNames;
131 private static List<String> serviceTypeNamesList = new ArrayList<>();
133 public static List<String> getServiceTypeNamesList() {
134 return serviceTypeNamesList;
138 public void init(ServletConfig servletConfig) throws ServletException {
139 super.init(servletConfig);
141 // Common initialization
143 XACMLRest.xacmlInit(servletConfig);
145 //Initialize ClosedLoop JSON
147 PolicyManagerServlet.initializeJSONLoad();
150 protected static void initializeJSONLoad() {
151 closedLoopJsonLocation = Paths.get(XACMLProperties
152 .getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP));
153 String location = closedLoopJsonLocation.toString();
154 if (! location.endsWith("json")) {
155 LOGGER.warn("JSONConfig file does not end with extension .json");
158 try (FileInputStream inputStream = new FileInputStream(location);
159 JsonReader jsonReader = Json.createReader(inputStream)) {
160 policyNames = jsonReader.readArray();
161 serviceTypeNamesList = new ArrayList<>();
162 for (int i = 0; i < policyNames.size(); i++) {
163 javax.json.JsonObject policyName = policyNames.getJsonObject(i);
164 String name = policyName.getJsonString("serviceTypePolicyName").getString();
165 serviceTypeNamesList.add(name);
167 } catch (IOException e) {
168 LOGGER.error("Exception Occured while initializing the JSONConfig file"+e);
173 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
174 LOGGER.debug("doPost");
176 // if request contains multipart-form-data
177 if (ServletFileUpload.isMultipartContent(request)) {
178 uploadFile(request, response);
180 // all other post request has json params in body
182 fileOperation(request, response);
184 } catch (Exception e) {
186 setError(e, response);
187 }catch(Exception e1){
188 LOGGER.error("Exception Occured"+e1);
193 //Set Error Message for Exception
194 private void setError(Exception t, HttpServletResponse response) throws IOException {
196 JSONObject responseJsonObject = error(t.getMessage());
197 response.setContentType(CONTENTTYPE);
198 PrintWriter out = response.getWriter();
199 out.print(responseJsonObject);
201 } catch (Exception x) {
202 LOGGER.error("Exception Occured"+x);
203 response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage());
207 //Policy Import Functionality
208 private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException {
211 Map<String, InputStream> files = new HashMap<>();
213 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
214 for (FileItem item : items) {
215 if (!item.isFormField()) {
216 // Process form file field (input type="file").
217 files.put(item.getName(), item.getInputStream());
218 processFormFile(request, item);
222 JSONObject responseJsonObject;
223 responseJsonObject = this.success();
224 response.setContentType(CONTENTTYPE);
225 PrintWriter out = response.getWriter();
226 out.print(responseJsonObject);
228 } catch (Exception e) {
229 LOGGER.debug("Cannot write file");
230 throw new ServletException("Cannot write file", e);
234 private void processFormFile(HttpServletRequest request, FileItem item) {
236 if(item.getName().endsWith(".xls") && item.getSize() <= PolicyController.getFileSizeLimit()){
237 File file = new File(item.getName());
238 try (OutputStream outputStream = new FileOutputStream(file);)
240 IOUtils.copy(item.getInputStream(), outputStream);
241 newFile = file.toString();
242 PolicyExportAndImportController importController = new PolicyExportAndImportController();
243 importController.importRepositoryFile(newFile, request);
245 LOGGER.error("Upload error : " + e);
248 else if (!item.getName().endsWith(".xls")) {
249 LOGGER.error("Non .xls filetype uploaded: " + item.getName());
251 else { //uploaded file size is greater than allowed
252 LOGGER.error("Upload file size limit exceeded! File size (Bytes) is: " + item.getSize());
256 //File Operation Functionality
257 private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
258 JSONObject responseJsonObject = null;
260 StringBuilder sb = new StringBuilder();
261 BufferedReader br = request.getReader();
263 while ((str = br.readLine()) != null) {
267 JSONObject jObj = new JSONObject(sb.toString());
268 JSONObject params = jObj.getJSONObject("params");
269 Mode mode = Mode.valueOf(params.getString("mode"));
271 String userId = UserUtils.getUserSession(request).getOrgUserId();
272 LOGGER.info("****************************************Logging UserID while doing actions on Editor tab*******************************************");
273 LOGGER.info("UserId: " + userId + "Action Mode: "+ mode.toString() + "Action Params: "+params.toString());
274 LOGGER.info("***********************************************************************************************************************************");
279 responseJsonObject = addFolder(params, request);
282 responseJsonObject = copy(params, request);
285 responseJsonObject = delete(params, request);
289 responseJsonObject = editFile(params);
292 responseJsonObject = list(params, request);
295 responseJsonObject = rename(params, request);
297 case DESCRIBEPOLICYFILE:
298 responseJsonObject = describePolicy(params);
301 responseJsonObject = switchVersion(params, request);
304 responseJsonObject = searchPolicyList(params, request);
307 throw new ServletException("not implemented");
309 if (responseJsonObject == null) {
310 responseJsonObject = error("generic error : responseJsonObject is null");
312 } catch (Exception e) {
313 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While doing File Operation" + e);
314 responseJsonObject = error(e.getMessage());
316 response.setContentType(CONTENTTYPE);
317 PrintWriter out = response.getWriter();
318 out.print(responseJsonObject);
322 private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) {
325 List<Object> policyData = new ArrayList<>();
326 JSONArray policyList = null;
327 if(params.has("policyList")){
328 policyList = (JSONArray) params.get("policyList");
330 PolicyController controller = getPolicyControllerInstance();
331 List<JSONObject> resultList = new ArrayList<>();
333 //Get the Login Id of the User from Request
334 String userId = UserUtils.getUserSession(request).getOrgUserId();
335 List<Object> userRoles = controller.getRoles(userId);
336 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
339 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
340 if(scopes.isEmpty()){
341 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
343 Set<String> tempScopes = scopes;
344 for(String scope : tempScopes){
345 addScope(scopes, scope);
348 if(policyList!= null){
349 for(int i = 0; i < policyList.length(); i++){
350 String policyName = policyList.get(i).toString().replace(".xml", "");
351 String version = policyName.substring(policyName.lastIndexOf('.')+1);
352 policyName = policyName.substring(0, policyName.lastIndexOf('.')).replace(".", File.separator);
353 parsePolicyList(resultList, controller, policyName, version);
356 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ){
357 policyData = controller.getData(PolicyVersion.class);
359 List<Object> filterdatas = controller.getData(PolicyVersion.class);
360 for(Object filter : filterdatas){
361 PolicyVersion filterdata = (PolicyVersion) filter;
363 String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator));
364 if(scopes.contains(scopeName)){
365 policyData.add(filterdata);
368 LOGGER.error("Exception occured while filtering policyversion data"+e);
373 if(!policyData.isEmpty()){
374 updateResultList(policyData, resultList);
378 LOGGER.error("Exception occured while reading policy Data from Policy Version table for Policy Search Data"+e);
381 return new JSONObject().put(RESULT, resultList);
384 private void updateResultList(List<Object> policyData, List<JSONObject> resultList) {
385 for(int i =0; i < policyData.size(); i++){
386 PolicyVersion policy = (PolicyVersion) policyData.get(i);
387 JSONObject el = new JSONObject();
388 el.put("name", policy.getPolicyName().replace(File.separator, "/"));
389 el.put("date", policy.getModifiedDate());
390 el.put("version", policy.getActiveVersion());
392 el.put("type", "file");
393 el.put("createdBy", getUserName(policy.getCreatedBy()));
394 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
399 private void parsePolicyList(List<JSONObject> resultList, PolicyController controller, String policyName, String version) {
400 if(policyName.contains("\\")){
401 policyName = policyName.replace("\\", "\\\\");
403 String policyVersionQuery = "From PolicyVersion where policy_name = :policyName and active_version = :version and id >0";
404 SimpleBindings pvParams = new SimpleBindings();
405 pvParams.put("policyName", policyName);
406 pvParams.put("version", version);
407 List<Object> activeData = controller.getDataByQuery(policyVersionQuery, pvParams);
408 if(!activeData.isEmpty()){
409 PolicyVersion policy = (PolicyVersion) activeData.get(0);
410 JSONObject el = new JSONObject();
411 el.put("name", policy.getPolicyName().replace(File.separator, "/"));
412 el.put("date", policy.getModifiedDate());
413 el.put("version", policy.getActiveVersion());
415 el.put("type", "file");
416 el.put("createdBy", getUserName(policy.getCreatedBy()));
417 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
422 private void addScope(Set<String> scopes, String scope) {
423 List<Object> scopesList = queryPolicyEditorScopes(scope);
424 if(!scopesList.isEmpty()){
425 for(int i = 0; i < scopesList.size(); i++){
426 PolicyEditorScopes tempScope = (PolicyEditorScopes) scopesList.get(i);
427 scopes.add(tempScope.getScopeName());
432 //Switch Version Functionality
433 private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{
434 String path = params.getString("path");
435 String userId = null;
437 userId = UserUtils.getUserSession(request).getOrgUserId();
438 } catch (Exception e) {
439 LOGGER.error("Exception Occured while reading userid from cookie" +e);
442 String removeExtension = path.replace(".xml", "");
443 if(path.startsWith("/")){
444 policyName = removeExtension.substring(1, removeExtension.lastIndexOf('.'));
446 policyName = removeExtension.substring(0, removeExtension.lastIndexOf('.'));
450 PolicyController controller = getPolicyControllerInstance();
451 if(! params.toString().contains("activeVersion")){
452 return controller.switchVersionPolicyContent(policyName);
454 String activeVersion = params.getString("activeVersion");
455 String highestVersion = params.get("highestVersion").toString();
456 if(Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)){
457 return error("The Version shouldn't be greater than Highest Value");
459 activePolicy = policyName + "." + activeVersion + ".xml";
460 String dbCheckName = activePolicy.replace("/", ".");
461 if(dbCheckName.contains("Config_")){
462 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
463 }else if(dbCheckName.contains("Action_")){
464 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
465 }else if(dbCheckName.contains("Decision_")){
466 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
468 String[] splitDBCheckName = dbCheckName.split(":");
469 String peQuery = "FROM PolicyEntity where policyName = :splitDBCheckName_1 and scope = :splitDBCheckName_0";
470 SimpleBindings policyParams = new SimpleBindings();
471 policyParams.put("splitDBCheckName_1", splitDBCheckName[1]);
472 policyParams.put("splitDBCheckName_0", splitDBCheckName[0]);
473 List<Object> policyEntity = controller.getDataByQuery(peQuery, policyParams);
474 PolicyEntity pentity = (PolicyEntity) policyEntity.get(0);
475 if(pentity.isDeleted()){
476 return error("The Policy is Not Existing in Workspace");
478 if(policyName.contains("/")){
479 policyName = policyName.replace("/", File.separator);
481 policyName = policyName.substring(policyName.indexOf(File.separator)+1);
482 if(policyName.contains("\\")){
483 policyName = policyName.replace(File.separator, "\\");
485 policyName = splitDBCheckName[0].replace(".", File.separator)+File.separator+policyName;
486 String watchPolicyName = policyName;
487 if(policyName.contains("/")){
488 policyName = policyName.replace("/", File.separator);
490 if(policyName.contains("\\")){
491 policyName = policyName.replace("\\", "\\\\");
493 String query = "update PolicyVersion set active_version='"+activeVersion+"' where policy_name ='"+policyName+"' and id >0";
495 controller.executeQuery(query);
496 //Policy Notification
497 PolicyVersion entity = new PolicyVersion();
498 entity.setPolicyName(watchPolicyName);
499 entity.setActiveVersion(Integer.parseInt(activeVersion));
500 entity.setModifiedBy(userId);
501 controller.watchPolicyFunction(entity, activePolicy, "SwitchVersion");
506 private JSONObject describePolicy(JSONObject params) throws ServletException{
507 JSONObject object = null;
508 String path = params.getString("path");
509 String policyName = null;
510 if(path.startsWith("/")){
511 path = path.substring(1);
512 policyName = path.substring(path.lastIndexOf('/') +1);
513 path = path.replace("/", ".");
515 path = path.replace("/", ".");
518 if(path.contains("Config_")){
519 path = path.replace(".Config_", ":Config_");
520 }else if(path.contains("Action_")){
521 path = path.replace(".Action_", ":Action_");
522 }else if(path.contains("Decision_")){
523 path = path.replace(".Decision_", ":Decision_");
525 PolicyController controller = getPolicyControllerInstance();
526 String[] split = path.split(":");
527 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
528 SimpleBindings peParams = new SimpleBindings();
529 peParams.put("split_1", split[1]);
530 peParams.put("split_0", split[0]);
531 List<Object> queryData = null;
532 if(PolicyController.isjUnit()){
533 queryData = controller.getDataByQuery(query, null);
535 queryData = controller.getDataByQuery(query, peParams);
537 if(queryData.isEmpty()){
538 return error("Error Occured while Describing the Policy - query is empty");
540 PolicyEntity entity = (PolicyEntity) queryData.get(0);
543 temp = File.createTempFile(policyName, ".tmp");
544 } catch (IOException e) {
545 String message = "Failed to create temp file " + policyName + ".tmp";
546 LOGGER.error(message + e);
547 return error(message);
549 try (BufferedWriter bw = new BufferedWriter(new FileWriter(temp))) {
550 bw.write(entity.getPolicyData());
551 } catch (IOException e) {
552 LOGGER.error("Exception Occured while Describing the Policy"+e);
554 object = HumanPolicyComponent.DescribePolicy(temp);
557 Files.delete(temp.toPath());
558 } catch (IOException e) {
559 LOGGER.warn("Failed to delete " + temp.getName() + e);
565 //Get the List of Policies and Scopes for Showing in Editor tab
566 private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException {
567 Set<String> scopes = null;
568 List<String> roles = null;
570 PolicyController controller = getPolicyControllerInstance();
571 //Get the Login Id of the User from Request
572 String testUserID = getTestUserId();
573 String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId();
574 List<Object> userRoles = controller.getRoles(userId);
575 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
579 List<JSONObject> resultList = new ArrayList<>();
580 boolean onlyFolders = params.getBoolean("onlyFolders");
581 String path = params.getString("path");
582 if(path.contains("..xml")){
583 path = path.replaceAll("..xml", "").trim();
586 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
587 if(scopes.isEmpty()){
588 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
590 if(!"/".equals(path)){
591 String tempScope = path.substring(1, path.length());
592 tempScope = tempScope.replace("/", File.separator);
593 scopes.add(tempScope);
598 if("/".equals(path)){
599 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
600 List<Object> scopesList = queryPolicyEditorScopes(null);
601 for(Object list : scopesList){
602 PolicyEditorScopes scope = (PolicyEditorScopes) list;
603 if(!(scope.getScopeName().contains(File.separator))){
604 JSONObject el = new JSONObject();
605 el.put("name", scope.getScopeName());
606 el.put("date", scope.getModifiedDate());
608 el.put("type", "dir");
609 el.put("createdBy", scope.getUserCreatedBy().getUserName());
610 el.put("modifiedBy", scope.getUserModifiedBy().getUserName());
614 }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){
615 for(Object scope : scopes){
616 JSONObject el = new JSONObject();
617 List<Object> scopesList = queryPolicyEditorScopes(scope.toString());
618 if(!scopesList.isEmpty()){
619 PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
620 el.put("name", scopeById.getScopeName());
621 el.put("date", scopeById.getModifiedDate());
623 el.put("type", "dir");
624 el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
625 el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
632 String scopeName = path.substring(path.indexOf('/') +1);
633 activePolicyList(scopeName, resultList, roles, scopes, onlyFolders);
634 } catch (Exception ex) {
635 LOGGER.error("Error Occured While reading Policy Files List"+ex );
639 return new JSONObject().put(RESULT, resultList);
640 } catch (Exception e) {
641 LOGGER.error("list", e);
642 return error(e.getMessage());
646 private List<Object> queryPolicyEditorScopes(String scopeName){
647 String scopeNamequery;
648 SimpleBindings params = new SimpleBindings();
649 if(scopeName == null){
650 scopeNamequery = "from PolicyEditorScopes";
652 scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
653 params.put("scopeName", scopeName + "%");
655 PolicyController controller = getPolicyControllerInstance();
656 List<Object> scopesList;
657 if(PolicyController.isjUnit()){
658 scopesList = controller.getDataByQuery(scopeNamequery, null);
660 scopesList = controller.getDataByQuery(scopeNamequery, params);
665 //Get Active Policy List based on Scope Selection form Policy Version table
666 private void activePolicyList(String inScopeName, List<JSONObject> resultList, List<String> roles, Set<String> scopes, boolean onlyFolders){
667 PolicyController controller = getPolicyControllerInstance();
668 String scopeName = inScopeName;
669 if(scopeName.contains("/")){
670 scopeName = scopeName.replace("/", File.separator);
672 if(scopeName.contains("\\")){
673 scopeName = scopeName.replace("\\", "\\\\");
675 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
676 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
678 SimpleBindings params = new SimpleBindings();
679 params.put("scopeName", scopeName + "%");
681 List<Object> activePolicies;
682 List<Object> scopesList;
683 if(PolicyController.isjUnit()){
684 activePolicies = controller.getDataByQuery(query, null);
685 scopesList = controller.getDataByQuery(scopeNamequery, null);
687 activePolicies = controller.getDataByQuery(query, params);
688 scopesList = controller.getDataByQuery(scopeNamequery, params);
690 for(Object list : scopesList){
691 PolicyEditorScopes scopeById = (PolicyEditorScopes) list;
692 String scope = scopeById.getScopeName();
693 if(scope.contains(File.separator)){
694 String checkScope = scope.substring(0, scope.lastIndexOf(File.separator));
695 if(scopeName.contains("\\\\")){
696 scopeName = scopeName.replace("\\\\", File.separator);
698 if(scope.contains(File.separator)){
699 scope = scope.substring(checkScope.length()+1);
700 if(scope.contains(File.separator)){
701 scope = scope.substring(0, scope.indexOf(File.separator));
704 if(scopeName.equalsIgnoreCase(checkScope)){
705 JSONObject el = new JSONObject();
706 el.put("name", scope);
707 el.put("date", scopeById.getModifiedDate());
709 el.put("type", "dir");
710 el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
711 el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
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("createdBy", getUserName(policy.getCreatedBy()));
734 el.put("modifiedBy", 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("createdBy", getUserName(policy.getCreatedBy()));
745 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
751 private String getUserName(String loginId){
752 PolicyController controller = getPolicyControllerInstance();
753 UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
754 if(userInfo == null){
757 return userInfo.getUserName();
761 private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
763 boolean isActive = false;
764 List<String> policyActiveInPDP = new ArrayList<>();
765 Set<String> scopeOfPolicyActiveInPDP = new HashSet<>();
766 String userId = UserUtils.getUserSession(request).getOrgUserId();
767 String oldPath = params.getString("path");
768 String newPath = params.getString("newPath");
769 oldPath = oldPath.substring(oldPath.indexOf('/')+1);
770 newPath = newPath.substring(newPath.indexOf('/')+1);
771 String checkValidation = null;
772 if(oldPath.endsWith(".xml")){
773 checkValidation = newPath.replace(".xml", "");
774 checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf("."));
775 checkValidation = checkValidation.substring(checkValidation.lastIndexOf("/")+1);
776 if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains("success")){
777 return error("Policy Rename Failed. The Name contains special characters.");
779 JSONObject result = policyRename(oldPath, newPath, userId);
780 if(!(Boolean)(result.getJSONObject("result").get("success"))){
784 String scopeName = oldPath;
785 String newScopeName = newPath;
786 if(scopeName.contains("/")){
787 scopeName = scopeName.replace("/", File.separator);
788 newScopeName = newScopeName.replace("/", File.separator);
790 checkValidation = newScopeName.substring(newScopeName.lastIndexOf(File.separator)+1);
791 if(scopeName.contains("\\")){
792 scopeName = scopeName.replace("\\", "\\\\\\\\");
793 newScopeName = newScopeName.replace("\\", "\\\\\\\\");
795 if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains("success")){
796 return error("Scope Rename Failed. The Name contains special characters.");
798 PolicyController controller = getPolicyControllerInstance();
799 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
800 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
801 SimpleBindings pvParams = new SimpleBindings();
802 pvParams.put("scopeName", scopeName + "%");
803 List<Object> activePolicies = controller.getDataByQuery(query, pvParams);
804 List<Object> scopesList = controller.getDataByQuery(scopeNamequery, pvParams);
805 for(Object object : activePolicies){
806 PolicyVersion activeVersion = (PolicyVersion) object;
807 String policyOldPath = activeVersion.getPolicyName().replace(File.separator, "/") + "." + activeVersion.getActiveVersion() + ".xml";
808 String policyNewPath = policyOldPath.replace(oldPath, newPath);
809 JSONObject result = policyRename(policyOldPath, policyNewPath, userId);
810 if(!(Boolean)(result.getJSONObject("result").get("success"))){
812 policyActiveInPDP.add(policyOldPath);
813 String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf('/'));
814 scopeOfPolicyActiveInPDP.add(scope.replace("/", File.separator));
817 boolean rename = false;
818 if(activePolicies.size() != policyActiveInPDP.size()){
822 UserInfo userInfo = new UserInfo();
823 userInfo.setUserLoginId(userId);
824 if(policyActiveInPDP.isEmpty()){
825 renameScope(scopesList, scopeName, newScopeName, controller);
827 renameScope(scopesList, scopeName, newScopeName, controller);
828 for(String scope : scopeOfPolicyActiveInPDP){
829 PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes();
830 editorScopeEntity.setScopeName(scope.replace("\\", "\\\\\\\\"));
831 editorScopeEntity.setUserCreatedBy(userInfo);
832 editorScopeEntity.setUserModifiedBy(userInfo);
833 controller.saveData(editorScopeEntity);
837 return error("The Following policies rename failed. Since they are active in PDP Groups" +policyActiveInPDP);
841 } catch (Exception e) {
842 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
843 return error(e.getMessage());
847 private void renameScope(List<Object> scopesList, String inScopeName, String newScopeName, PolicyController controller){
848 for(Object object : scopesList){
849 PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object;
850 String scopeName = inScopeName;
851 if(scopeName.contains("\\\\\\\\")){
852 scopeName = scopeName.replace("\\\\\\\\", File.separator);
853 newScopeName = newScopeName.replace("\\\\\\\\", File.separator);
855 String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName);
856 editorScopeEntity.setScopeName(scope);
857 controller.updateData(editorScopeEntity);
861 private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
864 PolicyController controller = getPolicyControllerInstance();
866 String policyVersionName = newPath.replace(".xml", "");
867 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')).replace("/", File.separator);
869 String oldpolicyVersionName = oldPath.replace(".xml", "");
870 String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf('.')).replace("/", File.separator);
872 String newpolicyName = newPath.replace("/", ".");
873 String newPolicyCheck = newpolicyName;
874 if(newPolicyCheck.contains("Config_")){
875 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
876 }else if(newPolicyCheck.contains("Action_")){
877 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
878 }else if(newPolicyCheck.contains("Decision_")){
879 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
881 String[] newPolicySplit = newPolicyCheck.split(":");
883 String orignalPolicyName = oldPath.replace("/", ".");
884 String oldPolicyCheck = orignalPolicyName;
885 if(oldPolicyCheck.contains("Config_")){
886 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
887 }else if(oldPolicyCheck.contains("Action_")){
888 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
889 }else if(oldPolicyCheck.contains("Decision_")){
890 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
892 String[] oldPolicySplit = oldPolicyCheck.split(":");
894 //Check PolicyEntity table with newPolicy Name
895 String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
896 SimpleBindings policyParams = new SimpleBindings();
897 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
898 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
899 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
900 if(!queryData.isEmpty()){
901 return error("Policy rename failed. Since, the policy with same name already exists.");
904 //Query the Policy Entity with oldPolicy Name
905 String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf('.'));
906 String oldpolicyEntityquery = "FROM PolicyEntity where policyName like :policyEntityCheck and scope = :oldPolicySplit_0";
907 SimpleBindings params = new SimpleBindings();
908 params.put("policyEntityCheck", policyEntityCheck + "%");
909 params.put("oldPolicySplit_0", oldPolicySplit[0]);
910 List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery, params);
911 if(!oldEntityData.isEmpty()){
912 StringBuilder groupQuery = new StringBuilder();
913 groupQuery.append("FROM PolicyGroupEntity where (");
914 SimpleBindings geParams = new SimpleBindings();
915 for(int i=0; i<oldEntityData.size(); i++){
916 entity = (PolicyEntity) oldEntityData.get(i);
918 groupQuery.append("policyid = :policyId");
919 geParams.put("policyId", entity.getPolicyId());
921 groupQuery.append(" or policyid = :policyId" + i);
922 geParams.put("policyId" + i, entity.getPolicyId());
925 groupQuery.append(")");
926 List<Object> groupEntityData = controller.getDataByQuery(groupQuery.toString(), geParams);
927 if(! groupEntityData.isEmpty()){
928 return error("Policy rename failed. Since the policy or its version is active in PDP Groups.");
930 for(int i=0; i<oldEntityData.size(); i++){
931 entity = (PolicyEntity) oldEntityData.get(i);
932 String checkEntityName = entity.getPolicyName().replace(".xml", "");
933 checkEntityName = checkEntityName.substring(0, checkEntityName.lastIndexOf('.'));
934 String originalPolicyName = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
935 if(checkEntityName.equals(originalPolicyName)){
936 checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0] , newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
940 return error("Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin.");
944 } catch (Exception e) {
945 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
946 return error(e.getMessage());
950 private JSONObject checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, String oldScope, String removeoldPolicyExtension,
951 String policyName, String newpolicyName, String oldpolicyName, String userId) throws ServletException{
953 ConfigurationDataEntity configEntity = entity.getConfigurationData();
954 ActionBodyEntity actionEntity = entity.getActionBodyEntity();
955 PolicyController controller = getPolicyControllerInstance();
957 String oldPolicyNameWithoutExtension = removeoldPolicyExtension;
958 String newPolicyNameWithoutExtension = removenewPolicyExtension;
959 if(removeoldPolicyExtension.endsWith(".xml")){
960 oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf('.'));
961 newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf('.'));
963 entity.setPolicyName(entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
964 entity.setPolicyData(entity.getPolicyData().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
965 entity.setScope(newScope);
966 entity.setModifiedBy(userId);
968 String oldConfigurationName = null;
969 String newConfigurationName = null;
970 if(newpolicyName.contains("Config_")){
971 oldConfigurationName = configEntity.getConfigurationName();
972 configEntity.setConfigurationName(configEntity.getConfigurationName().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
973 controller.updateData(configEntity);
974 newConfigurationName = configEntity.getConfigurationName();
975 File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName);
977 File renamefile = new File(PolicyController.getConfigHome() + File.separator + newConfigurationName);
978 file.renameTo(renamefile);
980 }else if(newpolicyName.contains("Action_")){
981 oldConfigurationName = actionEntity.getActionBodyName();
982 actionEntity.setActionBody(actionEntity.getActionBody().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
983 controller.updateData(actionEntity);
984 newConfigurationName = actionEntity.getActionBodyName();
985 File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName);
987 File renamefile = new File(PolicyController.getActionHome() + File.separator + newConfigurationName);
988 file.renameTo(renamefile);
991 controller.updateData(entity);
993 PolicyRestController restController = new PolicyRestController();
994 restController.notifyOtherPAPSToUpdateConfigurations("rename", newConfigurationName, oldConfigurationName);
995 PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldpolicyName);
996 versionEntity.setPolicyName(policyName);
997 versionEntity.setModifiedBy(userId);
998 controller.updateData(versionEntity);
999 String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator)+1);
1000 String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
1001 if(movePolicyCheck.equals(moveOldPolicyCheck)){
1002 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move");
1004 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename");
1007 } catch (Exception e) {
1008 LOGGER.error("Exception Occured"+e);
1009 return error(e.getMessage());
1013 private JSONObject cloneRecord(String newpolicyName, String oldScope, String inRemoveoldPolicyExtension, String newScope, String inRemovenewPolicyExtension, PolicyEntity entity, String userId) throws ServletException{
1014 String queryEntityName;
1015 PolicyController controller = getPolicyControllerInstance();
1016 PolicyEntity cloneEntity = new PolicyEntity();
1017 cloneEntity.setPolicyName(newpolicyName);
1018 String removeoldPolicyExtension = inRemoveoldPolicyExtension;
1019 String removenewPolicyExtension = inRemovenewPolicyExtension;
1020 removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
1021 removenewPolicyExtension = removenewPolicyExtension.replace(".xml", "");
1022 cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope+"."+removeoldPolicyExtension, newScope+"."+removenewPolicyExtension));
1023 cloneEntity.setScope(entity.getScope());
1024 String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
1025 String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
1026 String newConfigurationName = null;
1027 if(newpolicyName.contains("Config_")){
1028 ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
1029 configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1030 queryEntityName = configurationDataEntity.getConfigurationName();
1031 configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody());
1032 configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType());
1033 configurationDataEntity.setDeleted(false);
1034 configurationDataEntity.setCreatedBy(userId);
1035 configurationDataEntity.setModifiedBy(userId);
1036 controller.saveData(configurationDataEntity);
1037 ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
1038 cloneEntity.setConfigurationData(configEntiy);
1039 newConfigurationName = configEntiy.getConfigurationName();
1040 try (FileWriter fw = new FileWriter(PolicyController.getConfigHome() + File.separator + newConfigurationName);
1041 BufferedWriter bw = new BufferedWriter(fw)){
1042 bw.write(configEntiy.getConfigBody());
1043 } catch (IOException e) {
1044 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1046 }else if(newpolicyName.contains("Action_")){
1047 ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
1048 actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1049 queryEntityName = actionBodyEntity.getActionBodyName();
1050 actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody());
1051 actionBodyEntity.setDeleted(false);
1052 actionBodyEntity.setCreatedBy(userId);
1053 actionBodyEntity.setModifiedBy(userId);
1054 controller.saveData(actionBodyEntity);
1055 ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class, "actionBodyName", queryEntityName);
1056 cloneEntity.setActionBodyEntity(actionEntiy);
1057 newConfigurationName = actionEntiy.getActionBodyName();
1058 try (FileWriter fw = new FileWriter(PolicyController.getActionHome() + File.separator + newConfigurationName);
1059 BufferedWriter bw = new BufferedWriter(fw)){
1060 bw.write(actionEntiy.getActionBody());
1061 } catch (IOException e) {
1062 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1066 cloneEntity.setDeleted(entity.isDeleted());
1067 cloneEntity.setCreatedBy(userId);
1068 cloneEntity.setModifiedBy(userId);
1069 controller.saveData(cloneEntity);
1071 //Notify others paps regarding clone policy.
1072 PolicyRestController restController = new PolicyRestController();
1073 restController.notifyOtherPAPSToUpdateConfigurations("clonePolicy", newConfigurationName, null);
1078 private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
1080 String userId = UserUtils.getUserSession(request).getOrgUserId();
1081 String oldPath = params.getString("path");
1082 String newPath = params.getString("newPath");
1083 oldPath = oldPath.substring(oldPath.indexOf('/')+1);
1084 newPath = newPath.substring(newPath.indexOf('/')+1);
1086 String policyVersionName = newPath.replace(".xml", "");
1087 String version = policyVersionName.substring(policyVersionName.indexOf('.')+1);
1088 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')).replace("/", File.separator);
1090 String newpolicyName = newPath.replace("/", ".");
1092 String orignalPolicyName = oldPath.replace("/", ".");
1094 String newPolicyCheck = newpolicyName;
1095 if(newPolicyCheck.contains("Config_")){
1096 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
1097 }else if(newPolicyCheck.contains("Action_")){
1098 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
1099 }else if(newPolicyCheck.contains("Decision_")){
1100 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
1102 if(!newPolicyCheck.contains(":")){
1103 return error("Policy Clone Failed. The Name contains special characters.");
1105 String[] newPolicySplit = newPolicyCheck.split(":");
1107 String checkValidation = newPolicySplit[1].replace(".xml", "");
1108 checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf("."));
1109 if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains("success")){
1110 return error("Policy Clone Failed. The Name contains special characters.");
1113 String oldPolicyCheck = orignalPolicyName;
1114 if(oldPolicyCheck.contains("Config_")){
1115 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
1116 }else if(oldPolicyCheck.contains("Action_")){
1117 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
1118 }else if(oldPolicyCheck.contains("Decision_")){
1119 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
1121 String[] oldPolicySplit = oldPolicyCheck.split(":");
1123 PolicyController controller = getPolicyControllerInstance();
1125 PolicyEntity entity = null;
1126 boolean success = false;
1128 //Check PolicyEntity table with newPolicy Name
1129 String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
1130 SimpleBindings policyParams = new SimpleBindings();
1131 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
1132 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
1133 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
1134 if(!queryData.isEmpty()){
1135 return error("Policy already exists with same name");
1138 //Query the Policy Entity with oldPolicy Name
1139 policyEntityquery = "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0";
1140 SimpleBindings peParams = new SimpleBindings();
1141 peParams.put("oldPolicySplit_1", oldPolicySplit[1]);
1142 peParams.put("oldPolicySplit_0", oldPolicySplit[0]);
1143 if(PolicyController.isjUnit()){
1144 queryData = controller.getDataByQuery(policyEntityquery, null);
1146 queryData = controller.getDataByQuery(policyEntityquery, peParams);
1148 if(!queryData.isEmpty()){
1149 entity = (PolicyEntity) queryData.get(0);
1152 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId);
1157 PolicyVersion entityItem = new PolicyVersion();
1158 entityItem.setActiveVersion(Integer.parseInt(version));
1159 entityItem.setHigherVersion(Integer.parseInt(version));
1160 entityItem.setPolicyName(policyName);
1161 entityItem.setCreatedBy(userId);
1162 entityItem.setModifiedBy(userId);
1163 entityItem.setModifiedDate(new Date());
1164 controller.saveData(entityItem);
1167 LOGGER.debug("copy from: {} to: {}" + oldPath +newPath);
1170 } catch (Exception e) {
1171 LOGGER.error("copy", e);
1172 return error(e.getMessage());
1176 //Delete Policy or Scope Functionality
1177 private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
1178 PolicyController controller = getPolicyControllerInstance();
1179 PolicyRestController restController = new PolicyRestController();
1180 PolicyEntity policyEntity = null;
1181 String policyNamewithoutExtension;
1183 String userId = UserUtils.getUserSession(request).getOrgUserId();
1184 String deleteVersion = "";
1185 String path = params.getString("path");
1186 LOGGER.debug("delete {}" +path);
1187 if(params.has("deleteVersion")){
1188 deleteVersion = params.getString("deleteVersion");
1190 path = path.substring(path.indexOf('/')+1);
1191 String policyNamewithExtension = path.replace("/", File.separator);
1192 String policyVersionName = policyNamewithExtension.replace(".xml", "");
1194 SimpleBindings policyParams = new SimpleBindings();
1195 if(path.endsWith(".xml")){
1196 policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf('.'));
1197 policyNamewithoutExtension = policyNamewithoutExtension.replace(File.separator, ".");
1198 String splitPolicyName = null;
1199 if(policyNamewithoutExtension.contains("Config_")){
1200 splitPolicyName = policyNamewithoutExtension.replace(".Config_", ":Config_");
1201 }else if(policyNamewithoutExtension.contains("Action_")){
1202 splitPolicyName = policyNamewithoutExtension.replace(".Action_", ":Action_");
1203 }else if(policyNamewithoutExtension.contains("Decision_")){
1204 splitPolicyName = policyNamewithoutExtension.replace(".Decision_", ":Decision_");
1206 String[] split = splitPolicyName.split(":");
1208 query = "FROM PolicyEntity where policyName like :split_1 and scope = :split_0";
1209 policyParams.put("split_1", split[1] + "%");
1210 policyParams.put("split_0", split[0]);
1212 policyNamewithoutExtension = path.replace(File.separator, ".");
1213 query = "FROM PolicyEntity where scope like :policyNamewithoutExtension";
1214 policyParams.put("policyNamewithoutExtension", policyNamewithoutExtension + "%");
1217 List<Object> policyEntityobjects = controller.getDataByQuery(query, policyParams);
1218 String activePolicyName = null;
1219 boolean pdpCheck = false;
1220 if(path.endsWith(".xml")){
1221 policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator);
1222 int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf('.')+1));
1223 if("ALL".equals(deleteVersion)){
1224 if(!policyEntityobjects.isEmpty()){
1225 for(Object object : policyEntityobjects){
1226 policyEntity = (PolicyEntity) object;
1227 String groupEntityquery = "from PolicyGroupEntity where policyid ='"+policyEntity.getPolicyId()+"'";
1228 SimpleBindings pgeParams = new SimpleBindings();
1229 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, pgeParams);
1230 if(!groupobject.isEmpty()){
1232 activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName();
1234 //Delete the entity from Elastic Search Database
1235 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1236 restController.deleteElasticData(searchFileName);
1237 //Delete the entity from Policy Entity table
1238 controller.deleteData(policyEntity);
1239 if(policyNamewithoutExtension.contains("Config_")){
1240 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1241 controller.deleteData(policyEntity.getConfigurationData());
1242 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getConfigurationData().getConfigurationName());
1243 }else if(policyNamewithoutExtension.contains("Action_")){
1244 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1245 controller.deleteData(policyEntity.getActionBodyEntity());
1246 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getActionBodyEntity().getActionBodyName());
1251 //Policy Notification
1252 PolicyVersion versionEntity = new PolicyVersion();
1253 versionEntity.setPolicyName(policyNamewithoutExtension);
1254 versionEntity.setModifiedBy(userId);
1255 controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll");
1257 //Delete from policyVersion table
1258 String getActivePDPPolicyVersion = activePolicyName.replace(".xml", "");
1259 getActivePDPPolicyVersion = getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf('.')+1);
1260 String policyVersionQuery = "update PolicyVersion set active_version='"+getActivePDPPolicyVersion+"' , highest_version='"+getActivePDPPolicyVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1261 if(policyVersionQuery != null){
1262 controller.executeQuery(policyVersionQuery);
1264 return error("Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "+activePolicyName);
1266 //No Active Policy in PDP. So, deleting all entries from policyVersion table
1267 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1268 if(policyVersionQuery != null){
1269 controller.executeQuery(policyVersionQuery);
1272 }else if("CURRENT".equals(deleteVersion)){
1273 String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1);
1274 String currentVersionScope = policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator)).replace(File.separator, ".");
1275 query = "FROM PolicyEntity where policyName = :currentVersionPolicyName and scope = :currentVersionScope";
1277 SimpleBindings peParams = new SimpleBindings();
1278 peParams.put("currentVersionPolicyName", currentVersionPolicyName);
1279 peParams.put("currentVersionScope", currentVersionScope);
1281 List<Object> policyEntitys = controller.getDataByQuery(query, peParams);
1282 if(!policyEntitys.isEmpty()){
1283 policyEntity = (PolicyEntity) policyEntitys.get(0);
1285 if(policyEntity != null){
1286 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId and policyid > 0";
1287 SimpleBindings geParams = new SimpleBindings();
1288 geParams.put("policyEntityId", policyEntity.getPolicyId());
1289 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1290 if(groupobject.isEmpty()){
1291 //Delete the entity from Elastic Search Database
1292 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1293 restController.deleteElasticData(searchFileName);
1294 //Delete the entity from Policy Entity table
1295 controller.deleteData(policyEntity);
1296 if(policyNamewithoutExtension.contains("Config_")){
1297 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1298 controller.deleteData(policyEntity.getConfigurationData());
1299 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getConfigurationData().getConfigurationName());
1300 }else if(policyNamewithoutExtension.contains("Action_")){
1301 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1302 controller.deleteData(policyEntity.getActionBodyEntity());
1303 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getActionBodyEntity().getActionBodyName());
1307 int highestVersion = 0;
1308 if(!policyEntityobjects.isEmpty()){
1309 for(Object object : policyEntityobjects){
1310 policyEntity = (PolicyEntity) object;
1311 String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
1312 int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf('.')+1));
1313 if(policyEntityVersion > highestVersion && policyEntityVersion != version){
1314 highestVersion = policyEntityVersion;
1319 //Policy Notification
1320 PolicyVersion entity = new PolicyVersion();
1321 entity.setPolicyName(policyNamewithoutExtension);
1322 entity.setActiveVersion(highestVersion);
1323 entity.setModifiedBy(userId);
1324 controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne");
1326 String updatequery = "";
1327 if(highestVersion != 0){
1328 updatequery = "update PolicyVersion set active_version='"+highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"'";
1330 updatequery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1332 controller.executeQuery(updatequery);
1334 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1335 if(policyVersionQuery != null){
1336 controller.executeQuery(policyVersionQuery);
1340 return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'");
1345 List<String> activePoliciesInPDP = new ArrayList<>();
1346 if(!policyEntityobjects.isEmpty()){
1347 for(Object object : policyEntityobjects){
1348 policyEntity = (PolicyEntity) object;
1349 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId";
1350 SimpleBindings geParams = new SimpleBindings();
1351 geParams.put("policyEntityId", policyEntity.getPolicyId());
1352 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1353 if(!groupobject.isEmpty()){
1355 activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName());
1357 //Delete the entity from Elastic Search Database
1358 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1359 restController.deleteElasticData(searchFileName);
1360 //Delete the entity from Policy Entity table
1361 controller.deleteData(policyEntity);
1362 policyNamewithoutExtension = policyEntity.getPolicyName();
1363 if(policyNamewithoutExtension.contains("Config_")){
1364 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1365 controller.deleteData(policyEntity.getConfigurationData());
1366 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getConfigurationData().getConfigurationName());
1367 }else if(policyNamewithoutExtension.contains("Action_")){
1368 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1369 controller.deleteData(policyEntity.getActionBodyEntity());
1370 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getActionBodyEntity().getActionBodyName());
1374 //Delete from policyVersion and policyEditor Scope table
1375 String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1376 controller.executeQuery(policyVersionQuery);
1378 //Policy Notification
1379 PolicyVersion entity = new PolicyVersion();
1380 entity.setPolicyName(path);
1381 entity.setModifiedBy(userId);
1382 controller.watchPolicyFunction(entity, path, "DeleteScope");
1384 //Add Active Policies List to PolicyVersionTable
1385 for(int i =0; i < activePoliciesInPDP.size(); i++){
1386 String activePDPPolicyName = activePoliciesInPDP.get(i).replace(".xml", "");
1387 int activePDPPolicyVersion = Integer.parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf('.')+1));
1388 activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf('.')).replace(".", File.separator);
1389 PolicyVersion insertactivePDPVersion = new PolicyVersion();
1390 insertactivePDPVersion.setPolicyName(activePDPPolicyName);
1391 insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion);
1392 insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion);
1393 insertactivePDPVersion.setCreatedBy(userId);
1394 insertactivePDPVersion.setModifiedBy(userId);
1395 controller.saveData(insertactivePDPVersion);
1398 return error("All the Policies has been deleted in Scope. Except the following list of Policies:"+activePoliciesInPDP);
1400 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1401 controller.executeQuery(policyScopeQuery);
1404 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1405 controller.executeQuery(policyScopeQuery);
1409 } catch (Exception e) {
1410 LOGGER.error("delete", e);
1411 return error(e.getMessage());
1416 private JSONObject editFile(JSONObject params) throws ServletException {
1419 PolicyController controller = getPolicyControllerInstance();
1420 String mode = params.getString("mode");
1421 String path = params.getString("path");
1422 LOGGER.debug("editFile path: {}"+ path);
1424 String domain = path.substring(1, path.lastIndexOf('/'));
1425 domain = domain.replace("/", ".");
1427 path = path.substring(1);
1428 path = path.replace("/", ".");
1429 String dbCheckName = path;
1430 if(dbCheckName.contains("Config_")){
1431 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
1432 }else if(dbCheckName.contains("Action_")){
1433 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
1434 }else if(dbCheckName.contains("Decision_")){
1435 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
1438 String[] split = dbCheckName.split(":");
1439 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
1440 SimpleBindings peParams = new SimpleBindings();
1441 peParams.put("split_1", split[1]);
1442 peParams.put("split_0", split[0]);
1443 List<Object> queryData;
1444 if(PolicyController.isjUnit()){
1445 queryData = controller.getDataByQuery(query, null);
1447 queryData = controller.getDataByQuery(query, peParams);
1449 PolicyEntity entity = (PolicyEntity) queryData.get(0);
1450 InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
1453 Object policy = XACMLPolicyScanner.readPolicy(stream);
1454 PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
1455 policyAdapter.setData(policy);
1457 if("viewPolicy".equalsIgnoreCase(mode)){
1458 policyAdapter.setReadOnly(true);
1459 policyAdapter.setEditPolicy(false);
1461 policyAdapter.setReadOnly(false);
1462 policyAdapter.setEditPolicy(true);
1465 policyAdapter.setDomainDir(domain);
1466 policyAdapter.setPolicyData(policy);
1467 String policyName = path.replace(".xml", "");
1468 policyName = policyName.substring(0, policyName.lastIndexOf('.'));
1469 policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf('.')+1));
1471 PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance();
1472 setpolicyAdapter.configure(policyAdapter,entity);
1474 policyAdapter.setParentPath(null);
1475 ObjectMapper mapper = new ObjectMapper();
1476 String json = mapper.writeValueAsString(policyAdapter);
1477 JsonNode jsonNode = mapper.readTree(json);
1479 return new JSONObject().put(RESULT, jsonNode);
1480 } catch (Exception e) {
1481 LOGGER.error("editFile", e);
1482 return error(e.getMessage());
1487 private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
1488 PolicyController controller = getPolicyControllerInstance();
1491 String userId = UserUtils.getUserSession(request).getOrgUserId();
1492 String path = params.getString("path");
1494 if(params.has("subScopename")){
1495 if(! "".equals(params.getString("subScopename"))) {
1496 name = params.getString("path").replace("/", File.separator) + File.separator +params.getString("subScopename");
1499 name = params.getString("name");
1501 }catch(Exception e){
1502 name = params.getString("name");
1503 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e);
1505 String validateName;
1506 if(name.contains(File.separator)){
1507 validateName = name.substring(name.lastIndexOf(File.separator)+1);
1509 validateName = name;
1511 if(!name.isEmpty()){
1512 String validate = PolicyUtils.policySpecialCharValidator(validateName);
1513 if(!validate.contains("success")){
1514 return error(validate);
1517 LOGGER.debug("addFolder path: {} name: {}" + path +name);
1518 if(! "".equals(name)){
1519 if(name.startsWith(File.separator)){
1520 name = name.substring(1);
1522 PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, "scopeName", name);
1524 UserInfo userInfo = new UserInfo();
1525 userInfo.setUserLoginId(userId);
1526 PolicyEditorScopes newScope = new PolicyEditorScopes();
1527 newScope.setScopeName(name);
1528 newScope.setUserCreatedBy(userInfo);
1529 newScope.setUserModifiedBy(userInfo);
1530 controller.saveData(newScope);
1532 return error("Scope Already Exists");
1536 } catch (Exception e) {
1537 LOGGER.error("addFolder", e);
1538 return error(e.getMessage());
1542 //Return Error Object
1543 private JSONObject error(String msg) throws ServletException {
1545 JSONObject result = new JSONObject();
1546 result.put("success", false);
1547 result.put("error", msg);
1548 return new JSONObject().put(RESULT, result);
1549 } catch (JSONException e) {
1550 throw new ServletException(e);
1554 //Return Success Object
1555 private JSONObject success() throws ServletException {
1557 JSONObject result = new JSONObject();
1558 result.put("success", true);
1559 result.put("error", (Object) null);
1560 return new JSONObject().put(RESULT, result);
1561 } catch (JSONException e) {
1562 throw new ServletException(e);
1566 private PolicyController getPolicyControllerInstance(){
1567 return policyController != null ? getPolicyController() : new PolicyController();
1570 public String getTestUserId() {
1574 public static void setTestUserId(String testUserId) {
1575 PolicyManagerServlet.testUserId = testUserId;