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.FileNotFoundException;
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.Path;
37 import java.nio.file.Paths;
38 import java.util.ArrayList;
39 import java.util.HashMap;
40 import java.util.HashSet;
41 import java.util.List;
45 import javax.json.Json;
46 import javax.json.JsonArray;
47 import javax.json.JsonReader;
48 import javax.script.SimpleBindings;
49 import javax.servlet.ServletConfig;
50 import javax.servlet.ServletException;
51 import javax.servlet.annotation.WebInitParam;
52 import javax.servlet.annotation.WebServlet;
53 import javax.servlet.http.HttpServlet;
54 import javax.servlet.http.HttpServletRequest;
55 import javax.servlet.http.HttpServletResponse;
57 import org.apache.commons.compress.utils.IOUtils;
58 import org.apache.commons.fileupload.FileItem;
59 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
60 import org.apache.commons.fileupload.servlet.ServletFileUpload;
61 import org.apache.http.HttpStatus;
62 import org.json.JSONArray;
63 import org.json.JSONException;
64 import org.json.JSONObject;
65 import org.onap.policy.common.logging.flexlogger.FlexLogger;
66 import org.onap.policy.common.logging.flexlogger.Logger;
67 import org.onap.policy.components.HumanPolicyComponent;
68 import org.onap.policy.controller.PolicyController;
69 import org.onap.policy.controller.PolicyExportAndImportController;
70 import org.onap.policy.rest.XACMLRest;
71 import org.onap.policy.rest.XACMLRestProperties;
72 import org.onap.policy.rest.adapter.PolicyRestAdapter;
73 import org.onap.policy.rest.jpa.ActionBodyEntity;
74 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
75 import org.onap.policy.rest.jpa.PolicyEditorScopes;
76 import org.onap.policy.rest.jpa.PolicyEntity;
77 import org.onap.policy.rest.jpa.PolicyVersion;
78 import org.onap.policy.rest.jpa.UserInfo;
79 import org.onap.policy.utils.PolicyUtils;
80 import org.onap.policy.xacml.api.XACMLErrorConstants;
81 import org.onap.policy.xacml.util.XACMLPolicyScanner;
82 import org.openecomp.policy.model.Roles;
83 import org.openecomp.portalsdk.core.web.support.UserUtils;
85 import com.att.research.xacml.util.XACMLProperties;
86 import com.fasterxml.jackson.databind.JsonNode;
87 import com.fasterxml.jackson.databind.ObjectMapper;
90 @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.") })
91 public class PolicyManagerServlet extends HttpServlet {
92 private static final Logger LOGGER = FlexLogger.getLogger(PolicyManagerServlet.class);
93 private static final long serialVersionUID = -8453502699403909016L;
96 LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT, SEARCHLIST
99 private static PolicyController policyController;
100 public synchronized PolicyController getPolicyController() {
101 return policyController;
104 public synchronized static void setPolicyController(PolicyController policyController) {
105 PolicyManagerServlet.policyController = policyController;
108 private static String CONTENTTYPE = "application/json";
109 private static String SUPERADMIN = "super-admin";
110 private static String SUPEREDITOR = "super-editor";
111 private static String SUPERGUEST = "super-guest";
112 private static String ADMIN = "admin";
113 private static String EDITOR = "editor";
114 private static String GUEST = "guest";
115 private static String RESULT = "result";
117 private static Path closedLoopJsonLocation;
118 private static JsonArray policyNames;
119 private static String testUserId = null;
121 public static JsonArray getPolicyNames() {
125 public static void setPolicyNames(JsonArray policyNames) {
126 PolicyManagerServlet.policyNames = policyNames;
129 private static List<String> serviceTypeNamesList = new ArrayList<>();
131 public static List<String> getServiceTypeNamesList() {
132 return serviceTypeNamesList;
136 public void init(ServletConfig servletConfig) throws ServletException {
137 super.init(servletConfig);
139 // Common initialization
141 XACMLRest.xacmlInit(servletConfig);
143 //Initialize ClosedLoop JSON
145 PolicyManagerServlet.initializeJSONLoad();
148 protected static void initializeJSONLoad() {
149 closedLoopJsonLocation = Paths.get(XACMLProperties
150 .getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP));
151 FileInputStream inputStream = null;
152 JsonReader jsonReader = null;
153 String location = closedLoopJsonLocation.toString();
155 inputStream = new FileInputStream(location);
156 if (location.endsWith("json")) {
157 jsonReader = Json.createReader(inputStream);
158 policyNames = jsonReader.readArray();
159 serviceTypeNamesList = new ArrayList<>();
160 for (int i = 0; i < policyNames.size(); i++) {
161 javax.json.JsonObject policyName = policyNames.getJsonObject(i);
162 String name = policyName.getJsonString("serviceTypePolicyName").getString();
163 serviceTypeNamesList.add(name);
166 } catch (FileNotFoundException e) {
167 LOGGER.error("Exception Occured while initializing the JSONConfig file"+e);
170 if(inputStream != null){
173 if(jsonReader != null){
176 } catch (IOException e) {
177 LOGGER.error("Exception Occured while closing the File InputStream"+e);
183 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
184 LOGGER.debug("doPost");
186 // if request contains multipart-form-data
187 if (ServletFileUpload.isMultipartContent(request)) {
188 uploadFile(request, response);
190 // all other post request has json params in body
192 fileOperation(request, response);
194 } catch (Exception e) {
196 setError(e, response);
197 }catch(Exception e1){
198 LOGGER.error("Exception Occured"+e1);
203 //Set Error Message for Exception
204 private void setError(Exception t, HttpServletResponse response) throws IOException {
206 JSONObject responseJsonObject = error(t.getMessage());
207 response.setContentType(CONTENTTYPE);
208 PrintWriter out = response.getWriter();
209 out.print(responseJsonObject);
211 } catch (Exception x) {
212 LOGGER.error("Exception Occured"+x);
213 response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage());
217 //Policy Import Functionality
218 private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException {
221 Map<String, InputStream> files = new HashMap<>();
223 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
224 for (FileItem item : items) {
225 if (!item.isFormField()) {
226 // Process form file field (input type="file").
227 files.put(item.getName(), item.getInputStream());
228 if(item.getName().endsWith(".xls")){
229 OutputStream outputStream = null;
231 File file = new File(item.getName());
232 outputStream = new FileOutputStream(file);
233 IOUtils.copy(item.getInputStream(), outputStream);
234 outputStream.close();
235 newFile = file.toString();
236 PolicyExportAndImportController importController = new PolicyExportAndImportController();
237 importController.importRepositoryFile(newFile, request);
239 LOGGER.error("Upload error : " + e);
241 if(outputStream != null){
242 outputStream.close();
249 JSONObject responseJsonObject = null;
250 responseJsonObject = this.success();
251 response.setContentType(CONTENTTYPE);
252 PrintWriter out = response.getWriter();
253 out.print(responseJsonObject);
255 } catch (Exception e) {
256 LOGGER.debug("Cannot write file");
257 throw new ServletException("Cannot write file", e);
261 //File Operation Functionality
262 private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
263 JSONObject responseJsonObject = null;
265 StringBuilder sb = new StringBuilder();
266 BufferedReader br = request.getReader();
268 while ((str = br.readLine()) != null) {
272 JSONObject jObj = new JSONObject(sb.toString());
273 JSONObject params = jObj.getJSONObject("params");
274 Mode mode = Mode.valueOf(params.getString("mode"));
278 responseJsonObject = addFolder(params, request);
281 responseJsonObject = copy(params, request);
284 responseJsonObject = delete(params, request);
288 responseJsonObject = editFile(params);
291 responseJsonObject = list(params, request);
294 responseJsonObject = rename(params, request);
296 case DESCRIBEPOLICYFILE:
297 responseJsonObject = describePolicy(params);
300 responseJsonObject = switchVersion(params, request);
303 responseJsonObject = searchPolicyList(params, request);
306 throw new ServletException("not implemented");
308 if (responseJsonObject == null) {
309 responseJsonObject = error("generic error : responseJsonObject is null");
311 } catch (Exception e) {
312 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While doing File Operation" + e);
313 responseJsonObject = error(e.getMessage());
315 response.setContentType(CONTENTTYPE);
316 PrintWriter out = response.getWriter();
317 out.print(responseJsonObject);
321 private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) {
322 Set<String> scopes = null;
323 List<String> roles = null;
324 List<Object> policyData = new ArrayList<>();
325 JSONArray policyList = null;
326 if(params.has("policyList")){
327 policyList = (JSONArray) params.get("policyList");
329 PolicyController controller = getPolicyControllerInstance();
330 List<JSONObject> resultList = new ArrayList<>();
332 //Get the Login Id of the User from Request
333 String userId = UserUtils.getUserSession(request).getOrgUserId();
334 //Check if the Role and Scope Size are Null get the values from db.
335 List<Object> userRoles = controller.getRoles(userId);
336 roles = new ArrayList<>();
337 scopes = new HashSet<>();
338 for(Object role: userRoles){
339 Roles userRole = (Roles) role;
340 roles.add(userRole.getRole());
341 if(userRole.getScope() != null){
342 if(userRole.getScope().contains(",")){
343 String[] multipleScopes = userRole.getScope().split(",");
344 for(int i =0; i < multipleScopes.length; i++){
345 scopes.add(multipleScopes[i]);
348 scopes.add(userRole.getScope());
352 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
353 if(scopes.isEmpty()){
354 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
356 Set<String> tempScopes = scopes;
357 for(String scope : tempScopes){
358 List<Object> scopesList = queryPolicyEditorScopes(scope);
359 if(!scopesList.isEmpty()){
360 for(int i = 0; i < scopesList.size(); i++){
361 PolicyEditorScopes tempScope = (PolicyEditorScopes) scopesList.get(i);
362 scopes.add(tempScope.getScopeName());
367 if(policyList!= null){
368 for(int i = 0; i < policyList.length(); i++){
369 String policyName = policyList.get(i).toString().replace(".xml", "");
370 String version = policyName.substring(policyName.lastIndexOf(".")+1);
371 policyName = policyName.substring(0, policyName.lastIndexOf(".")).replace(".", File.separator);
372 if(policyName.contains("\\")){
373 policyName = policyName.replace("\\", "\\\\");
375 String policyVersionQuery = "From PolicyVersion where policy_name = :policyName and active_version = :version and id >0";
376 SimpleBindings pvParams = new SimpleBindings();
377 pvParams.put("policyName", policyName);
378 pvParams.put("version", version);
379 List<Object> activeData = controller.getDataByQuery(policyVersionQuery, pvParams);
380 if(!activeData.isEmpty()){
381 PolicyVersion policy = (PolicyVersion) activeData.get(0);
382 JSONObject el = new JSONObject();
383 el.put("name", policy.getPolicyName().replace(File.separator, "/"));
384 el.put("date", policy.getModifiedDate());
385 el.put("version", policy.getActiveVersion());
387 el.put("type", "file");
388 el.put("createdBy", getUserName(policy.getCreatedBy()));
389 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
394 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ){
395 policyData = controller.getData(PolicyVersion.class);
397 List<Object> filterdatas = controller.getData(PolicyVersion.class);
398 for(Object filter : filterdatas){
399 PolicyVersion filterdata = (PolicyVersion) filter;
401 String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator));
402 if(scopes.contains(scopeName)){
403 policyData.add(filterdata);
406 LOGGER.error("Exception occured while filtering policyversion data"+e);
411 if(!policyData.isEmpty()){
412 for(int i =0; i < policyData.size(); i++){
413 PolicyVersion policy = (PolicyVersion) policyData.get(i);
414 JSONObject el = new JSONObject();
415 el.put("name", policy.getPolicyName().replace(File.separator, "/"));
416 el.put("date", policy.getModifiedDate());
417 el.put("version", policy.getActiveVersion());
419 el.put("type", "file");
420 el.put("createdBy", getUserName(policy.getCreatedBy()));
421 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
427 LOGGER.error("Exception occured while reading policy Data from Policy Version table for Policy Search Data"+e);
430 return new JSONObject().put(RESULT, resultList);
433 //Switch Version Functionality
434 private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{
435 String path = params.getString("path");
436 String userId = null;
438 userId = UserUtils.getUserSession(request).getOrgUserId();
439 } catch (Exception e) {
440 LOGGER.error("Exception Occured while reading userid from cookie" +e);
443 String removeExtension = path.replace(".xml", "");
444 if(path.startsWith("/")){
445 policyName = removeExtension.substring(1, removeExtension.lastIndexOf("."));
447 policyName = removeExtension.substring(0, removeExtension.lastIndexOf("."));
450 String activePolicy = null;
451 PolicyController controller = getPolicyControllerInstance();
452 if(params.toString().contains("activeVersion")){
453 String activeVersion = params.getString("activeVersion");
454 String highestVersion = params.get("highestVersion").toString();
455 if(Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)){
456 return error("The Version shouldn't be greater than Highest Value");
458 activePolicy = policyName + "." + activeVersion + ".xml";
459 String dbCheckName = activePolicy.replace("/", ".");
460 if(dbCheckName.contains("Config_")){
461 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
462 }else if(dbCheckName.contains("Action_")){
463 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
464 }else if(dbCheckName.contains("Decision_")){
465 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
467 String[] splitDBCheckName = dbCheckName.split(":");
468 String peQuery = "FROM PolicyEntity where policyName = :splitDBCheckName_1 and scope = :splitDBCheckName_0";
469 SimpleBindings policyParams = new SimpleBindings();
470 policyParams.put("splitDBCheckName_1", splitDBCheckName[1]);
471 policyParams.put("splitDBCheckName_0", splitDBCheckName[0]);
472 List<Object> policyEntity = controller.getDataByQuery(peQuery, policyParams);
473 PolicyEntity pentity = (PolicyEntity) policyEntity.get(0);
474 if(pentity.isDeleted()){
475 return error("The Policy is Not Existing in Workspace");
477 if(policyName.contains("/")){
478 policyName = policyName.replace("/", File.separator);
480 policyName = policyName.substring(policyName.indexOf(File.separator)+1);
481 if(policyName.contains("\\")){
482 policyName = policyName.replace(File.separator, "\\");
484 policyName = splitDBCheckName[0].replace(".", File.separator)+File.separator+policyName;
485 String watchPolicyName = policyName;
486 if(policyName.contains("/")){
487 policyName = policyName.replace("/", File.separator);
489 if(policyName.contains("\\")){
490 policyName = policyName.replace("\\", "\\\\");
492 String query = "update PolicyVersion set active_version='"+activeVersion+"' where policy_name ='"+policyName+"' and id >0";
494 controller.executeQuery(query);
495 //Policy Notification
496 PolicyVersion entity = new PolicyVersion();
497 entity.setPolicyName(watchPolicyName);
498 entity.setActiveVersion(Integer.parseInt(activeVersion));
499 entity.setModifiedBy(userId);
500 controller.watchPolicyFunction(entity, activePolicy, "SwitchVersion");
505 return controller.switchVersionPolicyContent(policyName);
509 private JSONObject describePolicy(JSONObject params) throws ServletException{
510 JSONObject object = null;
511 String path = params.getString("path");
512 String policyName = null;
513 if(path.startsWith("/")){
514 path = path.substring(1);
515 policyName = path.substring(path.lastIndexOf("/") +1);
516 path = path.replace("/", ".");
518 path = path.replace("/", ".");
521 if(path.contains("Config_")){
522 path = path.replace(".Config_", ":Config_");
523 }else if(path.contains("Action_")){
524 path = path.replace(".Action_", ":Action_");
525 }else if(path.contains("Decision_")){
526 path = path.replace(".Decision_", ":Decision_");
528 PolicyController controller = getPolicyControllerInstance();
529 String[] split = path.split(":");
530 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
531 SimpleBindings peParams = new SimpleBindings();
532 peParams.put("split_1", split[1]);
533 peParams.put("split_0", split[0]);
534 List<Object> queryData = controller.getDataByQuery(query, peParams);
535 if(!queryData.isEmpty()){
536 PolicyEntity entity = (PolicyEntity) queryData.get(0);
538 BufferedWriter bw = null;
540 temp = File.createTempFile(policyName, ".tmp");
541 bw = new BufferedWriter(new FileWriter(temp));
542 bw.write(entity.getPolicyData());
544 object = HumanPolicyComponent.DescribePolicy(temp);
545 } catch (IOException e) {
546 LOGGER.error("Exception Occured while Describing the Policy"+e);
554 } catch (IOException e) {
555 LOGGER.error("Exception Occured while Closing the File Writer"+e);
560 return error("Error Occured while Describing the Policy");
566 //Get the List of Policies and Scopes for Showing in Editor tab
567 private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException {
568 Set<String> scopes = null;
569 List<String> roles = null;
571 PolicyController controller = getPolicyControllerInstance();
572 //Get the Login Id of the User from Request
573 String testUserID = getTestUserId();
574 String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId();
575 //Check if the Role and Scope Size are Null get the values from db.
576 List<Object> userRoles = controller.getRoles(userId);
577 roles = new ArrayList<>();
578 scopes = new HashSet<>();
579 for(Object role: userRoles){
580 Roles userRole = (Roles) role;
581 roles.add(userRole.getRole());
582 if(userRole.getScope() != null){
583 if(userRole.getScope().contains(",")){
584 String[] multipleScopes = userRole.getScope().split(",");
585 for(int i =0; i < multipleScopes.length; i++){
586 scopes.add(multipleScopes[i]);
589 scopes.add(userRole.getScope());
594 List<JSONObject> resultList = new ArrayList<>();
595 boolean onlyFolders = params.getBoolean("onlyFolders");
596 String path = params.getString("path");
597 if(path.contains("..xml")){
598 path = path.replaceAll("..xml", "").trim();
601 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
602 if(scopes.isEmpty()){
603 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
605 if(!"/".equals(path)){
606 String tempScope = path.substring(1, path.length());
607 tempScope = tempScope.replace("/", File.separator);
608 scopes.add(tempScope);
613 if("/".equals(path)){
614 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
615 List<Object> scopesList = queryPolicyEditorScopes(null);
616 for(Object list : scopesList){
617 PolicyEditorScopes scope = (PolicyEditorScopes) list;
618 if(!(scope.getScopeName().contains(File.separator))){
619 JSONObject el = new JSONObject();
620 el.put("name", scope.getScopeName());
621 el.put("date", scope.getCreatedDate());
623 el.put("type", "dir");
624 el.put("createdBy", scope.getUserCreatedBy().getUserName());
625 el.put("modifiedBy", scope.getUserModifiedBy().getUserName());
629 }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){
630 for(Object scope : scopes){
631 JSONObject el = new JSONObject();
632 List<Object> scopesList = queryPolicyEditorScopes(scope.toString());
633 if(!scopesList.isEmpty()){
634 PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
635 el.put("name", scopeById.getScopeName());
636 el.put("date", scopeById.getCreatedDate());
638 el.put("type", "dir");
639 el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
640 el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
647 String scopeName = path.substring(path.indexOf("/") +1);
648 activePolicyList(scopeName, resultList, roles, scopes, onlyFolders);
649 } catch (Exception ex) {
650 LOGGER.error("Error Occured While reading Policy Files List"+ex );
654 return new JSONObject().put(RESULT, resultList);
655 } catch (Exception e) {
656 LOGGER.error("list", e);
657 return error(e.getMessage());
661 private List<Object> queryPolicyEditorScopes(String scopeName){
662 String scopeNamequery = "";
663 SimpleBindings params = new SimpleBindings();
664 if(scopeName == null){
665 scopeNamequery = "from PolicyEditorScopes";
667 scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
668 params.put("scopeName", scopeName + "%");
670 PolicyController controller = getPolicyControllerInstance();
671 List<Object> scopesList = controller.getDataByQuery(scopeNamequery, params);
675 //Get Active Policy List based on Scope Selection form Policy Version table
676 private void activePolicyList(String scopeName, List<JSONObject> resultList, List<String> roles, Set<String> scopes, boolean onlyFolders){
677 PolicyController controller = getPolicyControllerInstance();
678 if(scopeName.contains("/")){
679 scopeName = scopeName.replace("/", File.separator);
681 if(scopeName.contains("\\")){
682 scopeName = scopeName.replace("\\", "\\\\\\\\");
684 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
685 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
687 SimpleBindings params = new SimpleBindings();
688 params.put("scopeName", scopeName + "%");
690 List<Object> activePolicies = controller.getDataByQuery(query, params);
691 List<Object> scopesList = controller.getDataByQuery(scopeNamequery, params);
692 for(Object list : scopesList){
693 PolicyEditorScopes scopeById = (PolicyEditorScopes) list;
694 String scope = scopeById.getScopeName();
695 if(scope.contains(File.separator)){
696 String checkScope = scope.substring(0, scope.lastIndexOf(File.separator));
697 if(scopeName.contains("\\\\")){
698 scopeName = scopeName.replace("\\\\", File.separator);
700 if(scope.contains(File.separator)){
701 scope = scope.substring(checkScope.length()+1);
702 if(scope.contains(File.separator)){
703 scope = scope.substring(0, scope.indexOf(File.separator));
706 if(scopeName.equalsIgnoreCase(checkScope)){
707 JSONObject el = new JSONObject();
708 el.put("name", scope);
709 el.put("date", scopeById.getModifiedDate());
711 el.put("type", "dir");
712 el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
713 el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
718 String scopeNameCheck = null;
719 for (Object list : activePolicies) {
720 PolicyVersion policy = (PolicyVersion) list;
721 String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator));
722 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
723 if((scopeName.contains("\\\\"))){
724 scopeNameCheck = scopeName.replace("\\\\", File.separator);
726 scopeNameCheck = scopeName;
728 if(scopeNameValue.equals(scopeNameCheck)){
729 JSONObject el = new JSONObject();
730 el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
731 el.put("date", policy.getModifiedDate());
732 el.put("version", policy.getActiveVersion());
734 el.put("type", "file");
735 el.put("createdBy", getUserName(policy.getCreatedBy()));
736 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
739 }else if(!scopes.isEmpty()){
740 if(scopes.contains(scopeNameValue)){
741 JSONObject el = new JSONObject();
742 el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
743 el.put("date", policy.getModifiedDate());
744 el.put("version", policy.getActiveVersion());
746 el.put("type", "file");
747 el.put("createdBy", getUserName(policy.getCreatedBy()));
748 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
755 private String getUserName(String loginId){
756 PolicyController controller = getPolicyControllerInstance();
757 UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
758 if(userInfo == null){
761 return userInfo.getUserName();
765 private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
767 boolean isActive = false;
768 List<String> policyActiveInPDP = new ArrayList<>();
769 Set<String> scopeOfPolicyActiveInPDP = new HashSet<>();
770 String userId = UserUtils.getUserSession(request).getOrgUserId();
771 String oldPath = params.getString("path");
772 String newPath = params.getString("newPath");
773 oldPath = oldPath.substring(oldPath.indexOf("/")+1);
774 newPath = newPath.substring(newPath.indexOf("/")+1);
775 if(oldPath.endsWith(".xml")){
776 JSONObject result = policyRename(oldPath, newPath, userId);
777 if(!(Boolean)(result.getJSONObject("result").get("success"))){
781 String scopeName = oldPath;
782 String newScopeName = newPath;
783 if(scopeName.contains("/")){
784 scopeName = scopeName.replace("/", File.separator);
785 newScopeName = newScopeName.replace("/", File.separator);
787 if(scopeName.contains("\\")){
788 scopeName = scopeName.replace("\\", "\\\\\\\\");
789 newScopeName = newScopeName.replace("\\", "\\\\\\\\");
791 PolicyController controller = getPolicyControllerInstance();
792 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
793 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
794 SimpleBindings pvParams = new SimpleBindings();
795 pvParams.put("scopeName", scopeName + "%");
796 List<Object> activePolicies = controller.getDataByQuery(query, pvParams);
797 List<Object> scopesList = controller.getDataByQuery(scopeNamequery, pvParams);
798 for(Object object : activePolicies){
799 PolicyVersion activeVersion = (PolicyVersion) object;
800 String policyOldPath = activeVersion.getPolicyName().replace(File.separator, "/") + "." + activeVersion.getActiveVersion() + ".xml";
801 String policyNewPath = policyOldPath.replace(oldPath, newPath);
802 JSONObject result = policyRename(policyOldPath, policyNewPath, userId);
803 if(!(Boolean)(result.getJSONObject("result").get("success"))){
805 policyActiveInPDP.add(policyOldPath);
806 String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf("/"));
807 scopeOfPolicyActiveInPDP.add(scope.replace("/", File.separator));
810 boolean rename = false;
811 if(activePolicies.size() != policyActiveInPDP.size()){
815 UserInfo userInfo = new UserInfo();
816 userInfo.setUserLoginId(userId);
817 if(policyActiveInPDP.size() == 0){
818 renameScope(scopesList, scopeName, newScopeName, controller);
820 renameScope(scopesList, scopeName, newScopeName, controller);
821 for(String scope : scopeOfPolicyActiveInPDP){
822 PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes();
823 editorScopeEntity.setScopeName(scope.replace("\\", "\\\\\\\\"));
824 editorScopeEntity.setUserCreatedBy(userInfo);
825 editorScopeEntity.setUserModifiedBy(userInfo);
826 controller.saveData(editorScopeEntity);
830 return error("The Following policies rename failed. Since they are active in PDP Groups" +policyActiveInPDP);
834 } catch (Exception e) {
835 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
836 return error(e.getMessage());
840 private void renameScope(List<Object> scopesList, String scopeName, String newScopeName, PolicyController controller){
841 for(Object object : scopesList){
842 PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object;
843 if(scopeName.contains("\\\\\\\\")){
844 scopeName = scopeName.replace("\\\\\\\\", File.separator);
845 newScopeName = newScopeName.replace("\\\\\\\\", File.separator);
847 String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName);
848 editorScopeEntity.setScopeName(scope);
849 controller.updateData(editorScopeEntity);
853 private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
855 PolicyEntity entity = null;
856 PolicyController controller = getPolicyControllerInstance();
858 String policyVersionName = newPath.replace(".xml", "");
859 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")).replace("/", File.separator);
861 String oldpolicyVersionName = oldPath.replace(".xml", "");
862 String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf(".")).replace("/", File.separator);
864 String newpolicyName = newPath.replace("/", ".");
865 String newPolicyCheck = newpolicyName;
866 if(newPolicyCheck.contains("Config_")){
867 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
868 }else if(newPolicyCheck.contains("Action_")){
869 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
870 }else if(newPolicyCheck.contains("Decision_")){
871 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
873 String[] newPolicySplit = newPolicyCheck.split(":");
875 String orignalPolicyName = oldPath.replace("/", ".");
876 String oldPolicyCheck = orignalPolicyName;
877 if(oldPolicyCheck.contains("Config_")){
878 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
879 }else if(oldPolicyCheck.contains("Action_")){
880 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
881 }else if(oldPolicyCheck.contains("Decision_")){
882 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
884 String[] oldPolicySplit = oldPolicyCheck.split(":");
886 //Check PolicyEntity table with newPolicy Name
887 String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_1";
888 SimpleBindings policyParams = new SimpleBindings();
889 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
890 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
891 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
892 if(!queryData.isEmpty()){
893 entity = (PolicyEntity) queryData.get(0);
894 return error("Policy rename failed. Since, the policy with same name already exists.");
897 //Query the Policy Entity with oldPolicy Name
898 String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf("."));
899 String oldpolicyEntityquery = "FROM PolicyEntity where policyName like :policyEntityCheck and scope = :oldPolicySplit_0";
900 SimpleBindings params = new SimpleBindings();
901 params.put("policyEntityCheck", policyEntityCheck + "%");
902 params.put("oldPolicySplit_0", oldPolicySplit[0]);
903 List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery, params);
904 if(!oldEntityData.isEmpty()){
905 String groupQuery = "FROM PolicyGroupEntity where (";
906 SimpleBindings geParams = new SimpleBindings();
907 for(int i=0; i<oldEntityData.size(); i++){
908 entity = (PolicyEntity) oldEntityData.get(i);
910 groupQuery = groupQuery + "policyid = :policyId";
911 geParams.put("policyId", entity.getPolicyId());
913 groupQuery = groupQuery + " or policyid = :policyId" + i;
914 geParams.put("policyId" + i, entity.getPolicyId());
917 groupQuery = groupQuery + ")";
918 List<Object> groupEntityData = controller.getDataByQuery(groupQuery, geParams);
919 if(groupEntityData.size() > 0){
920 return error("Policy rename failed. Since the policy or its version is active in PDP Groups.");
922 for(int i=0; i<oldEntityData.size(); i++){
923 entity = (PolicyEntity) oldEntityData.get(i);
924 checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0] , newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
927 return error("Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin.");
931 } catch (Exception e) {
932 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
933 return error(e.getMessage());
937 private JSONObject checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, String oldScope, String removeoldPolicyExtension,
938 String policyName, String newpolicyName, String oldpolicyName, String userId) throws ServletException{
940 ConfigurationDataEntity configEntity = entity.getConfigurationData();
941 ActionBodyEntity actionEntity = entity.getActionBodyEntity();
942 PolicyController controller = getPolicyControllerInstance();
944 String oldPolicyNameWithoutExtension = removeoldPolicyExtension;
945 String newPolicyNameWithoutExtension = removenewPolicyExtension;
946 if(removeoldPolicyExtension.endsWith(".xml")){
947 oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf("."));
948 newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf("."));
950 entity.setPolicyName(entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
951 entity.setPolicyData(entity.getPolicyData().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
952 entity.setScope(newScope);
953 entity.setModifiedBy(userId);
954 if(newpolicyName.contains("Config_")){
955 String oldConfigurationName = configEntity.getConfigurationName();
956 configEntity.setConfigurationName(configEntity.getConfigurationName().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
957 controller.updateData(configEntity);
958 String newConfigurationName = configEntity.getConfigurationName();
959 File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName);
961 File renamefile = new File(PolicyController.getConfigHome() + File.separator + newConfigurationName);
962 file.renameTo(renamefile);
964 }else if(newpolicyName.contains("Action_")){
965 String oldConfigurationName = actionEntity.getActionBodyName();
966 actionEntity.setActionBody(actionEntity.getActionBody().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
967 controller.updateData(actionEntity);
968 String newConfigurationName = actionEntity.getActionBodyName();
969 File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName);
971 File renamefile = new File(PolicyController.getActionHome() + File.separator + newConfigurationName);
972 file.renameTo(renamefile);
975 controller.updateData(entity);
977 PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldpolicyName);
978 versionEntity.setPolicyName(policyName);
979 versionEntity.setModifiedBy(userId);
980 controller.updateData(versionEntity);
981 String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator)+1);
982 String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
983 if(movePolicyCheck.equals(moveOldPolicyCheck)){
984 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move");
986 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename");
989 } catch (Exception e) {
990 LOGGER.error("Exception Occured"+e);
991 return error(e.getMessage());
995 private JSONObject cloneRecord(String newpolicyName, String oldScope, String removeoldPolicyExtension, String newScope, String removenewPolicyExtension, PolicyEntity entity, String userId) throws ServletException{
996 FileWriter fw = null;
997 String queryEntityName = null;
998 PolicyController controller = getPolicyControllerInstance();
999 PolicyEntity cloneEntity = new PolicyEntity();
1000 cloneEntity.setPolicyName(newpolicyName);
1001 removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
1002 removenewPolicyExtension = removenewPolicyExtension.replace(".xml", "");
1003 cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope+"."+removeoldPolicyExtension, newScope+"."+removenewPolicyExtension));
1004 cloneEntity.setScope(entity.getScope());
1005 String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
1006 String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
1007 if(newpolicyName.contains("Config_")){
1008 ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
1009 configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1010 queryEntityName = configurationDataEntity.getConfigurationName();
1011 configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody());
1012 configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType());
1013 configurationDataEntity.setDeleted(false);
1014 configurationDataEntity.setCreatedBy(userId);
1015 configurationDataEntity.setModifiedBy(userId);
1016 controller.saveData(configurationDataEntity);
1017 ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
1018 cloneEntity.setConfigurationData(configEntiy);
1019 String newConfigurationName = configEntiy.getConfigurationName();
1021 fw = new FileWriter(PolicyController.getConfigHome() + File.separator + newConfigurationName);
1022 BufferedWriter bw = new BufferedWriter(fw);
1023 bw.write(configEntiy.getConfigBody());
1025 } catch (IOException e) {
1026 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1028 }else if(newpolicyName.contains("Action_")){
1029 ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
1030 actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1031 queryEntityName = actionBodyEntity.getActionBodyName();
1032 actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody());
1033 actionBodyEntity.setDeleted(false);
1034 actionBodyEntity.setCreatedBy(userId);
1035 actionBodyEntity.setModifiedBy(userId);
1036 controller.saveData(actionBodyEntity);
1037 ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class, "actionBodyName", queryEntityName);
1038 cloneEntity.setActionBodyEntity(actionEntiy);
1039 String newConfigurationName = actionEntiy.getActionBodyName();
1041 fw = new FileWriter(PolicyController.getActionHome() + File.separator + newConfigurationName);
1042 BufferedWriter bw = new BufferedWriter(fw);
1043 bw.write(actionEntiy.getActionBody());
1045 } catch (IOException e) {
1046 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1052 } catch (IOException e) {
1053 LOGGER.error("Exception Occured While closing the File input stream"+e);
1056 cloneEntity.setDeleted(entity.isDeleted());
1057 cloneEntity.setCreatedBy(userId);
1058 cloneEntity.setModifiedBy(userId);
1059 controller.saveData(cloneEntity);
1065 private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
1067 String userId = UserUtils.getUserSession(request).getOrgUserId();
1068 String oldPath = params.getString("path");
1069 String newPath = params.getString("newPath");
1070 oldPath = oldPath.substring(oldPath.indexOf("/")+1);
1071 newPath = newPath.substring(newPath.indexOf("/")+1);
1073 String policyVersionName = newPath.replace(".xml", "");
1074 String version = policyVersionName.substring(policyVersionName.indexOf(".")+1);
1075 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")).replace("/", File.separator);
1077 String newpolicyName = newPath.replace("/", ".");
1079 String orignalPolicyName = oldPath.replace("/", ".");
1081 String newPolicyCheck = newpolicyName;
1082 if(newPolicyCheck.contains("Config_")){
1083 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
1084 }else if(newPolicyCheck.contains("Action_")){
1085 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
1086 }else if(newPolicyCheck.contains("Decision_")){
1087 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
1089 String[] newPolicySplit = newPolicyCheck.split(":");
1091 String oldPolicyCheck = orignalPolicyName;
1092 if(oldPolicyCheck.contains("Config_")){
1093 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
1094 }else if(oldPolicyCheck.contains("Action_")){
1095 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
1096 }else if(oldPolicyCheck.contains("Decision_")){
1097 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
1099 String[] oldPolicySplit = oldPolicyCheck.split(":");
1101 PolicyController controller = getPolicyControllerInstance();
1103 PolicyEntity entity = null;
1104 boolean success = false;
1106 //Check PolicyEntity table with newPolicy Name
1107 String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
1108 SimpleBindings policyParams = new SimpleBindings();
1109 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
1110 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
1111 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
1112 if(!queryData.isEmpty()){
1113 return error("Policy already exists with same name");
1116 //Query the Policy Entity with oldPolicy Name
1117 policyEntityquery = "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0";
1118 SimpleBindings peParams = new SimpleBindings();
1119 peParams.put("oldPolicySplit_1", oldPolicySplit[1]);
1120 peParams.put("oldPolicySplit_0", oldPolicySplit[0]);
1121 queryData = controller.getDataByQuery(policyEntityquery, peParams);
1122 if(!queryData.isEmpty()){
1123 entity = (PolicyEntity) queryData.get(0);
1126 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId);
1131 PolicyVersion entityItem = new PolicyVersion();
1132 entityItem.setActiveVersion(Integer.parseInt(version));
1133 entityItem.setHigherVersion(Integer.parseInt(version));
1134 entityItem.setPolicyName(policyName);
1135 entityItem.setCreatedBy(userId);
1136 entityItem.setModifiedBy(userId);
1137 controller.saveData(entityItem);
1140 LOGGER.debug("copy from: {} to: {}" + oldPath +newPath);
1143 } catch (Exception e) {
1144 LOGGER.error("copy", e);
1145 return error(e.getMessage());
1149 //Delete Policy or Scope Functionality
1150 private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
1151 PolicyController controller = getPolicyControllerInstance();
1152 PolicyRestController restController = new PolicyRestController();
1153 PolicyEntity policyEntity = null;
1154 String policyNamewithoutExtension;
1156 String userId = UserUtils.getUserSession(request).getOrgUserId();
1157 String deleteVersion = "";
1158 String path = params.getString("path");
1159 LOGGER.debug("delete {}" +path);
1160 if(params.has("deleteVersion")){
1161 deleteVersion = params.getString("deleteVersion");
1163 path = path.substring(path.indexOf("/")+1);
1164 String policyNamewithExtension = path.replace("/", File.separator);
1165 String policyVersionName = policyNamewithExtension.replace(".xml", "");
1167 SimpleBindings policyParams = new SimpleBindings();
1168 if(path.endsWith(".xml")){
1169 policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf("."));
1170 policyNamewithoutExtension = policyNamewithoutExtension.replace(File.separator, ".");
1171 String splitPolicyName = null;
1172 if(policyNamewithoutExtension.contains("Config_")){
1173 splitPolicyName = policyNamewithoutExtension.replace(".Config_", ":Config_");
1174 }else if(policyNamewithoutExtension.contains("Action_")){
1175 splitPolicyName = policyNamewithoutExtension.replace(".Action_", ":Action_");
1176 }else if(policyNamewithoutExtension.contains("Decision_")){
1177 splitPolicyName = policyNamewithoutExtension.replace(".Decision_", ":Decision_");
1179 String[] split = splitPolicyName.split(":");
1180 query = "FROM PolicyEntity where policyName like split_1 and scope = split_0";
1181 policyParams.put("split_1", split[1] + "%");
1182 policyParams.put("split_0", split[0]);
1184 policyNamewithoutExtension = path.replace(File.separator, ".");
1185 query = "FROM PolicyEntity where scope like :policyNamewithoutExtension";
1186 policyParams.put("policyNamewithoutExtension", policyNamewithoutExtension + "%");
1189 List<Object> policyEntityobjects = controller.getDataByQuery(query, policyParams);
1190 String activePolicyName = null;
1191 boolean pdpCheck = false;
1192 if(path.endsWith(".xml")){
1193 policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator);
1194 int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf(".")+1));
1195 if("ALL".equals(deleteVersion)){
1196 if(!policyEntityobjects.isEmpty()){
1197 for(Object object : policyEntityobjects){
1198 policyEntity = (PolicyEntity) object;
1199 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyId";
1200 SimpleBindings pgeParams = new SimpleBindings();
1201 pgeParams.put("policyId", policyEntity.getPolicyId());
1202 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, pgeParams);
1203 if(!groupobject.isEmpty()){
1205 activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName();
1207 //Delete the entity from Elastic Search Database
1208 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1209 restController.deleteElasticData(searchFileName);
1210 //Delete the entity from Policy Entity table
1211 controller.deleteData(policyEntity);
1212 if(policyNamewithoutExtension.contains("Config_")){
1213 controller.deleteData(policyEntity.getConfigurationData());
1214 }else if(policyNamewithoutExtension.contains("Action_")){
1215 controller.deleteData(policyEntity.getActionBodyEntity());
1220 //Policy Notification
1221 PolicyVersion versionEntity = new PolicyVersion();
1222 versionEntity.setPolicyName(policyNamewithoutExtension);
1223 versionEntity.setModifiedBy(userId);
1224 controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll");
1226 //Delete from policyVersion table
1227 String getActivePDPPolicyVersion = activePolicyName.replace(".xml", "");
1228 getActivePDPPolicyVersion = getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf(".")+1);
1229 String policyVersionQuery = "update PolicyVersion set active_version='"+getActivePDPPolicyVersion+"' , highest_version='"+getActivePDPPolicyVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1230 if(policyVersionQuery != null){
1231 controller.executeQuery(policyVersionQuery);
1233 return error("Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "+activePolicyName);
1235 //No Active Policy in PDP. So, deleting all entries from policyVersion table
1236 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1237 if(policyVersionQuery != null){
1238 controller.executeQuery(policyVersionQuery);
1241 }else if("CURRENT".equals(deleteVersion)){
1242 String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1);
1243 String currentVersionScope = policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator)).replace(File.separator, ".");
1244 query = "FROM PolicyEntity where policyName = :currentVersionPolicyName and scope = :currentVersionScope";
1246 SimpleBindings peParams = new SimpleBindings();
1247 peParams.put("currentVersionPolicyName", currentVersionPolicyName);
1248 peParams.put("currentVersionScope", currentVersionScope);
1250 List<Object> policyEntitys = controller.getDataByQuery(query, peParams);
1251 if(!policyEntitys.isEmpty()){
1252 policyEntity = (PolicyEntity) policyEntitys.get(0);
1254 if(policyEntity != null){
1255 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId and policyid > 0";
1256 SimpleBindings geParams = new SimpleBindings();
1257 geParams.put("policyEntityId", policyEntity.getPolicyId());
1258 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1259 if(groupobject.isEmpty()){
1260 //Delete the entity from Elastic Search Database
1261 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1262 restController.deleteElasticData(searchFileName);
1263 //Delete the entity from Policy Entity table
1264 controller.deleteData(policyEntity);
1265 if(policyNamewithoutExtension.contains("Config_")){
1266 controller.deleteData(policyEntity.getConfigurationData());
1267 }else if(policyNamewithoutExtension.contains("Action_")){
1268 controller.deleteData(policyEntity.getActionBodyEntity());
1272 int highestVersion = 0;
1273 if(!policyEntityobjects.isEmpty()){
1274 for(Object object : policyEntityobjects){
1275 policyEntity = (PolicyEntity) object;
1276 String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
1277 int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf(".")+1));
1278 if(policyEntityVersion > highestVersion && policyEntityVersion != version){
1279 highestVersion = policyEntityVersion;
1284 //Policy Notification
1285 PolicyVersion entity = new PolicyVersion();
1286 entity.setPolicyName(policyNamewithoutExtension);
1287 entity.setActiveVersion(highestVersion);
1288 entity.setModifiedBy(userId);
1289 controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne");
1291 String updatequery = "update PolicyVersion set active_version='"+highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"'";
1292 controller.executeQuery(updatequery);
1294 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1295 if(policyVersionQuery != null){
1296 controller.executeQuery(policyVersionQuery);
1300 return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'");
1305 List<String> activePoliciesInPDP = new ArrayList<String>();
1306 if(!policyEntityobjects.isEmpty()){
1307 for(Object object : policyEntityobjects){
1308 policyEntity = (PolicyEntity) object;
1309 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId";
1310 SimpleBindings geParams = new SimpleBindings();
1311 geParams.put("policyEntityId", policyEntity.getPolicyId());
1312 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1313 if(!groupobject.isEmpty()){
1315 activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName());
1317 //Delete the entity from Elastic Search Database
1318 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1319 restController.deleteElasticData(searchFileName);
1320 //Delete the entity from Policy Entity table
1321 controller.deleteData(policyEntity);
1322 policyNamewithoutExtension = policyEntity.getPolicyName();
1323 if(policyNamewithoutExtension.contains("Config_")){
1324 controller.deleteData(policyEntity.getConfigurationData());
1325 }else if(policyNamewithoutExtension.contains("Action_")){
1326 controller.deleteData(policyEntity.getActionBodyEntity());
1330 //Delete from policyVersion and policyEditor Scope table
1331 String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1332 controller.executeQuery(policyVersionQuery);
1334 //Policy Notification
1335 PolicyVersion entity = new PolicyVersion();
1336 entity.setPolicyName(path);
1337 entity.setModifiedBy(userId);
1338 controller.watchPolicyFunction(entity, path, "DeleteScope");
1340 //Add Active Policies List to PolicyVersionTable
1341 for(int i =0; i < activePoliciesInPDP.size(); i++){
1342 String activePDPPolicyName = activePoliciesInPDP.get(i).replace(".xml", "");
1343 int activePDPPolicyVersion = Integer.parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf(".")+1));
1344 activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf(".")).replace(".", File.separator);
1345 PolicyVersion insertactivePDPVersion = new PolicyVersion();
1346 insertactivePDPVersion.setPolicyName(activePDPPolicyName);
1347 insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion);
1348 insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion);
1349 insertactivePDPVersion.setCreatedBy(userId);
1350 insertactivePDPVersion.setModifiedBy(userId);
1351 controller.saveData(insertactivePDPVersion);
1354 return error("All the Policies has been deleted in Scope. Except the following list of Policies:"+activePoliciesInPDP);
1356 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1357 controller.executeQuery(policyScopeQuery);
1360 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1361 controller.executeQuery(policyScopeQuery);
1365 } catch (Exception e) {
1366 LOGGER.error("delete", e);
1367 return error(e.getMessage());
1372 private JSONObject editFile(JSONObject params) throws ServletException {
1375 PolicyController controller = getPolicyControllerInstance();
1376 String mode = params.getString("mode");
1377 String path = params.getString("path");
1378 LOGGER.debug("editFile path: {}"+ path);
1380 String domain = path.substring(1, path.lastIndexOf("/"));
1381 domain = domain.replace("/", ".");
1383 path = path.substring(1);
1384 path = path.replace("/", ".");
1385 String dbCheckName = path;
1386 if(dbCheckName.contains("Config_")){
1387 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
1388 }else if(dbCheckName.contains("Action_")){
1389 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
1390 }else if(dbCheckName.contains("Decision_")){
1391 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
1394 String[] split = dbCheckName.split(":");
1395 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
1396 SimpleBindings peParams = new SimpleBindings();
1397 peParams.put("split_1", split[1]);
1398 peParams.put("split_0", split[0]);
1399 List<Object> queryData = controller.getDataByQuery(query, peParams);
1400 PolicyEntity entity = (PolicyEntity) queryData.get(0);
1401 InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
1404 Object policy = XACMLPolicyScanner.readPolicy(stream);
1405 PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
1406 policyAdapter.setData(policy);
1408 if("viewPolicy".equalsIgnoreCase(mode)){
1409 policyAdapter.setReadOnly(true);
1410 policyAdapter.setEditPolicy(false);
1412 policyAdapter.setReadOnly(false);
1413 policyAdapter.setEditPolicy(true);
1415 policyAdapter.setDomain(domain);
1416 policyAdapter.setDomainDir(domain);
1417 policyAdapter.setPolicyData(policy);
1418 String policyName = path.replace(".xml", "");
1419 policyName = policyName.substring(0, policyName.lastIndexOf("."));
1420 policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf(".")+1));
1422 PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance();
1423 setpolicyAdapter.configure(policyAdapter,entity);
1425 policyAdapter.setParentPath(null);
1426 ObjectMapper mapper = new ObjectMapper();
1427 String json = mapper.writeValueAsString(policyAdapter);
1428 JsonNode jsonNode = mapper.readTree(json);
1430 return new JSONObject().put(RESULT, jsonNode);
1431 } catch (Exception e) {
1432 LOGGER.error("editFile", e);
1433 return error(e.getMessage());
1438 private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
1439 PolicyController controller = getPolicyControllerInstance();
1442 String userId = UserUtils.getUserSession(request).getOrgUserId();
1443 String path = params.getString("path");
1445 if(params.has("subScopename")){
1446 if(!params.getString("subScopename").equals("")){
1447 name = params.getString("path").replace("/", File.separator) + File.separator +params.getString("subScopename");
1450 name = params.getString("name");
1452 }catch(Exception e){
1453 name = params.getString("name");
1454 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e);
1456 String validateName;
1457 if(name.contains(File.separator)){
1458 validateName = name.substring(name.lastIndexOf(File.separator)+1);
1460 validateName = name;
1462 if(!name.isEmpty()){
1463 String validate = PolicyUtils.emptyPolicyValidator(validateName);
1464 if(!validate.contains("success")){
1465 return error(validate);
1468 LOGGER.debug("addFolder path: {} name: {}" + path +name);
1469 if(!name.equals("")){
1470 if(name.startsWith(File.separator)){
1471 name = name.substring(1);
1473 PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, "scopeName", name);
1475 UserInfo userInfo = new UserInfo();
1476 userInfo.setUserLoginId(userId);
1477 PolicyEditorScopes newScope = new PolicyEditorScopes();
1478 newScope.setScopeName(name);
1479 newScope.setUserCreatedBy(userInfo);
1480 newScope.setUserModifiedBy(userInfo);
1481 controller.saveData(newScope);
1483 return error("Scope Already Exists");
1487 } catch (Exception e) {
1488 LOGGER.error("addFolder", e);
1489 return error(e.getMessage());
1493 //Return Error Object
1494 private JSONObject error(String msg) throws ServletException {
1496 JSONObject result = new JSONObject();
1497 result.put("success", false);
1498 result.put("error", msg);
1499 return new JSONObject().put(RESULT, result);
1500 } catch (JSONException e) {
1501 throw new ServletException(e);
1505 //Return Success Object
1506 private JSONObject success() throws ServletException {
1508 JSONObject result = new JSONObject();
1509 result.put("success", true);
1510 result.put("error", (Object) null);
1511 return new JSONObject().put(RESULT, result);
1512 } catch (JSONException e) {
1513 throw new ServletException(e);
1517 private PolicyController getPolicyControllerInstance(){
1518 return policyController != null ? getPolicyController() : new PolicyController();
1521 public String getTestUserId() {
1525 public static void setTestUserId(String testUserId) {
1526 PolicyManagerServlet.testUserId = testUserId;