2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.admin;
23 import java.io.BufferedReader;
24 import java.io.BufferedWriter;
25 import java.io.ByteArrayInputStream;
27 import java.io.FileInputStream;
28 import java.io.FileOutputStream;
29 import java.io.FileWriter;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.io.OutputStream;
33 import java.io.PrintWriter;
34 import java.nio.charset.StandardCharsets;
35 import java.nio.file.Files;
36 import java.nio.file.Path;
37 import java.nio.file.Paths;
38 import java.util.ArrayList;
39 import java.util.Date;
40 import java.util.HashMap;
41 import java.util.HashSet;
42 import java.util.List;
46 import javax.json.Json;
47 import javax.json.JsonArray;
48 import javax.json.JsonReader;
49 import javax.script.SimpleBindings;
50 import javax.servlet.ServletConfig;
51 import javax.servlet.ServletException;
52 import javax.servlet.annotation.WebInitParam;
53 import javax.servlet.annotation.WebServlet;
54 import javax.servlet.http.HttpServlet;
55 import javax.servlet.http.HttpServletRequest;
56 import javax.servlet.http.HttpServletResponse;
58 import org.apache.commons.compress.utils.IOUtils;
59 import org.apache.commons.fileupload.FileItem;
60 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
61 import org.apache.commons.fileupload.servlet.ServletFileUpload;
62 import org.apache.http.HttpStatus;
63 import org.json.JSONArray;
64 import org.json.JSONException;
65 import org.json.JSONObject;
66 import org.onap.policy.common.logging.flexlogger.FlexLogger;
67 import org.onap.policy.common.logging.flexlogger.Logger;
68 import org.onap.policy.components.HumanPolicyComponent;
69 import org.onap.policy.controller.PolicyController;
70 import org.onap.policy.controller.PolicyExportAndImportController;
71 import org.onap.policy.rest.XACMLRest;
72 import org.onap.policy.rest.XACMLRestProperties;
73 import org.onap.policy.rest.adapter.PolicyRestAdapter;
74 import org.onap.policy.rest.jpa.ActionBodyEntity;
75 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
76 import org.onap.policy.rest.jpa.PolicyEditorScopes;
77 import org.onap.policy.rest.jpa.PolicyEntity;
78 import org.onap.policy.rest.jpa.PolicyVersion;
79 import org.onap.policy.rest.jpa.UserInfo;
80 import org.onap.policy.utils.PolicyUtils;
81 import org.onap.policy.utils.UserUtils.Pair;
82 import org.onap.policy.xacml.api.XACMLErrorConstants;
83 import org.onap.policy.xacml.util.XACMLPolicyScanner;
84 import org.onap.portalsdk.core.web.support.UserUtils;
86 import com.att.research.xacml.util.XACMLProperties;
87 import com.fasterxml.jackson.databind.JsonNode;
88 import com.fasterxml.jackson.databind.ObjectMapper;
91 @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.") })
92 public class PolicyManagerServlet extends HttpServlet {
93 private static final Logger LOGGER = FlexLogger.getLogger(PolicyManagerServlet.class);
94 private static final long serialVersionUID = -8453502699403909016L;
97 LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT, SEARCHLIST
100 private static PolicyController policyController;
101 public synchronized PolicyController getPolicyController() {
102 return policyController;
105 public static synchronized void setPolicyController(PolicyController policyController) {
106 PolicyManagerServlet.policyController = policyController;
109 private static String CONTENTTYPE = "application/json";
110 private static String SUPERADMIN = "super-admin";
111 private static String SUPEREDITOR = "super-editor";
112 private static String SUPERGUEST = "super-guest";
113 private static String ADMIN = "admin";
114 private static String EDITOR = "editor";
115 private static String GUEST = "guest";
116 private static String RESULT = "result";
118 private static Path closedLoopJsonLocation;
119 private static JsonArray policyNames;
120 private static String testUserId = null;
122 public static JsonArray getPolicyNames() {
126 public static void setPolicyNames(JsonArray policyNames) {
127 PolicyManagerServlet.policyNames = policyNames;
130 private static List<String> serviceTypeNamesList = new ArrayList<>();
132 public static List<String> getServiceTypeNamesList() {
133 return serviceTypeNamesList;
137 public void init(ServletConfig servletConfig) throws ServletException {
138 super.init(servletConfig);
140 // Common initialization
142 XACMLRest.xacmlInit(servletConfig);
144 //Initialize ClosedLoop JSON
146 PolicyManagerServlet.initializeJSONLoad();
149 protected static void initializeJSONLoad() {
150 closedLoopJsonLocation = Paths.get(XACMLProperties
151 .getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP));
152 String location = closedLoopJsonLocation.toString();
153 if (! location.endsWith("json")) {
154 LOGGER.warn("JSONConfig file does not end with extension .json");
157 try (FileInputStream inputStream = new FileInputStream(location);
158 JsonReader jsonReader = Json.createReader(inputStream)) {
159 policyNames = jsonReader.readArray();
160 serviceTypeNamesList = new ArrayList<>();
161 for (int i = 0; i < policyNames.size(); i++) {
162 javax.json.JsonObject policyName = policyNames.getJsonObject(i);
163 String name = policyName.getJsonString("serviceTypePolicyName").getString();
164 serviceTypeNamesList.add(name);
166 } catch (IOException e) {
167 LOGGER.error("Exception Occured while initializing the JSONConfig file"+e);
172 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
173 LOGGER.debug("doPost");
175 // if request contains multipart-form-data
176 if (ServletFileUpload.isMultipartContent(request)) {
177 uploadFile(request, response);
179 // all other post request has json params in body
181 fileOperation(request, response);
183 } catch (Exception e) {
185 setError(e, response);
186 }catch(Exception e1){
187 LOGGER.error("Exception Occured"+e1);
192 //Set Error Message for Exception
193 private void setError(Exception t, HttpServletResponse response) throws IOException {
195 JSONObject responseJsonObject = error(t.getMessage());
196 response.setContentType(CONTENTTYPE);
197 PrintWriter out = response.getWriter();
198 out.print(responseJsonObject);
200 } catch (Exception x) {
201 LOGGER.error("Exception Occured"+x);
202 response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage());
206 //Policy Import Functionality
207 private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException {
210 Map<String, InputStream> files = new HashMap<>();
212 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
213 for (FileItem item : items) {
214 if (!item.isFormField()) {
215 // Process form file field (input type="file").
216 files.put(item.getName(), item.getInputStream());
217 if(item.getName().endsWith(".xls") && item.getSize() <= PolicyController.getFileSizeLimit()){
218 File file = new File(item.getName());
219 try (OutputStream outputStream = new FileOutputStream(file);)
221 IOUtils.copy(item.getInputStream(), outputStream);
222 newFile = file.toString();
223 PolicyExportAndImportController importController = new PolicyExportAndImportController();
224 importController.importRepositoryFile(newFile, request);
226 LOGGER.error("Upload error : " + e);
229 else if (!item.getName().endsWith(".xls")) {
230 LOGGER.error("Non .xls filetype uploaded: " + item.getName());
232 else { //uploaded file size is greater than allowed
233 LOGGER.error("Upload file size limit exceeded! File size (Bytes) is: " + item.getSize());
238 JSONObject responseJsonObject;
239 responseJsonObject = this.success();
240 response.setContentType(CONTENTTYPE);
241 PrintWriter out = response.getWriter();
242 out.print(responseJsonObject);
244 } catch (Exception e) {
245 LOGGER.debug("Cannot write file");
246 throw new ServletException("Cannot write file", e);
250 //File Operation Functionality
251 private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
252 JSONObject responseJsonObject = null;
254 StringBuilder sb = new StringBuilder();
255 BufferedReader br = request.getReader();
257 while ((str = br.readLine()) != null) {
261 JSONObject jObj = new JSONObject(sb.toString());
262 JSONObject params = jObj.getJSONObject("params");
263 Mode mode = Mode.valueOf(params.getString("mode"));
265 String userId = UserUtils.getUserSession(request).getOrgUserId();
266 LOGGER.info("****************************************Logging UserID while doing actions on Editor tab*******************************************");
267 LOGGER.info("UserId: " + userId + "Action Mode: "+ mode.toString() + "Action Params: "+params.toString());
268 LOGGER.info("***********************************************************************************************************************************");
273 responseJsonObject = addFolder(params, request);
276 responseJsonObject = copy(params, request);
279 responseJsonObject = delete(params, request);
283 responseJsonObject = editFile(params);
286 responseJsonObject = list(params, request);
289 responseJsonObject = rename(params, request);
291 case DESCRIBEPOLICYFILE:
292 responseJsonObject = describePolicy(params);
295 responseJsonObject = switchVersion(params, request);
298 responseJsonObject = searchPolicyList(params, request);
301 throw new ServletException("not implemented");
303 if (responseJsonObject == null) {
304 responseJsonObject = error("generic error : responseJsonObject is null");
306 } catch (Exception e) {
307 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While doing File Operation" + e);
308 responseJsonObject = error(e.getMessage());
310 response.setContentType(CONTENTTYPE);
311 PrintWriter out = response.getWriter();
312 out.print(responseJsonObject);
316 private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) {
319 List<Object> policyData = new ArrayList<>();
320 JSONArray policyList = null;
321 if(params.has("policyList")){
322 policyList = (JSONArray) params.get("policyList");
324 PolicyController controller = getPolicyControllerInstance();
325 List<JSONObject> resultList = new ArrayList<>();
327 //Get the Login Id of the User from Request
328 String userId = UserUtils.getUserSession(request).getOrgUserId();
329 List<Object> userRoles = controller.getRoles(userId);
330 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
333 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
334 if(scopes.isEmpty()){
335 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
337 Set<String> tempScopes = scopes;
338 for(String scope : tempScopes){
339 List<Object> scopesList = queryPolicyEditorScopes(scope);
340 if(!scopesList.isEmpty()){
341 for(int i = 0; i < scopesList.size(); i++){
342 PolicyEditorScopes tempScope = (PolicyEditorScopes) scopesList.get(i);
343 scopes.add(tempScope.getScopeName());
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 if(policyName.contains("\\")){
354 policyName = policyName.replace("\\", "\\\\");
356 String policyVersionQuery = "From PolicyVersion where policy_name = :policyName and active_version = :version and id >0";
357 SimpleBindings pvParams = new SimpleBindings();
358 pvParams.put("policyName", policyName);
359 pvParams.put("version", version);
360 List<Object> activeData = controller.getDataByQuery(policyVersionQuery, pvParams);
361 if(!activeData.isEmpty()){
362 PolicyVersion policy = (PolicyVersion) activeData.get(0);
363 JSONObject el = new JSONObject();
364 el.put("name", policy.getPolicyName().replace(File.separator, "/"));
365 el.put("date", policy.getModifiedDate());
366 el.put("version", policy.getActiveVersion());
368 el.put("type", "file");
369 el.put("createdBy", getUserName(policy.getCreatedBy()));
370 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
375 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ){
376 policyData = controller.getData(PolicyVersion.class);
378 List<Object> filterdatas = controller.getData(PolicyVersion.class);
379 for(Object filter : filterdatas){
380 PolicyVersion filterdata = (PolicyVersion) filter;
382 String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator));
383 if(scopes.contains(scopeName)){
384 policyData.add(filterdata);
387 LOGGER.error("Exception occured while filtering policyversion data"+e);
392 if(!policyData.isEmpty()){
393 for(int i =0; i < policyData.size(); i++){
394 PolicyVersion policy = (PolicyVersion) policyData.get(i);
395 JSONObject el = new JSONObject();
396 el.put("name", policy.getPolicyName().replace(File.separator, "/"));
397 el.put("date", policy.getModifiedDate());
398 el.put("version", policy.getActiveVersion());
400 el.put("type", "file");
401 el.put("createdBy", getUserName(policy.getCreatedBy()));
402 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
408 LOGGER.error("Exception occured while reading policy Data from Policy Version table for Policy Search Data"+e);
411 return new JSONObject().put(RESULT, resultList);
414 //Switch Version Functionality
415 private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{
416 String path = params.getString("path");
417 String userId = null;
419 userId = UserUtils.getUserSession(request).getOrgUserId();
420 } catch (Exception e) {
421 LOGGER.error("Exception Occured while reading userid from cookie" +e);
424 String removeExtension = path.replace(".xml", "");
425 if(path.startsWith("/")){
426 policyName = removeExtension.substring(1, removeExtension.lastIndexOf('.'));
428 policyName = removeExtension.substring(0, removeExtension.lastIndexOf('.'));
432 PolicyController controller = getPolicyControllerInstance();
433 if(! params.toString().contains("activeVersion")){
434 return controller.switchVersionPolicyContent(policyName);
436 String activeVersion = params.getString("activeVersion");
437 String highestVersion = params.get("highestVersion").toString();
438 if(Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)){
439 return error("The Version shouldn't be greater than Highest Value");
441 activePolicy = policyName + "." + activeVersion + ".xml";
442 String dbCheckName = activePolicy.replace("/", ".");
443 if(dbCheckName.contains("Config_")){
444 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
445 }else if(dbCheckName.contains("Action_")){
446 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
447 }else if(dbCheckName.contains("Decision_")){
448 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
450 String[] splitDBCheckName = dbCheckName.split(":");
451 String peQuery = "FROM PolicyEntity where policyName = :splitDBCheckName_1 and scope = :splitDBCheckName_0";
452 SimpleBindings policyParams = new SimpleBindings();
453 policyParams.put("splitDBCheckName_1", splitDBCheckName[1]);
454 policyParams.put("splitDBCheckName_0", splitDBCheckName[0]);
455 List<Object> policyEntity = controller.getDataByQuery(peQuery, policyParams);
456 PolicyEntity pentity = (PolicyEntity) policyEntity.get(0);
457 if(pentity.isDeleted()){
458 return error("The Policy is Not Existing in Workspace");
460 if(policyName.contains("/")){
461 policyName = policyName.replace("/", File.separator);
463 policyName = policyName.substring(policyName.indexOf(File.separator)+1);
464 if(policyName.contains("\\")){
465 policyName = policyName.replace(File.separator, "\\");
467 policyName = splitDBCheckName[0].replace(".", File.separator)+File.separator+policyName;
468 String watchPolicyName = policyName;
469 if(policyName.contains("/")){
470 policyName = policyName.replace("/", File.separator);
472 if(policyName.contains("\\")){
473 policyName = policyName.replace("\\", "\\\\");
475 String query = "update PolicyVersion set active_version='"+activeVersion+"' where policy_name ='"+policyName+"' and id >0";
477 controller.executeQuery(query);
478 //Policy Notification
479 PolicyVersion entity = new PolicyVersion();
480 entity.setPolicyName(watchPolicyName);
481 entity.setActiveVersion(Integer.parseInt(activeVersion));
482 entity.setModifiedBy(userId);
483 controller.watchPolicyFunction(entity, activePolicy, "SwitchVersion");
488 private JSONObject describePolicy(JSONObject params) throws ServletException{
489 JSONObject object = null;
490 String path = params.getString("path");
491 String policyName = null;
492 if(path.startsWith("/")){
493 path = path.substring(1);
494 policyName = path.substring(path.lastIndexOf('/') +1);
495 path = path.replace("/", ".");
497 path = path.replace("/", ".");
500 if(path.contains("Config_")){
501 path = path.replace(".Config_", ":Config_");
502 }else if(path.contains("Action_")){
503 path = path.replace(".Action_", ":Action_");
504 }else if(path.contains("Decision_")){
505 path = path.replace(".Decision_", ":Decision_");
507 PolicyController controller = getPolicyControllerInstance();
508 String[] split = path.split(":");
509 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
510 SimpleBindings peParams = new SimpleBindings();
511 peParams.put("split_1", split[1]);
512 peParams.put("split_0", split[0]);
513 List<Object> queryData = null;
514 if(PolicyController.isjUnit()){
515 queryData = controller.getDataByQuery(query, null);
517 queryData = controller.getDataByQuery(query, peParams);
519 if(queryData.isEmpty()){
520 return error("Error Occured while Describing the Policy - query is empty");
522 PolicyEntity entity = (PolicyEntity) queryData.get(0);
525 temp = File.createTempFile(policyName, ".tmp");
526 } catch (IOException e) {
527 String message = "Failed to create temp file " + policyName + ".tmp";
528 LOGGER.error(message + e);
529 return error(message);
531 try (BufferedWriter bw = new BufferedWriter(new FileWriter(temp))) {
532 bw.write(entity.getPolicyData());
533 object = HumanPolicyComponent.DescribePolicy(temp);
534 } catch (IOException e) {
535 LOGGER.error("Exception Occured while Describing the Policy"+e);
539 Files.delete(temp.toPath());
540 } catch (IOException e) {
541 LOGGER.warn("Failed to delete " + temp.getName() + e);
548 //Get the List of Policies and Scopes for Showing in Editor tab
549 private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException {
550 Set<String> scopes = null;
551 List<String> roles = null;
553 PolicyController controller = getPolicyControllerInstance();
554 //Get the Login Id of the User from Request
555 String testUserID = getTestUserId();
556 String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId();
557 List<Object> userRoles = controller.getRoles(userId);
558 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
562 List<JSONObject> resultList = new ArrayList<>();
563 boolean onlyFolders = params.getBoolean("onlyFolders");
564 String path = params.getString("path");
565 if(path.contains("..xml")){
566 path = path.replaceAll("..xml", "").trim();
569 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
570 if(scopes.isEmpty()){
571 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
573 if(!"/".equals(path)){
574 String tempScope = path.substring(1, path.length());
575 tempScope = tempScope.replace("/", File.separator);
576 scopes.add(tempScope);
581 if("/".equals(path)){
582 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
583 List<Object> scopesList = queryPolicyEditorScopes(null);
584 for(Object list : scopesList){
585 PolicyEditorScopes scope = (PolicyEditorScopes) list;
586 if(!(scope.getScopeName().contains(File.separator))){
587 JSONObject el = new JSONObject();
588 el.put("name", scope.getScopeName());
589 el.put("date", scope.getModifiedDate());
591 el.put("type", "dir");
592 el.put("createdBy", scope.getUserCreatedBy().getUserName());
593 el.put("modifiedBy", scope.getUserModifiedBy().getUserName());
597 }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){
598 for(Object scope : scopes){
599 JSONObject el = new JSONObject();
600 List<Object> scopesList = queryPolicyEditorScopes(scope.toString());
601 if(!scopesList.isEmpty()){
602 PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
603 el.put("name", scopeById.getScopeName());
604 el.put("date", scopeById.getModifiedDate());
606 el.put("type", "dir");
607 el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
608 el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
615 String scopeName = path.substring(path.indexOf('/') +1);
616 activePolicyList(scopeName, resultList, roles, scopes, onlyFolders);
617 } catch (Exception ex) {
618 LOGGER.error("Error Occured While reading Policy Files List"+ex );
622 return new JSONObject().put(RESULT, resultList);
623 } catch (Exception e) {
624 LOGGER.error("list", e);
625 return error(e.getMessage());
629 private List<Object> queryPolicyEditorScopes(String scopeName){
630 String scopeNamequery;
631 SimpleBindings params = new SimpleBindings();
632 if(scopeName == null){
633 scopeNamequery = "from PolicyEditorScopes";
635 scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
636 params.put("scopeName", scopeName + "%");
638 PolicyController controller = getPolicyControllerInstance();
639 List<Object> scopesList;
640 if(PolicyController.isjUnit()){
641 scopesList = controller.getDataByQuery(scopeNamequery, null);
643 scopesList = controller.getDataByQuery(scopeNamequery, params);
648 //Get Active Policy List based on Scope Selection form Policy Version table
649 private void activePolicyList(String inScopeName, List<JSONObject> resultList, List<String> roles, Set<String> scopes, boolean onlyFolders){
650 PolicyController controller = getPolicyControllerInstance();
651 String scopeName = inScopeName;
652 if(scopeName.contains("/")){
653 scopeName = scopeName.replace("/", File.separator);
655 if(scopeName.contains("\\")){
656 scopeName = scopeName.replace("\\", "\\\\\\\\");
658 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
659 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
661 SimpleBindings params = new SimpleBindings();
662 params.put("scopeName", scopeName + "%");
664 List<Object> activePolicies;
665 List<Object> scopesList;
666 if(PolicyController.isjUnit()){
667 activePolicies = controller.getDataByQuery(query, null);
668 scopesList = controller.getDataByQuery(scopeNamequery, null);
670 activePolicies = controller.getDataByQuery(query, params);
671 scopesList = controller.getDataByQuery(scopeNamequery, params);
673 for(Object list : scopesList){
674 PolicyEditorScopes scopeById = (PolicyEditorScopes) list;
675 String scope = scopeById.getScopeName();
676 if(scope.contains(File.separator)){
677 String checkScope = scope.substring(0, scope.lastIndexOf(File.separator));
678 if(scopeName.contains("\\\\")){
679 scopeName = scopeName.replace("\\\\", File.separator);
681 if(scope.contains(File.separator)){
682 scope = scope.substring(checkScope.length()+1);
683 if(scope.contains(File.separator)){
684 scope = scope.substring(0, scope.indexOf(File.separator));
687 if(scopeName.equalsIgnoreCase(checkScope)){
688 JSONObject el = new JSONObject();
689 el.put("name", scope);
690 el.put("date", scopeById.getModifiedDate());
692 el.put("type", "dir");
693 el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
694 el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
699 String scopeNameCheck;
700 for (Object list : activePolicies) {
701 PolicyVersion policy = (PolicyVersion) list;
702 String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator));
703 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
704 if(scopeName.contains("\\\\")){
705 scopeNameCheck = scopeName.replace("\\\\", File.separator);
707 scopeNameCheck = scopeName;
709 if(scopeNameValue.equals(scopeNameCheck)){
710 JSONObject el = new JSONObject();
711 el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
712 el.put("date", policy.getModifiedDate());
713 el.put("version", policy.getActiveVersion());
715 el.put("type", "file");
716 el.put("createdBy", getUserName(policy.getCreatedBy()));
717 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
720 }else if(!scopes.isEmpty() && scopes.contains(scopeNameValue)){
721 JSONObject el = new JSONObject();
722 el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
723 el.put("date", policy.getModifiedDate());
724 el.put("version", policy.getActiveVersion());
726 el.put("type", "file");
727 el.put("createdBy", getUserName(policy.getCreatedBy()));
728 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
734 private String getUserName(String loginId){
735 PolicyController controller = getPolicyControllerInstance();
736 UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
737 if(userInfo == null){
740 return userInfo.getUserName();
744 private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
746 boolean isActive = false;
747 List<String> policyActiveInPDP = new ArrayList<>();
748 Set<String> scopeOfPolicyActiveInPDP = new HashSet<>();
749 String userId = UserUtils.getUserSession(request).getOrgUserId();
750 String oldPath = params.getString("path");
751 String newPath = params.getString("newPath");
752 oldPath = oldPath.substring(oldPath.indexOf('/')+1);
753 newPath = newPath.substring(newPath.indexOf('/')+1);
754 if(oldPath.endsWith(".xml")){
755 JSONObject result = policyRename(oldPath, newPath, userId);
756 if(!(Boolean)(result.getJSONObject("result").get("success"))){
760 String scopeName = oldPath;
761 String newScopeName = newPath;
762 if(scopeName.contains("/")){
763 scopeName = scopeName.replace("/", File.separator);
764 newScopeName = newScopeName.replace("/", File.separator);
766 if(scopeName.contains("\\")){
767 scopeName = scopeName.replace("\\", "\\\\\\\\");
768 newScopeName = newScopeName.replace("\\", "\\\\\\\\");
770 PolicyController controller = getPolicyControllerInstance();
771 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
772 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
773 SimpleBindings pvParams = new SimpleBindings();
774 pvParams.put("scopeName", scopeName + "%");
775 List<Object> activePolicies = controller.getDataByQuery(query, pvParams);
776 List<Object> scopesList = controller.getDataByQuery(scopeNamequery, pvParams);
777 for(Object object : activePolicies){
778 PolicyVersion activeVersion = (PolicyVersion) object;
779 String policyOldPath = activeVersion.getPolicyName().replace(File.separator, "/") + "." + activeVersion.getActiveVersion() + ".xml";
780 String policyNewPath = policyOldPath.replace(oldPath, newPath);
781 JSONObject result = policyRename(policyOldPath, policyNewPath, userId);
782 if(!(Boolean)(result.getJSONObject("result").get("success"))){
784 policyActiveInPDP.add(policyOldPath);
785 String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf('/'));
786 scopeOfPolicyActiveInPDP.add(scope.replace("/", File.separator));
789 boolean rename = false;
790 if(activePolicies.size() != policyActiveInPDP.size()){
794 UserInfo userInfo = new UserInfo();
795 userInfo.setUserLoginId(userId);
796 if(policyActiveInPDP.isEmpty()){
797 renameScope(scopesList, scopeName, newScopeName, controller);
799 renameScope(scopesList, scopeName, newScopeName, controller);
800 for(String scope : scopeOfPolicyActiveInPDP){
801 PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes();
802 editorScopeEntity.setScopeName(scope.replace("\\", "\\\\\\\\"));
803 editorScopeEntity.setUserCreatedBy(userInfo);
804 editorScopeEntity.setUserModifiedBy(userInfo);
805 controller.saveData(editorScopeEntity);
809 return error("The Following policies rename failed. Since they are active in PDP Groups" +policyActiveInPDP);
813 } catch (Exception e) {
814 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
815 return error(e.getMessage());
819 private void renameScope(List<Object> scopesList, String inScopeName, String newScopeName, PolicyController controller){
820 for(Object object : scopesList){
821 PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object;
822 String scopeName = inScopeName;
823 if(scopeName.contains("\\\\\\\\")){
824 scopeName = scopeName.replace("\\\\\\\\", File.separator);
825 newScopeName = newScopeName.replace("\\\\\\\\", File.separator);
827 String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName);
828 editorScopeEntity.setScopeName(scope);
829 controller.updateData(editorScopeEntity);
833 private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
836 PolicyController controller = getPolicyControllerInstance();
838 String policyVersionName = newPath.replace(".xml", "");
839 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')).replace("/", File.separator);
841 String oldpolicyVersionName = oldPath.replace(".xml", "");
842 String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf('.')).replace("/", File.separator);
844 String newpolicyName = newPath.replace("/", ".");
845 String newPolicyCheck = newpolicyName;
846 if(newPolicyCheck.contains("Config_")){
847 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
848 }else if(newPolicyCheck.contains("Action_")){
849 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
850 }else if(newPolicyCheck.contains("Decision_")){
851 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
853 String[] newPolicySplit = newPolicyCheck.split(":");
855 String orignalPolicyName = oldPath.replace("/", ".");
856 String oldPolicyCheck = orignalPolicyName;
857 if(oldPolicyCheck.contains("Config_")){
858 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
859 }else if(oldPolicyCheck.contains("Action_")){
860 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
861 }else if(oldPolicyCheck.contains("Decision_")){
862 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
864 String[] oldPolicySplit = oldPolicyCheck.split(":");
866 //Check PolicyEntity table with newPolicy Name
867 String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
868 SimpleBindings policyParams = new SimpleBindings();
869 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
870 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
871 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
872 if(!queryData.isEmpty()){
873 return error("Policy rename failed. Since, the policy with same name already exists.");
876 //Query the Policy Entity with oldPolicy Name
877 String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf('.'));
878 String oldpolicyEntityquery = "FROM PolicyEntity where policyName like :policyEntityCheck and scope = :oldPolicySplit_0";
879 SimpleBindings params = new SimpleBindings();
880 params.put("policyEntityCheck", policyEntityCheck + "%");
881 params.put("oldPolicySplit_0", oldPolicySplit[0]);
882 List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery, params);
883 if(!oldEntityData.isEmpty()){
884 StringBuilder groupQuery = new StringBuilder();
885 groupQuery.append("FROM PolicyGroupEntity where (");
886 SimpleBindings geParams = new SimpleBindings();
887 for(int i=0; i<oldEntityData.size(); i++){
888 entity = (PolicyEntity) oldEntityData.get(i);
890 groupQuery.append("policyid = :policyId");
891 geParams.put("policyId", entity.getPolicyId());
893 groupQuery.append(" or policyid = :policyId" + i);
894 geParams.put("policyId" + i, entity.getPolicyId());
897 groupQuery.append(")");
898 List<Object> groupEntityData = controller.getDataByQuery(groupQuery.toString(), geParams);
899 if(! groupEntityData.isEmpty()){
900 return error("Policy rename failed. Since the policy or its version is active in PDP Groups.");
902 for(int i=0; i<oldEntityData.size(); i++){
903 entity = (PolicyEntity) oldEntityData.get(i);
904 checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0] , newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
907 return error("Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin.");
911 } catch (Exception e) {
912 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
913 return error(e.getMessage());
917 private JSONObject checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, String oldScope, String removeoldPolicyExtension,
918 String policyName, String newpolicyName, String oldpolicyName, String userId) throws ServletException{
920 ConfigurationDataEntity configEntity = entity.getConfigurationData();
921 ActionBodyEntity actionEntity = entity.getActionBodyEntity();
922 PolicyController controller = getPolicyControllerInstance();
924 String oldPolicyNameWithoutExtension = removeoldPolicyExtension;
925 String newPolicyNameWithoutExtension = removenewPolicyExtension;
926 if(removeoldPolicyExtension.endsWith(".xml")){
927 oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf('.'));
928 newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf('.'));
930 entity.setPolicyName(entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
931 entity.setPolicyData(entity.getPolicyData().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
932 entity.setScope(newScope);
933 entity.setModifiedBy(userId);
934 if(newpolicyName.contains("Config_")){
935 String oldConfigurationName = configEntity.getConfigurationName();
936 configEntity.setConfigurationName(configEntity.getConfigurationName().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
937 controller.updateData(configEntity);
938 String newConfigurationName = configEntity.getConfigurationName();
939 File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName);
941 File renamefile = new File(PolicyController.getConfigHome() + File.separator + newConfigurationName);
942 file.renameTo(renamefile);
944 }else if(newpolicyName.contains("Action_")){
945 String oldConfigurationName = actionEntity.getActionBodyName();
946 actionEntity.setActionBody(actionEntity.getActionBody().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
947 controller.updateData(actionEntity);
948 String newConfigurationName = actionEntity.getActionBodyName();
949 File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName);
951 File renamefile = new File(PolicyController.getActionHome() + File.separator + newConfigurationName);
952 file.renameTo(renamefile);
955 controller.updateData(entity);
957 PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldpolicyName);
958 versionEntity.setPolicyName(policyName);
959 versionEntity.setModifiedBy(userId);
960 controller.updateData(versionEntity);
961 String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator)+1);
962 String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
963 if(movePolicyCheck.equals(moveOldPolicyCheck)){
964 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move");
966 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename");
969 } catch (Exception e) {
970 LOGGER.error("Exception Occured"+e);
971 return error(e.getMessage());
975 private JSONObject cloneRecord(String newpolicyName, String oldScope, String inRemoveoldPolicyExtension, String newScope, String removenewPolicyExtension, PolicyEntity entity, String userId) throws ServletException{
976 String queryEntityName;
977 PolicyController controller = getPolicyControllerInstance();
978 PolicyEntity cloneEntity = new PolicyEntity();
979 cloneEntity.setPolicyName(newpolicyName);
980 String removeoldPolicyExtension = inRemoveoldPolicyExtension;
981 removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
982 removenewPolicyExtension = removenewPolicyExtension.replace(".xml", "");
983 cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope+"."+removeoldPolicyExtension, newScope+"."+removenewPolicyExtension));
984 cloneEntity.setScope(entity.getScope());
985 String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
986 String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
987 if(newpolicyName.contains("Config_")){
988 ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
989 configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
990 queryEntityName = configurationDataEntity.getConfigurationName();
991 configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody());
992 configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType());
993 configurationDataEntity.setDeleted(false);
994 configurationDataEntity.setCreatedBy(userId);
995 configurationDataEntity.setModifiedBy(userId);
996 controller.saveData(configurationDataEntity);
997 ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
998 cloneEntity.setConfigurationData(configEntiy);
999 String newConfigurationName = configEntiy.getConfigurationName();
1000 try (FileWriter fw = new FileWriter(PolicyController.getConfigHome() + File.separator + newConfigurationName);
1001 BufferedWriter bw = new BufferedWriter(fw)){
1002 bw.write(configEntiy.getConfigBody());
1003 } catch (IOException e) {
1004 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1006 }else if(newpolicyName.contains("Action_")){
1007 ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
1008 actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1009 queryEntityName = actionBodyEntity.getActionBodyName();
1010 actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody());
1011 actionBodyEntity.setDeleted(false);
1012 actionBodyEntity.setCreatedBy(userId);
1013 actionBodyEntity.setModifiedBy(userId);
1014 controller.saveData(actionBodyEntity);
1015 ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class, "actionBodyName", queryEntityName);
1016 cloneEntity.setActionBodyEntity(actionEntiy);
1017 String newConfigurationName = actionEntiy.getActionBodyName();
1018 try (FileWriter fw = new FileWriter(PolicyController.getActionHome() + File.separator + newConfigurationName);
1019 BufferedWriter bw = new BufferedWriter(fw)){
1020 bw.write(actionEntiy.getActionBody());
1021 } catch (IOException e) {
1022 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1025 cloneEntity.setDeleted(entity.isDeleted());
1026 cloneEntity.setCreatedBy(userId);
1027 cloneEntity.setModifiedBy(userId);
1028 controller.saveData(cloneEntity);
1034 private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
1036 String userId = UserUtils.getUserSession(request).getOrgUserId();
1037 String oldPath = params.getString("path");
1038 String newPath = params.getString("newPath");
1039 oldPath = oldPath.substring(oldPath.indexOf('/')+1);
1040 newPath = newPath.substring(newPath.indexOf('/')+1);
1042 String policyVersionName = newPath.replace(".xml", "");
1043 String version = policyVersionName.substring(policyVersionName.indexOf('.')+1);
1044 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')).replace("/", File.separator);
1046 String newpolicyName = newPath.replace("/", ".");
1048 String orignalPolicyName = oldPath.replace("/", ".");
1050 String newPolicyCheck = newpolicyName;
1051 if(newPolicyCheck.contains("Config_")){
1052 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
1053 }else if(newPolicyCheck.contains("Action_")){
1054 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
1055 }else if(newPolicyCheck.contains("Decision_")){
1056 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
1058 String[] newPolicySplit = newPolicyCheck.split(":");
1060 String oldPolicyCheck = orignalPolicyName;
1061 if(oldPolicyCheck.contains("Config_")){
1062 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
1063 }else if(oldPolicyCheck.contains("Action_")){
1064 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
1065 }else if(oldPolicyCheck.contains("Decision_")){
1066 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
1068 String[] oldPolicySplit = oldPolicyCheck.split(":");
1070 PolicyController controller = getPolicyControllerInstance();
1072 PolicyEntity entity = null;
1073 boolean success = false;
1075 //Check PolicyEntity table with newPolicy Name
1076 String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
1077 SimpleBindings policyParams = new SimpleBindings();
1078 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
1079 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
1080 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
1081 if(!queryData.isEmpty()){
1082 return error("Policy already exists with same name");
1085 //Query the Policy Entity with oldPolicy Name
1086 policyEntityquery = "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0";
1087 SimpleBindings peParams = new SimpleBindings();
1088 peParams.put("oldPolicySplit_1", oldPolicySplit[1]);
1089 peParams.put("oldPolicySplit_0", oldPolicySplit[0]);
1090 queryData = controller.getDataByQuery(policyEntityquery, peParams);
1091 if(!queryData.isEmpty()){
1092 entity = (PolicyEntity) queryData.get(0);
1095 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId);
1100 PolicyVersion entityItem = new PolicyVersion();
1101 entityItem.setActiveVersion(Integer.parseInt(version));
1102 entityItem.setHigherVersion(Integer.parseInt(version));
1103 entityItem.setPolicyName(policyName);
1104 entityItem.setCreatedBy(userId);
1105 entityItem.setModifiedBy(userId);
1106 entityItem.setModifiedDate(new Date());
1107 controller.saveData(entityItem);
1110 LOGGER.debug("copy from: {} to: {}" + oldPath +newPath);
1113 } catch (Exception e) {
1114 LOGGER.error("copy", e);
1115 return error(e.getMessage());
1119 //Delete Policy or Scope Functionality
1120 private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
1121 PolicyController controller = getPolicyControllerInstance();
1122 PolicyRestController restController = new PolicyRestController();
1123 PolicyEntity policyEntity = null;
1124 String policyNamewithoutExtension;
1126 String userId = UserUtils.getUserSession(request).getOrgUserId();
1127 String deleteVersion = "";
1128 String path = params.getString("path");
1129 LOGGER.debug("delete {}" +path);
1130 if(params.has("deleteVersion")){
1131 deleteVersion = params.getString("deleteVersion");
1133 path = path.substring(path.indexOf('/')+1);
1134 String policyNamewithExtension = path.replace("/", File.separator);
1135 String policyVersionName = policyNamewithExtension.replace(".xml", "");
1137 SimpleBindings policyParams = new SimpleBindings();
1138 if(path.endsWith(".xml")){
1139 policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf('.'));
1140 policyNamewithoutExtension = policyNamewithoutExtension.replace(File.separator, ".");
1141 String splitPolicyName = null;
1142 if(policyNamewithoutExtension.contains("Config_")){
1143 splitPolicyName = policyNamewithoutExtension.replace(".Config_", ":Config_");
1144 }else if(policyNamewithoutExtension.contains("Action_")){
1145 splitPolicyName = policyNamewithoutExtension.replace(".Action_", ":Action_");
1146 }else if(policyNamewithoutExtension.contains("Decision_")){
1147 splitPolicyName = policyNamewithoutExtension.replace(".Decision_", ":Decision_");
1149 String[] split = splitPolicyName.split(":");
1151 query = "FROM PolicyEntity where policyName like :split_1 and scope = :split_0";
1152 policyParams.put("split_1", split[1] + "%");
1153 policyParams.put("split_0", split[0]);
1155 policyNamewithoutExtension = path.replace(File.separator, ".");
1156 query = "FROM PolicyEntity where scope like :policyNamewithoutExtension";
1157 policyParams.put("policyNamewithoutExtension", policyNamewithoutExtension + "%");
1160 List<Object> policyEntityobjects = controller.getDataByQuery(query, policyParams);
1161 String activePolicyName = null;
1162 boolean pdpCheck = false;
1163 if(path.endsWith(".xml")){
1164 policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator);
1165 int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf('.')+1));
1166 if("ALL".equals(deleteVersion)){
1167 if(!policyEntityobjects.isEmpty()){
1168 for(Object object : policyEntityobjects){
1169 policyEntity = (PolicyEntity) object;
1170 String groupEntityquery = "from PolicyGroupEntity where policyid ='"+policyEntity.getPolicyId()+"'";
1171 SimpleBindings pgeParams = new SimpleBindings();
1172 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, pgeParams);
1173 if(!groupobject.isEmpty()){
1175 activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName();
1177 //Delete the entity from Elastic Search Database
1178 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1179 restController.deleteElasticData(searchFileName);
1180 //Delete the entity from Policy Entity table
1181 controller.deleteData(policyEntity);
1182 if(policyNamewithoutExtension.contains("Config_")){
1183 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1184 controller.deleteData(policyEntity.getConfigurationData());
1185 }else if(policyNamewithoutExtension.contains("Action_")){
1186 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1187 controller.deleteData(policyEntity.getActionBodyEntity());
1192 //Policy Notification
1193 PolicyVersion versionEntity = new PolicyVersion();
1194 versionEntity.setPolicyName(policyNamewithoutExtension);
1195 versionEntity.setModifiedBy(userId);
1196 controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll");
1198 //Delete from policyVersion table
1199 String getActivePDPPolicyVersion = activePolicyName.replace(".xml", "");
1200 getActivePDPPolicyVersion = getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf('.')+1);
1201 String policyVersionQuery = "update PolicyVersion set active_version='"+getActivePDPPolicyVersion+"' , highest_version='"+getActivePDPPolicyVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1202 if(policyVersionQuery != null){
1203 controller.executeQuery(policyVersionQuery);
1205 return error("Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "+activePolicyName);
1207 //No Active Policy in PDP. So, deleting all entries from policyVersion table
1208 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1209 if(policyVersionQuery != null){
1210 controller.executeQuery(policyVersionQuery);
1213 }else if("CURRENT".equals(deleteVersion)){
1214 String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1);
1215 String currentVersionScope = policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator)).replace(File.separator, ".");
1216 query = "FROM PolicyEntity where policyName = :currentVersionPolicyName and scope = :currentVersionScope";
1218 SimpleBindings peParams = new SimpleBindings();
1219 peParams.put("currentVersionPolicyName", currentVersionPolicyName);
1220 peParams.put("currentVersionScope", currentVersionScope);
1222 List<Object> policyEntitys = controller.getDataByQuery(query, peParams);
1223 if(!policyEntitys.isEmpty()){
1224 policyEntity = (PolicyEntity) policyEntitys.get(0);
1226 if(policyEntity != null){
1227 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId and policyid > 0";
1228 SimpleBindings geParams = new SimpleBindings();
1229 geParams.put("policyEntityId", policyEntity.getPolicyId());
1230 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1231 if(groupobject.isEmpty()){
1232 //Delete the entity from Elastic Search Database
1233 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1234 restController.deleteElasticData(searchFileName);
1235 //Delete the entity from Policy Entity table
1236 controller.deleteData(policyEntity);
1237 if(policyNamewithoutExtension.contains("Config_")){
1238 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1239 controller.deleteData(policyEntity.getConfigurationData());
1240 }else if(policyNamewithoutExtension.contains("Action_")){
1241 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1242 controller.deleteData(policyEntity.getActionBodyEntity());
1246 int highestVersion = 0;
1247 if(!policyEntityobjects.isEmpty()){
1248 for(Object object : policyEntityobjects){
1249 policyEntity = (PolicyEntity) object;
1250 String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
1251 int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf('.')+1));
1252 if(policyEntityVersion > highestVersion && policyEntityVersion != version){
1253 highestVersion = policyEntityVersion;
1258 //Policy Notification
1259 PolicyVersion entity = new PolicyVersion();
1260 entity.setPolicyName(policyNamewithoutExtension);
1261 entity.setActiveVersion(highestVersion);
1262 entity.setModifiedBy(userId);
1263 controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne");
1265 String updatequery = "update PolicyVersion set active_version='"+highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"'";
1266 controller.executeQuery(updatequery);
1268 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1269 if(policyVersionQuery != null){
1270 controller.executeQuery(policyVersionQuery);
1274 return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'");
1279 List<String> activePoliciesInPDP = new ArrayList<>();
1280 if(!policyEntityobjects.isEmpty()){
1281 for(Object object : policyEntityobjects){
1282 policyEntity = (PolicyEntity) object;
1283 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId";
1284 SimpleBindings geParams = new SimpleBindings();
1285 geParams.put("policyEntityId", policyEntity.getPolicyId());
1286 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1287 if(!groupobject.isEmpty()){
1289 activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName());
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 policyNamewithoutExtension = policyEntity.getPolicyName();
1297 if(policyNamewithoutExtension.contains("Config_")){
1298 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1299 controller.deleteData(policyEntity.getConfigurationData());
1300 }else if(policyNamewithoutExtension.contains("Action_")){
1301 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1302 controller.deleteData(policyEntity.getActionBodyEntity());
1306 //Delete from policyVersion and policyEditor Scope table
1307 String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1308 controller.executeQuery(policyVersionQuery);
1310 //Policy Notification
1311 PolicyVersion entity = new PolicyVersion();
1312 entity.setPolicyName(path);
1313 entity.setModifiedBy(userId);
1314 controller.watchPolicyFunction(entity, path, "DeleteScope");
1316 //Add Active Policies List to PolicyVersionTable
1317 for(int i =0; i < activePoliciesInPDP.size(); i++){
1318 String activePDPPolicyName = activePoliciesInPDP.get(i).replace(".xml", "");
1319 int activePDPPolicyVersion = Integer.parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf('.')+1));
1320 activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf('.')).replace(".", File.separator);
1321 PolicyVersion insertactivePDPVersion = new PolicyVersion();
1322 insertactivePDPVersion.setPolicyName(activePDPPolicyName);
1323 insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion);
1324 insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion);
1325 insertactivePDPVersion.setCreatedBy(userId);
1326 insertactivePDPVersion.setModifiedBy(userId);
1327 controller.saveData(insertactivePDPVersion);
1330 return error("All the Policies has been deleted in Scope. Except the following list of Policies:"+activePoliciesInPDP);
1332 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1333 controller.executeQuery(policyScopeQuery);
1336 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1337 controller.executeQuery(policyScopeQuery);
1341 } catch (Exception e) {
1342 LOGGER.error("delete", e);
1343 return error(e.getMessage());
1348 private JSONObject editFile(JSONObject params) throws ServletException {
1351 PolicyController controller = getPolicyControllerInstance();
1352 String mode = params.getString("mode");
1353 String path = params.getString("path");
1354 LOGGER.debug("editFile path: {}"+ path);
1356 String domain = path.substring(1, path.lastIndexOf('/'));
1357 domain = domain.replace("/", ".");
1359 path = path.substring(1);
1360 path = path.replace("/", ".");
1361 String dbCheckName = path;
1362 if(dbCheckName.contains("Config_")){
1363 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
1364 }else if(dbCheckName.contains("Action_")){
1365 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
1366 }else if(dbCheckName.contains("Decision_")){
1367 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
1370 String[] split = dbCheckName.split(":");
1371 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
1372 SimpleBindings peParams = new SimpleBindings();
1373 peParams.put("split_1", split[1]);
1374 peParams.put("split_0", split[0]);
1375 List<Object> queryData;
1376 if(PolicyController.isjUnit()){
1377 queryData = controller.getDataByQuery(query, null);
1379 queryData = controller.getDataByQuery(query, peParams);
1381 PolicyEntity entity = (PolicyEntity) queryData.get(0);
1382 InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
1385 Object policy = XACMLPolicyScanner.readPolicy(stream);
1386 PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
1387 policyAdapter.setData(policy);
1389 if("viewPolicy".equalsIgnoreCase(mode)){
1390 policyAdapter.setReadOnly(true);
1391 policyAdapter.setEditPolicy(false);
1393 policyAdapter.setReadOnly(false);
1394 policyAdapter.setEditPolicy(true);
1397 policyAdapter.setDomainDir(domain);
1398 policyAdapter.setPolicyData(policy);
1399 String policyName = path.replace(".xml", "");
1400 policyName = policyName.substring(0, policyName.lastIndexOf('.'));
1401 policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf('.')+1));
1403 PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance();
1404 setpolicyAdapter.configure(policyAdapter,entity);
1406 policyAdapter.setParentPath(null);
1407 ObjectMapper mapper = new ObjectMapper();
1408 String json = mapper.writeValueAsString(policyAdapter);
1409 JsonNode jsonNode = mapper.readTree(json);
1411 return new JSONObject().put(RESULT, jsonNode);
1412 } catch (Exception e) {
1413 LOGGER.error("editFile", e);
1414 return error(e.getMessage());
1419 private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
1420 PolicyController controller = getPolicyControllerInstance();
1423 String userId = UserUtils.getUserSession(request).getOrgUserId();
1424 String path = params.getString("path");
1426 if(params.has("subScopename")){
1427 if(! "".equals(params.getString("subScopename"))) {
1428 name = params.getString("path").replace("/", File.separator) + File.separator +params.getString("subScopename");
1431 name = params.getString("name");
1433 }catch(Exception e){
1434 name = params.getString("name");
1435 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e);
1437 String validateName;
1438 if(name.contains(File.separator)){
1439 validateName = name.substring(name.lastIndexOf(File.separator)+1);
1441 validateName = name;
1443 if(!name.isEmpty()){
1444 String validate = PolicyUtils.policySpecialCharValidator(validateName);
1445 if(!validate.contains("success")){
1446 return error(validate);
1449 LOGGER.debug("addFolder path: {} name: {}" + path +name);
1450 if(! "".equals(name)){
1451 if(name.startsWith(File.separator)){
1452 name = name.substring(1);
1454 PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, "scopeName", name);
1456 UserInfo userInfo = new UserInfo();
1457 userInfo.setUserLoginId(userId);
1458 PolicyEditorScopes newScope = new PolicyEditorScopes();
1459 newScope.setScopeName(name);
1460 newScope.setUserCreatedBy(userInfo);
1461 newScope.setUserModifiedBy(userInfo);
1462 controller.saveData(newScope);
1464 return error("Scope Already Exists");
1468 } catch (Exception e) {
1469 LOGGER.error("addFolder", e);
1470 return error(e.getMessage());
1474 //Return Error Object
1475 private JSONObject error(String msg) throws ServletException {
1477 JSONObject result = new JSONObject();
1478 result.put("success", false);
1479 result.put("error", msg);
1480 return new JSONObject().put(RESULT, result);
1481 } catch (JSONException e) {
1482 throw new ServletException(e);
1486 //Return Success Object
1487 private JSONObject success() throws ServletException {
1489 JSONObject result = new JSONObject();
1490 result.put("success", true);
1491 result.put("error", (Object) null);
1492 return new JSONObject().put(RESULT, result);
1493 } catch (JSONException e) {
1494 throw new ServletException(e);
1498 private PolicyController getPolicyControllerInstance(){
1499 return policyController != null ? getPolicyController() : new PolicyController();
1502 public String getTestUserId() {
1506 public static void setTestUserId(String testUserId) {
1507 PolicyManagerServlet.testUserId = testUserId;