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) {
331 List<Object> policyData = new ArrayList<>();
332 JSONArray policyList = null;
333 if(params.has("policyList")){
334 policyList = (JSONArray) params.get("policyList");
336 PolicyController controller = getPolicyControllerInstance();
337 List<JSONObject> resultList = new ArrayList<>();
339 //Get the Login Id of the User from Request
340 String userId = UserUtils.getUserSession(request).getOrgUserId();
341 List<Object> userRoles = controller.getRoles(userId);
342 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
345 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
346 if(scopes.isEmpty()){
347 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
349 Set<String> tempScopes = scopes;
350 for(String scope : tempScopes){
351 addScope(scopes, scope);
354 if(policyList!= null){
355 for(int i = 0; i < policyList.length(); i++){
356 String policyName = policyList.get(i).toString().replace(".xml", "");
357 String version = policyName.substring(policyName.lastIndexOf('.')+1);
358 policyName = policyName.substring(0, policyName.lastIndexOf('.')).replace(".", File.separator);
359 parsePolicyList(resultList, controller, policyName, version);
362 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ){
363 policyData = controller.getData(PolicyVersion.class);
365 List<Object> filterdatas = controller.getData(PolicyVersion.class);
366 for(Object filter : filterdatas){
367 PolicyVersion filterdata = (PolicyVersion) filter;
369 String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator));
370 if(scopes.contains(scopeName)){
371 policyData.add(filterdata);
374 LOGGER.error("Exception occured while filtering policyversion data"+e);
379 if(!policyData.isEmpty()){
380 updateResultList(policyData, resultList);
384 LOGGER.error("Exception occured while reading policy Data from Policy Version table for Policy Search Data"+e);
387 return new JSONObject().put(RESULT, resultList);
390 private void updateResultList(List<Object> policyData, List<JSONObject> resultList) {
391 for(int i =0; i < policyData.size(); i++){
392 PolicyVersion policy = (PolicyVersion) policyData.get(i);
393 JSONObject el = new JSONObject();
394 el.put(NAME, policy.getPolicyName().replace(File.separator, "/"));
395 el.put(DATE, policy.getModifiedDate());
396 el.put(VERSION, policy.getActiveVersion());
398 el.put(TYPE, "file");
399 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
400 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
405 private void parsePolicyList(List<JSONObject> resultList, PolicyController controller, String policyName, String version) {
406 if(policyName.contains("\\")){
407 policyName = policyName.replace("\\", "\\\\");
409 String policyVersionQuery = "From PolicyVersion where policy_name = :policyName and active_version = :version and id >0";
410 SimpleBindings pvParams = new SimpleBindings();
411 pvParams.put("policyName", policyName);
412 pvParams.put(VERSION, version);
413 List<Object> activeData = controller.getDataByQuery(policyVersionQuery, pvParams);
414 if(!activeData.isEmpty()){
415 PolicyVersion policy = (PolicyVersion) activeData.get(0);
416 JSONObject el = new JSONObject();
417 el.put(NAME, policy.getPolicyName().replace(File.separator, "/"));
418 el.put(DATE, policy.getModifiedDate());
419 el.put(VERSION, policy.getActiveVersion());
421 el.put(TYPE, "file");
422 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
423 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
428 private void addScope(Set<String> scopes, String scope) {
429 List<Object> scopesList = queryPolicyEditorScopes(scope);
430 if(!scopesList.isEmpty()){
431 for(int i = 0; i < scopesList.size(); i++){
432 PolicyEditorScopes tempScope = (PolicyEditorScopes) scopesList.get(i);
433 scopes.add(tempScope.getScopeName());
438 //Switch Version Functionality
439 private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{
440 String path = params.getString("path");
441 String userId = null;
443 userId = UserUtils.getUserSession(request).getOrgUserId();
444 } catch (Exception e) {
445 LOGGER.error("Exception Occured while reading userid from cookie" +e);
448 String removeExtension = path.replace(".xml", "");
449 if(path.startsWith("/")){
450 policyName = removeExtension.substring(1, removeExtension.lastIndexOf('.'));
452 policyName = removeExtension.substring(0, removeExtension.lastIndexOf('.'));
456 PolicyController controller = getPolicyControllerInstance();
457 if(! params.toString().contains("activeVersion")){
458 return controller.switchVersionPolicyContent(policyName);
460 String activeVersion = params.getString("activeVersion");
461 String highestVersion = params.get("highestVersion").toString();
462 if(Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)){
463 return error("The Version shouldn't be greater than Highest Value");
465 activePolicy = policyName + "." + activeVersion + ".xml";
466 String dbCheckName = activePolicy.replace("/", ".");
467 if(dbCheckName.contains("Config_")){
468 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
469 }else if(dbCheckName.contains("Action_")){
470 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
471 }else if(dbCheckName.contains("Decision_")){
472 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
474 String[] splitDBCheckName = dbCheckName.split(":");
475 String peQuery = "FROM PolicyEntity where policyName = :splitDBCheckName_1 and scope = :splitDBCheckName_0";
476 SimpleBindings policyParams = new SimpleBindings();
477 policyParams.put("splitDBCheckName_1", splitDBCheckName[1]);
478 policyParams.put("splitDBCheckName_0", splitDBCheckName[0]);
479 List<Object> policyEntity = controller.getDataByQuery(peQuery, policyParams);
480 PolicyEntity pentity = (PolicyEntity) policyEntity.get(0);
481 if(pentity.isDeleted()){
482 return error("The Policy is Not Existing in Workspace");
484 if(policyName.contains("/")){
485 policyName = policyName.replace("/", File.separator);
487 policyName = policyName.substring(policyName.indexOf(File.separator)+1);
488 if(policyName.contains("\\")){
489 policyName = policyName.replace(File.separator, "\\");
491 policyName = splitDBCheckName[0].replace(".", File.separator)+File.separator+policyName;
492 String watchPolicyName = policyName;
493 if(policyName.contains("/")){
494 policyName = policyName.replace("/", File.separator);
496 if(policyName.contains("\\")){
497 policyName = policyName.replace("\\", "\\\\");
499 String query = "update PolicyVersion set active_version='"+activeVersion+"' where policy_name ='"+policyName+"' and id >0";
501 controller.executeQuery(query);
502 //Policy Notification
503 PolicyVersion entity = new PolicyVersion();
504 entity.setPolicyName(watchPolicyName);
505 entity.setActiveVersion(Integer.parseInt(activeVersion));
506 entity.setModifiedBy(userId);
507 controller.watchPolicyFunction(entity, activePolicy, "SwitchVersion");
512 private JSONObject describePolicy(JSONObject params) throws ServletException{
513 JSONObject object = null;
514 String path = params.getString("path");
515 String policyName = null;
516 if(path.startsWith("/")){
517 path = path.substring(1);
518 policyName = path.substring(path.lastIndexOf('/') +1);
519 path = path.replace("/", ".");
521 path = path.replace("/", ".");
524 if(path.contains("Config_")){
525 path = path.replace(".Config_", ":Config_");
526 }else if(path.contains("Action_")){
527 path = path.replace(".Action_", ":Action_");
528 }else if(path.contains("Decision_")){
529 path = path.replace(".Decision_", ":Decision_");
531 PolicyController controller = getPolicyControllerInstance();
532 String[] split = path.split(":");
533 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
534 SimpleBindings peParams = new SimpleBindings();
535 peParams.put("split_1", split[1]);
536 peParams.put("split_0", split[0]);
537 List<Object> queryData = null;
538 if(PolicyController.isjUnit()){
539 queryData = controller.getDataByQuery(query, null);
541 queryData = controller.getDataByQuery(query, peParams);
543 if(queryData.isEmpty()){
544 return error("Error Occured while Describing the Policy - query is empty");
546 PolicyEntity entity = (PolicyEntity) queryData.get(0);
549 temp = File.createTempFile(policyName, ".tmp");
550 } catch (IOException e) {
551 String message = "Failed to create temp file " + policyName + ".tmp";
552 LOGGER.error(message + e);
553 return error(message);
555 try (BufferedWriter bw = new BufferedWriter(new FileWriter(temp))) {
556 bw.write(entity.getPolicyData());
557 } catch (IOException e) {
558 LOGGER.error("Exception Occured while Describing the Policy"+e);
560 object = HumanPolicyComponent.DescribePolicy(temp);
563 Files.delete(temp.toPath());
564 } catch (IOException e) {
565 LOGGER.warn("Failed to delete " + temp.getName() + e);
571 //Get the List of Policies and Scopes for Showing in Editor tab
572 private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException {
573 Set<String> scopes = null;
574 List<String> roles = null;
576 PolicyController controller = getPolicyControllerInstance();
577 //Get the Login Id of the User from Request
578 String testUserID = getTestUserId();
579 String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId();
580 List<Object> userRoles = controller.getRoles(userId);
581 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
585 List<JSONObject> resultList = new ArrayList<>();
586 boolean onlyFolders = params.getBoolean("onlyFolders");
587 String path = params.getString("path");
588 if(path.contains("..xml")){
589 path = path.replaceAll("..xml", "").trim();
592 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
593 if(scopes.isEmpty()){
594 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
596 if(!"/".equals(path)){
597 String tempScope = path.substring(1, path.length());
598 tempScope = tempScope.replace("/", File.separator);
599 scopes.add(tempScope);
604 if("/".equals(path)){
605 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
606 List<Object> scopesList = queryPolicyEditorScopes(null);
607 for(Object list : scopesList){
608 PolicyEditorScopes scope = (PolicyEditorScopes) list;
609 if(!(scope.getScopeName().contains(File.separator))){
610 JSONObject el = new JSONObject();
611 el.put(NAME, scope.getScopeName());
612 el.put(DATE, scope.getModifiedDate());
615 el.put(CREATED_BY, scope.getUserCreatedBy().getUserName());
616 el.put(MODIFIED_BY, scope.getUserModifiedBy().getUserName());
620 }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){
621 for(Object scope : scopes){
622 JSONObject el = new JSONObject();
623 List<Object> scopesList = queryPolicyEditorScopes(scope.toString());
624 if(!scopesList.isEmpty()){
625 PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
626 el.put(NAME, scopeById.getScopeName());
627 el.put(DATE, scopeById.getModifiedDate());
630 el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName());
631 el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName());
638 String scopeName = path.substring(path.indexOf('/') +1);
639 activePolicyList(scopeName, resultList, roles, scopes, onlyFolders);
640 } catch (Exception ex) {
641 LOGGER.error("Error Occured While reading Policy Files List"+ex );
645 return new JSONObject().put(RESULT, resultList);
646 } catch (Exception e) {
647 LOGGER.error("list", e);
648 return error(e.getMessage());
652 private List<Object> queryPolicyEditorScopes(String scopeName){
653 String scopeNamequery;
654 SimpleBindings params = new SimpleBindings();
655 if(scopeName == null){
656 scopeNamequery = "from PolicyEditorScopes";
658 scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
659 params.put("scopeName", scopeName + "%");
661 PolicyController controller = getPolicyControllerInstance();
662 List<Object> scopesList;
663 if(PolicyController.isjUnit()){
664 scopesList = controller.getDataByQuery(scopeNamequery, null);
666 scopesList = controller.getDataByQuery(scopeNamequery, params);
671 //Get Active Policy List based on Scope Selection form Policy Version table
672 private void activePolicyList(String inScopeName, List<JSONObject> resultList, List<String> roles, Set<String> scopes, boolean onlyFolders){
673 PolicyController controller = getPolicyControllerInstance();
674 String scopeName = inScopeName;
675 if(scopeName.contains("/")){
676 scopeName = scopeName.replace("/", File.separator);
678 if(scopeName.contains("\\")){
679 scopeName = scopeName.replace("\\", "\\\\");
681 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
682 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
684 SimpleBindings params = new SimpleBindings();
685 params.put("scopeName", scopeName + "%");
687 List<Object> activePolicies;
688 List<Object> scopesList;
689 if(PolicyController.isjUnit()){
690 activePolicies = controller.getDataByQuery(query, null);
691 scopesList = controller.getDataByQuery(scopeNamequery, null);
693 activePolicies = controller.getDataByQuery(query, params);
694 scopesList = controller.getDataByQuery(scopeNamequery, params);
696 for(Object list : scopesList){
697 PolicyEditorScopes scopeById = (PolicyEditorScopes) list;
698 String scope = scopeById.getScopeName();
699 if(scope.contains(File.separator)){
700 String checkScope = scope.substring(0, scope.lastIndexOf(File.separator));
701 if(scopeName.contains("\\\\")){
702 scopeName = scopeName.replace("\\\\", File.separator);
704 if(scope.contains(File.separator)){
705 scope = scope.substring(checkScope.length()+1);
706 if(scope.contains(File.separator)){
707 scope = scope.substring(0, scope.indexOf(File.separator));
710 if(scopeName.equalsIgnoreCase(checkScope)){
711 JSONObject el = new JSONObject();
713 el.put(DATE, scopeById.getModifiedDate());
716 el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName());
717 el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName());
722 String scopeNameCheck;
723 for (Object list : activePolicies) {
724 PolicyVersion policy = (PolicyVersion) list;
725 String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator));
726 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
727 if(scopeName.contains("\\\\")){
728 scopeNameCheck = scopeName.replace("\\\\", File.separator);
730 scopeNameCheck = scopeName;
732 if(scopeNameValue.equals(scopeNameCheck)){
733 JSONObject el = new JSONObject();
734 el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
735 el.put(DATE, policy.getModifiedDate());
736 el.put(VERSION, policy.getActiveVersion());
738 el.put(TYPE, "file");
739 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
740 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
743 }else if(!scopes.isEmpty() && scopes.contains(scopeNameValue)){
744 JSONObject el = new JSONObject();
745 el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
746 el.put(DATE, policy.getModifiedDate());
747 el.put(VERSION, policy.getActiveVersion());
749 el.put(TYPE, "file");
750 el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
751 el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
757 private String getUserName(String loginId){
758 PolicyController controller = getPolicyControllerInstance();
759 UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
760 if(userInfo == null){
763 return userInfo.getUserName();
767 private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
769 boolean isActive = false;
770 List<String> policyActiveInPDP = new ArrayList<>();
771 Set<String> scopeOfPolicyActiveInPDP = new HashSet<>();
772 String userId = UserUtils.getUserSession(request).getOrgUserId();
773 String oldPath = params.getString("path");
774 String newPath = params.getString("newPath");
775 oldPath = oldPath.substring(oldPath.indexOf('/')+1);
776 newPath = newPath.substring(newPath.indexOf('/')+1);
777 String checkValidation = null;
778 if(oldPath.endsWith(".xml")){
779 checkValidation = newPath.replace(".xml", "");
780 checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf("."));
781 checkValidation = checkValidation.substring(checkValidation.lastIndexOf("/")+1);
782 if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains("success")){
783 return error("Policy Rename Failed. The Name contains special characters.");
785 JSONObject result = policyRename(oldPath, newPath, userId);
786 if(!(Boolean)(result.getJSONObject("result").get("success"))){
790 String scopeName = oldPath;
791 String newScopeName = newPath;
792 if(scopeName.contains("/")){
793 scopeName = scopeName.replace("/", File.separator);
794 newScopeName = newScopeName.replace("/", File.separator);
796 checkValidation = newScopeName.substring(newScopeName.lastIndexOf(File.separator)+1);
797 if(scopeName.contains("\\")){
798 scopeName = scopeName.replace("\\", "\\\\\\\\");
799 newScopeName = newScopeName.replace("\\", "\\\\\\\\");
801 if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains("success")){
802 return error("Scope Rename Failed. The Name contains special characters.");
804 PolicyController controller = getPolicyControllerInstance();
805 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
806 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
807 SimpleBindings pvParams = new SimpleBindings();
808 pvParams.put("scopeName", scopeName + "%");
809 List<Object> activePolicies = controller.getDataByQuery(query, pvParams);
810 List<Object> scopesList = controller.getDataByQuery(scopeNamequery, pvParams);
811 for(Object object : activePolicies){
812 PolicyVersion activeVersion = (PolicyVersion) object;
813 String policyOldPath = activeVersion.getPolicyName().replace(File.separator, "/") + "." + activeVersion.getActiveVersion() + ".xml";
814 String policyNewPath = policyOldPath.replace(oldPath, newPath);
815 JSONObject result = policyRename(policyOldPath, policyNewPath, userId);
816 if(!(Boolean)(result.getJSONObject("result").get("success"))){
818 policyActiveInPDP.add(policyOldPath);
819 String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf('/'));
820 scopeOfPolicyActiveInPDP.add(scope.replace("/", File.separator));
823 boolean rename = false;
824 if(activePolicies.size() != policyActiveInPDP.size()){
828 UserInfo userInfo = new UserInfo();
829 userInfo.setUserLoginId(userId);
830 if(policyActiveInPDP.isEmpty()){
831 renameScope(scopesList, scopeName, newScopeName, controller);
833 renameScope(scopesList, scopeName, newScopeName, controller);
834 for(String scope : scopeOfPolicyActiveInPDP){
835 PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes();
836 editorScopeEntity.setScopeName(scope.replace("\\", "\\\\\\\\"));
837 editorScopeEntity.setUserCreatedBy(userInfo);
838 editorScopeEntity.setUserModifiedBy(userInfo);
839 controller.saveData(editorScopeEntity);
843 return error("The Following policies rename failed. Since they are active in PDP Groups" +policyActiveInPDP);
847 } catch (Exception e) {
848 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
849 return error(e.getMessage());
853 private void renameScope(List<Object> scopesList, String inScopeName, String newScopeName, PolicyController controller){
854 for(Object object : scopesList){
855 PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object;
856 String scopeName = inScopeName;
857 if(scopeName.contains("\\\\\\\\")){
858 scopeName = scopeName.replace("\\\\\\\\", File.separator);
859 newScopeName = newScopeName.replace("\\\\\\\\", File.separator);
861 String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName);
862 editorScopeEntity.setScopeName(scope);
863 controller.updateData(editorScopeEntity);
867 private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
870 PolicyController controller = getPolicyControllerInstance();
872 String policyVersionName = newPath.replace(".xml", "");
873 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')).replace("/", File.separator);
875 String oldpolicyVersionName = oldPath.replace(".xml", "");
876 String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf('.')).replace("/", File.separator);
878 String newpolicyName = newPath.replace("/", ".");
879 String newPolicyCheck = newpolicyName;
880 if(newPolicyCheck.contains("Config_")){
881 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
882 }else if(newPolicyCheck.contains("Action_")){
883 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
884 }else if(newPolicyCheck.contains("Decision_")){
885 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
887 String[] newPolicySplit = newPolicyCheck.split(":");
889 String orignalPolicyName = oldPath.replace("/", ".");
890 String oldPolicyCheck = orignalPolicyName;
891 if(oldPolicyCheck.contains("Config_")){
892 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
893 }else if(oldPolicyCheck.contains("Action_")){
894 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
895 }else if(oldPolicyCheck.contains("Decision_")){
896 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
898 String[] oldPolicySplit = oldPolicyCheck.split(":");
900 //Check PolicyEntity table with newPolicy Name
901 String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
902 SimpleBindings policyParams = new SimpleBindings();
903 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
904 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
905 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
906 if(!queryData.isEmpty()){
907 return error("Policy rename failed. Since, the policy with same name already exists.");
910 //Query the Policy Entity with oldPolicy Name
911 String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf('.'));
912 String oldpolicyEntityquery = "FROM PolicyEntity where policyName like :policyEntityCheck and scope = :oldPolicySplit_0";
913 SimpleBindings params = new SimpleBindings();
914 params.put("policyEntityCheck", policyEntityCheck + "%");
915 params.put("oldPolicySplit_0", oldPolicySplit[0]);
916 List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery, params);
917 if(!oldEntityData.isEmpty()){
918 StringBuilder groupQuery = new StringBuilder();
919 groupQuery.append("FROM PolicyGroupEntity where (");
920 SimpleBindings geParams = new SimpleBindings();
921 for(int i=0; i<oldEntityData.size(); i++){
922 entity = (PolicyEntity) oldEntityData.get(i);
924 groupQuery.append("policyid = :policyId");
925 geParams.put("policyId", entity.getPolicyId());
927 groupQuery.append(" or policyid = :policyId" + i);
928 geParams.put("policyId" + i, entity.getPolicyId());
931 groupQuery.append(")");
932 List<Object> groupEntityData = controller.getDataByQuery(groupQuery.toString(), geParams);
933 if(! groupEntityData.isEmpty()){
934 return error("Policy rename failed. Since the policy or its version is active in PDP Groups.");
936 for(int i=0; i<oldEntityData.size(); i++){
937 entity = (PolicyEntity) oldEntityData.get(i);
938 String checkEntityName = entity.getPolicyName().replace(".xml", "");
939 checkEntityName = checkEntityName.substring(0, checkEntityName.lastIndexOf('.'));
940 String originalPolicyName = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
941 if(checkEntityName.equals(originalPolicyName)){
942 checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0] , newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
946 return error("Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin.");
950 } catch (Exception e) {
951 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
952 return error(e.getMessage());
956 private JSONObject checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, String oldScope, String removeoldPolicyExtension,
957 String policyName, String newpolicyName, String oldpolicyName, String userId) throws ServletException{
959 ConfigurationDataEntity configEntity = entity.getConfigurationData();
960 ActionBodyEntity actionEntity = entity.getActionBodyEntity();
961 PolicyController controller = getPolicyControllerInstance();
963 String oldPolicyNameWithoutExtension = removeoldPolicyExtension;
964 String newPolicyNameWithoutExtension = removenewPolicyExtension;
965 if(removeoldPolicyExtension.endsWith(".xml")){
966 oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf('.'));
967 newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf('.'));
969 entity.setPolicyName(entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
970 entity.setPolicyData(entity.getPolicyData().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
971 entity.setScope(newScope);
972 entity.setModifiedBy(userId);
974 String oldConfigurationName = null;
975 String newConfigurationName = null;
976 if(newpolicyName.contains("Config_")){
977 oldConfigurationName = configEntity.getConfigurationName();
978 configEntity.setConfigurationName(configEntity.getConfigurationName().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
979 controller.updateData(configEntity);
980 newConfigurationName = configEntity.getConfigurationName();
981 File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName);
983 File renamefile = new File(PolicyController.getConfigHome() + File.separator + newConfigurationName);
984 file.renameTo(renamefile);
986 }else if(newpolicyName.contains("Action_")){
987 oldConfigurationName = actionEntity.getActionBodyName();
988 actionEntity.setActionBody(actionEntity.getActionBody().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
989 controller.updateData(actionEntity);
990 newConfigurationName = actionEntity.getActionBodyName();
991 File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName);
993 File renamefile = new File(PolicyController.getActionHome() + File.separator + newConfigurationName);
994 file.renameTo(renamefile);
997 controller.updateData(entity);
999 PolicyRestController restController = new PolicyRestController();
1000 restController.notifyOtherPAPSToUpdateConfigurations("rename", newConfigurationName, oldConfigurationName);
1001 PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldpolicyName);
1002 versionEntity.setPolicyName(policyName);
1003 versionEntity.setModifiedBy(userId);
1004 controller.updateData(versionEntity);
1005 String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator)+1);
1006 String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
1007 if(movePolicyCheck.equals(moveOldPolicyCheck)){
1008 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move");
1010 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename");
1013 } catch (Exception e) {
1014 LOGGER.error("Exception Occured"+e);
1015 return error(e.getMessage());
1019 private JSONObject cloneRecord(String newpolicyName, String oldScope, String inRemoveoldPolicyExtension, String newScope, String inRemovenewPolicyExtension, PolicyEntity entity, String userId) throws ServletException{
1020 String queryEntityName;
1021 PolicyController controller = getPolicyControllerInstance();
1022 PolicyEntity cloneEntity = new PolicyEntity();
1023 cloneEntity.setPolicyName(newpolicyName);
1024 String removeoldPolicyExtension = inRemoveoldPolicyExtension;
1025 String removenewPolicyExtension = inRemovenewPolicyExtension;
1026 removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
1027 removenewPolicyExtension = removenewPolicyExtension.replace(".xml", "");
1028 cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope+"."+removeoldPolicyExtension, newScope+"."+removenewPolicyExtension));
1029 cloneEntity.setScope(entity.getScope());
1030 String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
1031 String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
1032 String newConfigurationName = null;
1033 if(newpolicyName.contains("Config_")){
1034 ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
1035 configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1036 queryEntityName = configurationDataEntity.getConfigurationName();
1037 configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody());
1038 configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType());
1039 configurationDataEntity.setDeleted(false);
1040 configurationDataEntity.setCreatedBy(userId);
1041 configurationDataEntity.setModifiedBy(userId);
1042 controller.saveData(configurationDataEntity);
1043 ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
1044 cloneEntity.setConfigurationData(configEntiy);
1045 newConfigurationName = configEntiy.getConfigurationName();
1046 try (FileWriter fw = new FileWriter(PolicyController.getConfigHome() + File.separator + newConfigurationName);
1047 BufferedWriter bw = new BufferedWriter(fw)){
1048 bw.write(configEntiy.getConfigBody());
1049 } catch (IOException e) {
1050 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1052 }else if(newpolicyName.contains("Action_")){
1053 ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
1054 actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1055 queryEntityName = actionBodyEntity.getActionBodyName();
1056 actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody());
1057 actionBodyEntity.setDeleted(false);
1058 actionBodyEntity.setCreatedBy(userId);
1059 actionBodyEntity.setModifiedBy(userId);
1060 controller.saveData(actionBodyEntity);
1061 ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class, "actionBodyName", queryEntityName);
1062 cloneEntity.setActionBodyEntity(actionEntiy);
1063 newConfigurationName = actionEntiy.getActionBodyName();
1064 try (FileWriter fw = new FileWriter(PolicyController.getActionHome() + File.separator + newConfigurationName);
1065 BufferedWriter bw = new BufferedWriter(fw)){
1066 bw.write(actionEntiy.getActionBody());
1067 } catch (IOException e) {
1068 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1072 cloneEntity.setDeleted(entity.isDeleted());
1073 cloneEntity.setCreatedBy(userId);
1074 cloneEntity.setModifiedBy(userId);
1075 controller.saveData(cloneEntity);
1077 //Notify others paps regarding clone policy.
1078 PolicyRestController restController = new PolicyRestController();
1079 restController.notifyOtherPAPSToUpdateConfigurations("clonePolicy", newConfigurationName, null);
1084 private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
1086 String userId = UserUtils.getUserSession(request).getOrgUserId();
1087 String oldPath = params.getString("path");
1088 String newPath = params.getString("newPath");
1089 oldPath = oldPath.substring(oldPath.indexOf('/')+1);
1090 newPath = newPath.substring(newPath.indexOf('/')+1);
1092 String policyVersionName = newPath.replace(".xml", "");
1093 String version = policyVersionName.substring(policyVersionName.indexOf('.')+1);
1094 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')).replace("/", File.separator);
1096 String newpolicyName = newPath.replace("/", ".");
1098 String orignalPolicyName = oldPath.replace("/", ".");
1100 String newPolicyCheck = newpolicyName;
1101 if(newPolicyCheck.contains("Config_")){
1102 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
1103 }else if(newPolicyCheck.contains("Action_")){
1104 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
1105 }else if(newPolicyCheck.contains("Decision_")){
1106 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
1108 if(!newPolicyCheck.contains(":")){
1109 return error("Policy Clone Failed. The Name contains special characters.");
1111 String[] newPolicySplit = newPolicyCheck.split(":");
1113 String checkValidation = newPolicySplit[1].replace(".xml", "");
1114 checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf("."));
1115 if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains("success")){
1116 return error("Policy Clone Failed. The Name contains special characters.");
1119 String oldPolicyCheck = orignalPolicyName;
1120 if(oldPolicyCheck.contains("Config_")){
1121 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
1122 }else if(oldPolicyCheck.contains("Action_")){
1123 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
1124 }else if(oldPolicyCheck.contains("Decision_")){
1125 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
1127 String[] oldPolicySplit = oldPolicyCheck.split(":");
1129 PolicyController controller = getPolicyControllerInstance();
1131 PolicyEntity entity = null;
1132 boolean success = false;
1134 //Check PolicyEntity table with newPolicy Name
1135 String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
1136 SimpleBindings policyParams = new SimpleBindings();
1137 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
1138 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
1139 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
1140 if(!queryData.isEmpty()){
1141 return error("Policy already exists with same name");
1144 //Query the Policy Entity with oldPolicy Name
1145 policyEntityquery = "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0";
1146 SimpleBindings peParams = new SimpleBindings();
1147 peParams.put("oldPolicySplit_1", oldPolicySplit[1]);
1148 peParams.put("oldPolicySplit_0", oldPolicySplit[0]);
1149 if(PolicyController.isjUnit()){
1150 queryData = controller.getDataByQuery(policyEntityquery, null);
1152 queryData = controller.getDataByQuery(policyEntityquery, peParams);
1154 if(!queryData.isEmpty()){
1155 entity = (PolicyEntity) queryData.get(0);
1158 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId);
1163 PolicyVersion entityItem = new PolicyVersion();
1164 entityItem.setActiveVersion(Integer.parseInt(version));
1165 entityItem.setHigherVersion(Integer.parseInt(version));
1166 entityItem.setPolicyName(policyName);
1167 entityItem.setCreatedBy(userId);
1168 entityItem.setModifiedBy(userId);
1169 entityItem.setModifiedDate(new Date());
1170 controller.saveData(entityItem);
1173 LOGGER.debug("copy from: {} to: {}" + oldPath +newPath);
1176 } catch (Exception e) {
1177 LOGGER.error("copy", e);
1178 return error(e.getMessage());
1182 //Delete Policy or Scope Functionality
1183 private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
1184 PolicyController controller = getPolicyControllerInstance();
1185 PolicyRestController restController = new PolicyRestController();
1186 PolicyEntity policyEntity = null;
1187 String policyNamewithoutExtension;
1189 String userId = UserUtils.getUserSession(request).getOrgUserId();
1190 String deleteVersion = "";
1191 String path = params.getString("path");
1192 LOGGER.debug("delete {}" +path);
1193 if(params.has("deleteVersion")){
1194 deleteVersion = params.getString("deleteVersion");
1196 path = path.substring(path.indexOf('/')+1);
1197 String policyNamewithExtension = path.replace("/", File.separator);
1198 String policyVersionName = policyNamewithExtension.replace(".xml", "");
1200 SimpleBindings policyParams = new SimpleBindings();
1201 if(path.endsWith(".xml")){
1202 policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf('.'));
1203 policyNamewithoutExtension = policyNamewithoutExtension.replace(File.separator, ".");
1204 String splitPolicyName = null;
1205 if(policyNamewithoutExtension.contains("Config_")){
1206 splitPolicyName = policyNamewithoutExtension.replace(".Config_", ":Config_");
1207 }else if(policyNamewithoutExtension.contains("Action_")){
1208 splitPolicyName = policyNamewithoutExtension.replace(".Action_", ":Action_");
1209 }else if(policyNamewithoutExtension.contains("Decision_")){
1210 splitPolicyName = policyNamewithoutExtension.replace(".Decision_", ":Decision_");
1212 String[] split = splitPolicyName.split(":");
1214 query = "FROM PolicyEntity where policyName like :split_1 and scope = :split_0";
1215 policyParams.put("split_1", split[1] + "%");
1216 policyParams.put("split_0", split[0]);
1218 policyNamewithoutExtension = path.replace(File.separator, ".");
1219 query = "FROM PolicyEntity where scope like :policyNamewithoutExtension";
1220 policyParams.put("policyNamewithoutExtension", policyNamewithoutExtension + "%");
1223 List<Object> policyEntityobjects = controller.getDataByQuery(query, policyParams);
1224 String activePolicyName = null;
1225 boolean pdpCheck = false;
1226 if(path.endsWith(".xml")){
1227 policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator);
1228 int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf('.')+1));
1229 if("ALL".equals(deleteVersion)){
1230 if(!policyEntityobjects.isEmpty()){
1231 for(Object object : policyEntityobjects){
1232 policyEntity = (PolicyEntity) object;
1233 String groupEntityquery = "from PolicyGroupEntity where policyid ='"+policyEntity.getPolicyId()+"'";
1234 SimpleBindings pgeParams = new SimpleBindings();
1235 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, pgeParams);
1236 if(!groupobject.isEmpty()){
1238 activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName();
1240 //Delete the entity from Elastic Search Database
1241 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1242 restController.deleteElasticData(searchFileName);
1243 //Delete the entity from Policy Entity table
1244 controller.deleteData(policyEntity);
1245 if(policyNamewithoutExtension.contains("Config_")){
1246 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1247 controller.deleteData(policyEntity.getConfigurationData());
1248 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getConfigurationData().getConfigurationName());
1249 }else if(policyNamewithoutExtension.contains("Action_")){
1250 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1251 controller.deleteData(policyEntity.getActionBodyEntity());
1252 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getActionBodyEntity().getActionBodyName());
1257 //Policy Notification
1258 PolicyVersion versionEntity = new PolicyVersion();
1259 versionEntity.setPolicyName(policyNamewithoutExtension);
1260 versionEntity.setModifiedBy(userId);
1261 controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll");
1263 //Delete from policyVersion table
1264 String getActivePDPPolicyVersion = activePolicyName.replace(".xml", "");
1265 getActivePDPPolicyVersion = getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf('.')+1);
1266 String policyVersionQuery = "update PolicyVersion set active_version='"+getActivePDPPolicyVersion+"' , highest_version='"+getActivePDPPolicyVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1267 if(policyVersionQuery != null){
1268 controller.executeQuery(policyVersionQuery);
1270 return error("Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "+activePolicyName);
1272 //No Active Policy in PDP. So, deleting all entries from policyVersion table
1273 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1274 if(policyVersionQuery != null){
1275 controller.executeQuery(policyVersionQuery);
1278 }else if("CURRENT".equals(deleteVersion)){
1279 String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1);
1280 String currentVersionScope = policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator)).replace(File.separator, ".");
1281 query = "FROM PolicyEntity where policyName = :currentVersionPolicyName and scope = :currentVersionScope";
1283 SimpleBindings peParams = new SimpleBindings();
1284 peParams.put("currentVersionPolicyName", currentVersionPolicyName);
1285 peParams.put("currentVersionScope", currentVersionScope);
1287 List<Object> policyEntitys = controller.getDataByQuery(query, peParams);
1288 if(!policyEntitys.isEmpty()){
1289 policyEntity = (PolicyEntity) policyEntitys.get(0);
1291 if(policyEntity != null){
1292 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId and policyid > 0";
1293 SimpleBindings geParams = new SimpleBindings();
1294 geParams.put("policyEntityId", policyEntity.getPolicyId());
1295 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1296 if(groupobject.isEmpty()){
1297 //Delete the entity from Elastic Search Database
1298 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1299 restController.deleteElasticData(searchFileName);
1300 //Delete the entity from Policy Entity table
1301 controller.deleteData(policyEntity);
1302 if(policyNamewithoutExtension.contains("Config_")){
1303 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1304 controller.deleteData(policyEntity.getConfigurationData());
1305 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getConfigurationData().getConfigurationName());
1306 }else if(policyNamewithoutExtension.contains("Action_")){
1307 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1308 controller.deleteData(policyEntity.getActionBodyEntity());
1309 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getActionBodyEntity().getActionBodyName());
1313 int highestVersion = 0;
1314 if(!policyEntityobjects.isEmpty()){
1315 for(Object object : policyEntityobjects){
1316 policyEntity = (PolicyEntity) object;
1317 String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
1318 int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf('.')+1));
1319 if(policyEntityVersion > highestVersion && policyEntityVersion != version){
1320 highestVersion = policyEntityVersion;
1325 //Policy Notification
1326 PolicyVersion entity = new PolicyVersion();
1327 entity.setPolicyName(policyNamewithoutExtension);
1328 entity.setActiveVersion(highestVersion);
1329 entity.setModifiedBy(userId);
1330 controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne");
1332 String updatequery = "";
1333 if(highestVersion != 0){
1334 updatequery = "update PolicyVersion set active_version='"+highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"'";
1336 updatequery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1338 controller.executeQuery(updatequery);
1340 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1341 if(policyVersionQuery != null){
1342 controller.executeQuery(policyVersionQuery);
1346 return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'");
1351 List<String> activePoliciesInPDP = new ArrayList<>();
1352 if(!policyEntityobjects.isEmpty()){
1353 for(Object object : policyEntityobjects){
1354 policyEntity = (PolicyEntity) object;
1355 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId";
1356 SimpleBindings geParams = new SimpleBindings();
1357 geParams.put("policyEntityId", policyEntity.getPolicyId());
1358 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1359 if(!groupobject.isEmpty()){
1361 activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName());
1363 //Delete the entity from Elastic Search Database
1364 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1365 restController.deleteElasticData(searchFileName);
1366 //Delete the entity from Policy Entity table
1367 controller.deleteData(policyEntity);
1368 policyNamewithoutExtension = policyEntity.getPolicyName();
1369 if(policyNamewithoutExtension.contains("Config_")){
1370 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1371 controller.deleteData(policyEntity.getConfigurationData());
1372 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getConfigurationData().getConfigurationName());
1373 }else if(policyNamewithoutExtension.contains("Action_")){
1374 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1375 controller.deleteData(policyEntity.getActionBodyEntity());
1376 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getActionBodyEntity().getActionBodyName());
1380 //Delete from policyVersion and policyEditor Scope table
1381 String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1382 controller.executeQuery(policyVersionQuery);
1384 //Policy Notification
1385 PolicyVersion entity = new PolicyVersion();
1386 entity.setPolicyName(path);
1387 entity.setModifiedBy(userId);
1388 controller.watchPolicyFunction(entity, path, "DeleteScope");
1390 //Add Active Policies List to PolicyVersionTable
1391 for(int i =0; i < activePoliciesInPDP.size(); i++){
1392 String activePDPPolicyName = activePoliciesInPDP.get(i).replace(".xml", "");
1393 int activePDPPolicyVersion = Integer.parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf('.')+1));
1394 activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf('.')).replace(".", File.separator);
1395 PolicyVersion insertactivePDPVersion = new PolicyVersion();
1396 insertactivePDPVersion.setPolicyName(activePDPPolicyName);
1397 insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion);
1398 insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion);
1399 insertactivePDPVersion.setCreatedBy(userId);
1400 insertactivePDPVersion.setModifiedBy(userId);
1401 controller.saveData(insertactivePDPVersion);
1404 return error("All the Policies has been deleted in Scope. Except the following list of Policies:"+activePoliciesInPDP);
1406 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1407 controller.executeQuery(policyScopeQuery);
1410 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1411 controller.executeQuery(policyScopeQuery);
1415 } catch (Exception e) {
1416 LOGGER.error("delete", e);
1417 return error(e.getMessage());
1422 private JSONObject editFile(JSONObject params) throws ServletException {
1425 PolicyController controller = getPolicyControllerInstance();
1426 String mode = params.getString("mode");
1427 String path = params.getString("path");
1428 LOGGER.debug("editFile path: {}"+ path);
1430 String domain = path.substring(1, path.lastIndexOf('/'));
1431 domain = domain.replace("/", ".");
1433 path = path.substring(1);
1434 path = path.replace("/", ".");
1435 String dbCheckName = path;
1436 if(dbCheckName.contains("Config_")){
1437 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
1438 }else if(dbCheckName.contains("Action_")){
1439 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
1440 }else if(dbCheckName.contains("Decision_")){
1441 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
1444 String[] split = dbCheckName.split(":");
1445 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
1446 SimpleBindings peParams = new SimpleBindings();
1447 peParams.put("split_1", split[1]);
1448 peParams.put("split_0", split[0]);
1449 List<Object> queryData;
1450 if(PolicyController.isjUnit()){
1451 queryData = controller.getDataByQuery(query, null);
1453 queryData = controller.getDataByQuery(query, peParams);
1455 PolicyEntity entity = (PolicyEntity) queryData.get(0);
1456 InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
1459 Object policy = XACMLPolicyScanner.readPolicy(stream);
1460 PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
1461 policyAdapter.setData(policy);
1463 if("viewPolicy".equalsIgnoreCase(mode)){
1464 policyAdapter.setReadOnly(true);
1465 policyAdapter.setEditPolicy(false);
1467 policyAdapter.setReadOnly(false);
1468 policyAdapter.setEditPolicy(true);
1471 policyAdapter.setDomainDir(domain);
1472 policyAdapter.setPolicyData(policy);
1473 String policyName = path.replace(".xml", "");
1474 policyName = policyName.substring(0, policyName.lastIndexOf('.'));
1475 policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf('.')+1));
1477 PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance();
1478 setpolicyAdapter.configure(policyAdapter,entity);
1480 policyAdapter.setParentPath(null);
1481 ObjectMapper mapper = new ObjectMapper();
1482 String json = mapper.writeValueAsString(policyAdapter);
1483 JsonNode jsonNode = mapper.readTree(json);
1485 return new JSONObject().put(RESULT, jsonNode);
1486 } catch (Exception e) {
1487 LOGGER.error("editFile", e);
1488 return error(e.getMessage());
1493 private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
1494 PolicyController controller = getPolicyControllerInstance();
1497 String userId = UserUtils.getUserSession(request).getOrgUserId();
1498 String path = params.getString("path");
1500 if(params.has("subScopename")){
1501 if(! "".equals(params.getString("subScopename"))) {
1502 name = params.getString("path").replace("/", File.separator) + File.separator +params.getString("subScopename");
1505 name = params.getString(NAME);
1507 }catch(Exception e){
1508 name = params.getString(NAME);
1509 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e);
1511 String validateName;
1512 if(name.contains(File.separator)){
1513 validateName = name.substring(name.lastIndexOf(File.separator)+1);
1515 validateName = name;
1517 if(!name.isEmpty()){
1518 String validate = PolicyUtils.policySpecialCharValidator(validateName);
1519 if(!validate.contains("success")){
1520 return error(validate);
1523 LOGGER.debug("addFolder path: {} name: {}" + path +name);
1524 if(! "".equals(name)){
1525 if(name.startsWith(File.separator)){
1526 name = name.substring(1);
1528 PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, "scopeName", name);
1530 UserInfo userInfo = new UserInfo();
1531 userInfo.setUserLoginId(userId);
1532 PolicyEditorScopes newScope = new PolicyEditorScopes();
1533 newScope.setScopeName(name);
1534 newScope.setUserCreatedBy(userInfo);
1535 newScope.setUserModifiedBy(userInfo);
1536 controller.saveData(newScope);
1538 return error("Scope Already Exists");
1542 } catch (Exception e) {
1543 LOGGER.error("addFolder", e);
1544 return error(e.getMessage());
1548 //Return Error Object
1549 private JSONObject error(String msg) throws ServletException {
1551 JSONObject result = new JSONObject();
1552 result.put("success", false);
1553 result.put("error", msg);
1554 return new JSONObject().put(RESULT, result);
1555 } catch (JSONException e) {
1556 throw new ServletException(e);
1560 //Return Success Object
1561 private JSONObject success() throws ServletException {
1563 JSONObject result = new JSONObject();
1564 result.put("success", true);
1565 result.put("error", (Object) null);
1566 return new JSONObject().put(RESULT, result);
1567 } catch (JSONException e) {
1568 throw new ServletException(e);
1572 private PolicyController getPolicyControllerInstance(){
1573 return policyController != null ? getPolicyController() : new PolicyController();
1576 public String getTestUserId() {
1580 public static void setTestUserId(String testUserId) {
1581 PolicyManagerServlet.testUserId = testUserId;