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() && scopes.contains(scopeNameValue)){
740 JSONObject el = new JSONObject();
741 el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
742 el.put("date", policy.getModifiedDate());
743 el.put("version", policy.getActiveVersion());
745 el.put("type", "file");
746 el.put("createdBy", getUserName(policy.getCreatedBy()));
747 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
753 private String getUserName(String loginId){
754 PolicyController controller = getPolicyControllerInstance();
755 UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
756 if(userInfo == null){
759 return userInfo.getUserName();
763 private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
765 boolean isActive = false;
766 List<String> policyActiveInPDP = new ArrayList<>();
767 Set<String> scopeOfPolicyActiveInPDP = new HashSet<>();
768 String userId = UserUtils.getUserSession(request).getOrgUserId();
769 String oldPath = params.getString("path");
770 String newPath = params.getString("newPath");
771 oldPath = oldPath.substring(oldPath.indexOf("/")+1);
772 newPath = newPath.substring(newPath.indexOf("/")+1);
773 if(oldPath.endsWith(".xml")){
774 JSONObject result = policyRename(oldPath, newPath, userId);
775 if(!(Boolean)(result.getJSONObject("result").get("success"))){
779 String scopeName = oldPath;
780 String newScopeName = newPath;
781 if(scopeName.contains("/")){
782 scopeName = scopeName.replace("/", File.separator);
783 newScopeName = newScopeName.replace("/", File.separator);
785 if(scopeName.contains("\\")){
786 scopeName = scopeName.replace("\\", "\\\\\\\\");
787 newScopeName = newScopeName.replace("\\", "\\\\\\\\");
789 PolicyController controller = getPolicyControllerInstance();
790 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
791 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
792 SimpleBindings pvParams = new SimpleBindings();
793 pvParams.put("scopeName", scopeName + "%");
794 List<Object> activePolicies = controller.getDataByQuery(query, pvParams);
795 List<Object> scopesList = controller.getDataByQuery(scopeNamequery, pvParams);
796 for(Object object : activePolicies){
797 PolicyVersion activeVersion = (PolicyVersion) object;
798 String policyOldPath = activeVersion.getPolicyName().replace(File.separator, "/") + "." + activeVersion.getActiveVersion() + ".xml";
799 String policyNewPath = policyOldPath.replace(oldPath, newPath);
800 JSONObject result = policyRename(policyOldPath, policyNewPath, userId);
801 if(!(Boolean)(result.getJSONObject("result").get("success"))){
803 policyActiveInPDP.add(policyOldPath);
804 String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf("/"));
805 scopeOfPolicyActiveInPDP.add(scope.replace("/", File.separator));
808 boolean rename = false;
809 if(activePolicies.size() != policyActiveInPDP.size()){
813 UserInfo userInfo = new UserInfo();
814 userInfo.setUserLoginId(userId);
815 if(policyActiveInPDP.size() == 0){
816 renameScope(scopesList, scopeName, newScopeName, controller);
818 renameScope(scopesList, scopeName, newScopeName, controller);
819 for(String scope : scopeOfPolicyActiveInPDP){
820 PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes();
821 editorScopeEntity.setScopeName(scope.replace("\\", "\\\\\\\\"));
822 editorScopeEntity.setUserCreatedBy(userInfo);
823 editorScopeEntity.setUserModifiedBy(userInfo);
824 controller.saveData(editorScopeEntity);
828 return error("The Following policies rename failed. Since they are active in PDP Groups" +policyActiveInPDP);
832 } catch (Exception e) {
833 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
834 return error(e.getMessage());
838 private void renameScope(List<Object> scopesList, String scopeName, String newScopeName, PolicyController controller){
839 for(Object object : scopesList){
840 PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object;
841 if(scopeName.contains("\\\\\\\\")){
842 scopeName = scopeName.replace("\\\\\\\\", File.separator);
843 newScopeName = newScopeName.replace("\\\\\\\\", File.separator);
845 String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName);
846 editorScopeEntity.setScopeName(scope);
847 controller.updateData(editorScopeEntity);
851 private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
853 PolicyEntity entity = null;
854 PolicyController controller = getPolicyControllerInstance();
856 String policyVersionName = newPath.replace(".xml", "");
857 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")).replace("/", File.separator);
859 String oldpolicyVersionName = oldPath.replace(".xml", "");
860 String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf(".")).replace("/", File.separator);
862 String newpolicyName = newPath.replace("/", ".");
863 String newPolicyCheck = newpolicyName;
864 if(newPolicyCheck.contains("Config_")){
865 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
866 }else if(newPolicyCheck.contains("Action_")){
867 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
868 }else if(newPolicyCheck.contains("Decision_")){
869 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
871 String[] newPolicySplit = newPolicyCheck.split(":");
873 String orignalPolicyName = oldPath.replace("/", ".");
874 String oldPolicyCheck = orignalPolicyName;
875 if(oldPolicyCheck.contains("Config_")){
876 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
877 }else if(oldPolicyCheck.contains("Action_")){
878 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
879 }else if(oldPolicyCheck.contains("Decision_")){
880 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
882 String[] oldPolicySplit = oldPolicyCheck.split(":");
884 //Check PolicyEntity table with newPolicy Name
885 String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_1";
886 SimpleBindings policyParams = new SimpleBindings();
887 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
888 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
889 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
890 if(!queryData.isEmpty()){
891 entity = (PolicyEntity) queryData.get(0);
892 return error("Policy rename failed. Since, the policy with same name already exists.");
895 //Query the Policy Entity with oldPolicy Name
896 String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf("."));
897 String oldpolicyEntityquery = "FROM PolicyEntity where policyName like :policyEntityCheck and scope = :oldPolicySplit_0";
898 SimpleBindings params = new SimpleBindings();
899 params.put("policyEntityCheck", policyEntityCheck + "%");
900 params.put("oldPolicySplit_0", oldPolicySplit[0]);
901 List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery, params);
902 if(!oldEntityData.isEmpty()){
903 String groupQuery = "FROM PolicyGroupEntity where (";
904 SimpleBindings geParams = new SimpleBindings();
905 for(int i=0; i<oldEntityData.size(); i++){
906 entity = (PolicyEntity) oldEntityData.get(i);
908 groupQuery = groupQuery + "policyid = :policyId";
909 geParams.put("policyId", entity.getPolicyId());
911 groupQuery = groupQuery + " or policyid = :policyId" + i;
912 geParams.put("policyId" + i, entity.getPolicyId());
915 groupQuery = groupQuery + ")";
916 List<Object> groupEntityData = controller.getDataByQuery(groupQuery, geParams);
917 if(groupEntityData.size() > 0){
918 return error("Policy rename failed. Since the policy or its version is active in PDP Groups.");
920 for(int i=0; i<oldEntityData.size(); i++){
921 entity = (PolicyEntity) oldEntityData.get(i);
922 checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0] , newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
925 return error("Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin.");
929 } catch (Exception e) {
930 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
931 return error(e.getMessage());
935 private JSONObject checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, String oldScope, String removeoldPolicyExtension,
936 String policyName, String newpolicyName, String oldpolicyName, String userId) throws ServletException{
938 ConfigurationDataEntity configEntity = entity.getConfigurationData();
939 ActionBodyEntity actionEntity = entity.getActionBodyEntity();
940 PolicyController controller = getPolicyControllerInstance();
942 String oldPolicyNameWithoutExtension = removeoldPolicyExtension;
943 String newPolicyNameWithoutExtension = removenewPolicyExtension;
944 if(removeoldPolicyExtension.endsWith(".xml")){
945 oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf("."));
946 newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf("."));
948 entity.setPolicyName(entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
949 entity.setPolicyData(entity.getPolicyData().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
950 entity.setScope(newScope);
951 entity.setModifiedBy(userId);
952 if(newpolicyName.contains("Config_")){
953 String oldConfigurationName = configEntity.getConfigurationName();
954 configEntity.setConfigurationName(configEntity.getConfigurationName().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
955 controller.updateData(configEntity);
956 String newConfigurationName = configEntity.getConfigurationName();
957 File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName);
959 File renamefile = new File(PolicyController.getConfigHome() + File.separator + newConfigurationName);
960 file.renameTo(renamefile);
962 }else if(newpolicyName.contains("Action_")){
963 String oldConfigurationName = actionEntity.getActionBodyName();
964 actionEntity.setActionBody(actionEntity.getActionBody().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
965 controller.updateData(actionEntity);
966 String newConfigurationName = actionEntity.getActionBodyName();
967 File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName);
969 File renamefile = new File(PolicyController.getActionHome() + File.separator + newConfigurationName);
970 file.renameTo(renamefile);
973 controller.updateData(entity);
975 PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldpolicyName);
976 versionEntity.setPolicyName(policyName);
977 versionEntity.setModifiedBy(userId);
978 controller.updateData(versionEntity);
979 String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator)+1);
980 String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
981 if(movePolicyCheck.equals(moveOldPolicyCheck)){
982 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move");
984 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename");
987 } catch (Exception e) {
988 LOGGER.error("Exception Occured"+e);
989 return error(e.getMessage());
993 private JSONObject cloneRecord(String newpolicyName, String oldScope, String removeoldPolicyExtension, String newScope, String removenewPolicyExtension, PolicyEntity entity, String userId) throws ServletException{
994 FileWriter fw = null;
995 String queryEntityName = null;
996 PolicyController controller = getPolicyControllerInstance();
997 PolicyEntity cloneEntity = new PolicyEntity();
998 cloneEntity.setPolicyName(newpolicyName);
999 removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
1000 removenewPolicyExtension = removenewPolicyExtension.replace(".xml", "");
1001 cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope+"."+removeoldPolicyExtension, newScope+"."+removenewPolicyExtension));
1002 cloneEntity.setScope(entity.getScope());
1003 String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
1004 String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
1005 if(newpolicyName.contains("Config_")){
1006 ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
1007 configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1008 queryEntityName = configurationDataEntity.getConfigurationName();
1009 configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody());
1010 configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType());
1011 configurationDataEntity.setDeleted(false);
1012 configurationDataEntity.setCreatedBy(userId);
1013 configurationDataEntity.setModifiedBy(userId);
1014 controller.saveData(configurationDataEntity);
1015 ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
1016 cloneEntity.setConfigurationData(configEntiy);
1017 String newConfigurationName = configEntiy.getConfigurationName();
1019 fw = new FileWriter(PolicyController.getConfigHome() + File.separator + newConfigurationName);
1020 BufferedWriter bw = new BufferedWriter(fw);
1021 bw.write(configEntiy.getConfigBody());
1023 } catch (IOException e) {
1024 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1026 }else if(newpolicyName.contains("Action_")){
1027 ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
1028 actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1029 queryEntityName = actionBodyEntity.getActionBodyName();
1030 actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody());
1031 actionBodyEntity.setDeleted(false);
1032 actionBodyEntity.setCreatedBy(userId);
1033 actionBodyEntity.setModifiedBy(userId);
1034 controller.saveData(actionBodyEntity);
1035 ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class, "actionBodyName", queryEntityName);
1036 cloneEntity.setActionBodyEntity(actionEntiy);
1037 String newConfigurationName = actionEntiy.getActionBodyName();
1039 fw = new FileWriter(PolicyController.getActionHome() + File.separator + newConfigurationName);
1040 BufferedWriter bw = new BufferedWriter(fw);
1041 bw.write(actionEntiy.getActionBody());
1043 } catch (IOException e) {
1044 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1050 } catch (IOException e) {
1051 LOGGER.error("Exception Occured While closing the File input stream"+e);
1054 cloneEntity.setDeleted(entity.isDeleted());
1055 cloneEntity.setCreatedBy(userId);
1056 cloneEntity.setModifiedBy(userId);
1057 controller.saveData(cloneEntity);
1063 private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
1065 String userId = UserUtils.getUserSession(request).getOrgUserId();
1066 String oldPath = params.getString("path");
1067 String newPath = params.getString("newPath");
1068 oldPath = oldPath.substring(oldPath.indexOf("/")+1);
1069 newPath = newPath.substring(newPath.indexOf("/")+1);
1071 String policyVersionName = newPath.replace(".xml", "");
1072 String version = policyVersionName.substring(policyVersionName.indexOf(".")+1);
1073 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")).replace("/", File.separator);
1075 String newpolicyName = newPath.replace("/", ".");
1077 String orignalPolicyName = oldPath.replace("/", ".");
1079 String newPolicyCheck = newpolicyName;
1080 if(newPolicyCheck.contains("Config_")){
1081 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
1082 }else if(newPolicyCheck.contains("Action_")){
1083 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
1084 }else if(newPolicyCheck.contains("Decision_")){
1085 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
1087 String[] newPolicySplit = newPolicyCheck.split(":");
1089 String oldPolicyCheck = orignalPolicyName;
1090 if(oldPolicyCheck.contains("Config_")){
1091 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
1092 }else if(oldPolicyCheck.contains("Action_")){
1093 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
1094 }else if(oldPolicyCheck.contains("Decision_")){
1095 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
1097 String[] oldPolicySplit = oldPolicyCheck.split(":");
1099 PolicyController controller = getPolicyControllerInstance();
1101 PolicyEntity entity = null;
1102 boolean success = false;
1104 //Check PolicyEntity table with newPolicy Name
1105 String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
1106 SimpleBindings policyParams = new SimpleBindings();
1107 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
1108 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
1109 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
1110 if(!queryData.isEmpty()){
1111 return error("Policy already exists with same name");
1114 //Query the Policy Entity with oldPolicy Name
1115 policyEntityquery = "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0";
1116 SimpleBindings peParams = new SimpleBindings();
1117 peParams.put("oldPolicySplit_1", oldPolicySplit[1]);
1118 peParams.put("oldPolicySplit_0", oldPolicySplit[0]);
1119 queryData = controller.getDataByQuery(policyEntityquery, peParams);
1120 if(!queryData.isEmpty()){
1121 entity = (PolicyEntity) queryData.get(0);
1124 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId);
1129 PolicyVersion entityItem = new PolicyVersion();
1130 entityItem.setActiveVersion(Integer.parseInt(version));
1131 entityItem.setHigherVersion(Integer.parseInt(version));
1132 entityItem.setPolicyName(policyName);
1133 entityItem.setCreatedBy(userId);
1134 entityItem.setModifiedBy(userId);
1135 controller.saveData(entityItem);
1138 LOGGER.debug("copy from: {} to: {}" + oldPath +newPath);
1141 } catch (Exception e) {
1142 LOGGER.error("copy", e);
1143 return error(e.getMessage());
1147 //Delete Policy or Scope Functionality
1148 private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
1149 PolicyController controller = getPolicyControllerInstance();
1150 PolicyRestController restController = new PolicyRestController();
1151 PolicyEntity policyEntity = null;
1152 String policyNamewithoutExtension;
1154 String userId = UserUtils.getUserSession(request).getOrgUserId();
1155 String deleteVersion = "";
1156 String path = params.getString("path");
1157 LOGGER.debug("delete {}" +path);
1158 if(params.has("deleteVersion")){
1159 deleteVersion = params.getString("deleteVersion");
1161 path = path.substring(path.indexOf("/")+1);
1162 String policyNamewithExtension = path.replace("/", File.separator);
1163 String policyVersionName = policyNamewithExtension.replace(".xml", "");
1165 SimpleBindings policyParams = new SimpleBindings();
1166 if(path.endsWith(".xml")){
1167 policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf("."));
1168 policyNamewithoutExtension = policyNamewithoutExtension.replace(File.separator, ".");
1169 String splitPolicyName = null;
1170 if(policyNamewithoutExtension.contains("Config_")){
1171 splitPolicyName = policyNamewithoutExtension.replace(".Config_", ":Config_");
1172 }else if(policyNamewithoutExtension.contains("Action_")){
1173 splitPolicyName = policyNamewithoutExtension.replace(".Action_", ":Action_");
1174 }else if(policyNamewithoutExtension.contains("Decision_")){
1175 splitPolicyName = policyNamewithoutExtension.replace(".Decision_", ":Decision_");
1177 String[] split = splitPolicyName.split(":");
1178 query = "FROM PolicyEntity where policyName like split_1 and scope = split_0";
1179 policyParams.put("split_1", split[1] + "%");
1180 policyParams.put("split_0", split[0]);
1182 policyNamewithoutExtension = path.replace(File.separator, ".");
1183 query = "FROM PolicyEntity where scope like :policyNamewithoutExtension";
1184 policyParams.put("policyNamewithoutExtension", policyNamewithoutExtension + "%");
1187 List<Object> policyEntityobjects = controller.getDataByQuery(query, policyParams);
1188 String activePolicyName = null;
1189 boolean pdpCheck = false;
1190 if(path.endsWith(".xml")){
1191 policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator);
1192 int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf(".")+1));
1193 if("ALL".equals(deleteVersion)){
1194 if(!policyEntityobjects.isEmpty()){
1195 for(Object object : policyEntityobjects){
1196 policyEntity = (PolicyEntity) object;
1197 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyId";
1198 SimpleBindings pgeParams = new SimpleBindings();
1199 pgeParams.put("policyId", policyEntity.getPolicyId());
1200 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, pgeParams);
1201 if(!groupobject.isEmpty()){
1203 activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName();
1205 //Delete the entity from Elastic Search Database
1206 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1207 restController.deleteElasticData(searchFileName);
1208 //Delete the entity from Policy Entity table
1209 controller.deleteData(policyEntity);
1210 if(policyNamewithoutExtension.contains("Config_")){
1211 controller.deleteData(policyEntity.getConfigurationData());
1212 }else if(policyNamewithoutExtension.contains("Action_")){
1213 controller.deleteData(policyEntity.getActionBodyEntity());
1218 //Policy Notification
1219 PolicyVersion versionEntity = new PolicyVersion();
1220 versionEntity.setPolicyName(policyNamewithoutExtension);
1221 versionEntity.setModifiedBy(userId);
1222 controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll");
1224 //Delete from policyVersion table
1225 String getActivePDPPolicyVersion = activePolicyName.replace(".xml", "");
1226 getActivePDPPolicyVersion = getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf(".")+1);
1227 String policyVersionQuery = "update PolicyVersion set active_version='"+getActivePDPPolicyVersion+"' , highest_version='"+getActivePDPPolicyVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1228 if(policyVersionQuery != null){
1229 controller.executeQuery(policyVersionQuery);
1231 return error("Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "+activePolicyName);
1233 //No Active Policy in PDP. So, deleting all entries from policyVersion table
1234 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1235 if(policyVersionQuery != null){
1236 controller.executeQuery(policyVersionQuery);
1239 }else if("CURRENT".equals(deleteVersion)){
1240 String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1);
1241 String currentVersionScope = policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator)).replace(File.separator, ".");
1242 query = "FROM PolicyEntity where policyName = :currentVersionPolicyName and scope = :currentVersionScope";
1244 SimpleBindings peParams = new SimpleBindings();
1245 peParams.put("currentVersionPolicyName", currentVersionPolicyName);
1246 peParams.put("currentVersionScope", currentVersionScope);
1248 List<Object> policyEntitys = controller.getDataByQuery(query, peParams);
1249 if(!policyEntitys.isEmpty()){
1250 policyEntity = (PolicyEntity) policyEntitys.get(0);
1252 if(policyEntity != null){
1253 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId and policyid > 0";
1254 SimpleBindings geParams = new SimpleBindings();
1255 geParams.put("policyEntityId", policyEntity.getPolicyId());
1256 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1257 if(groupobject.isEmpty()){
1258 //Delete the entity from Elastic Search Database
1259 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1260 restController.deleteElasticData(searchFileName);
1261 //Delete the entity from Policy Entity table
1262 controller.deleteData(policyEntity);
1263 if(policyNamewithoutExtension.contains("Config_")){
1264 controller.deleteData(policyEntity.getConfigurationData());
1265 }else if(policyNamewithoutExtension.contains("Action_")){
1266 controller.deleteData(policyEntity.getActionBodyEntity());
1270 int highestVersion = 0;
1271 if(!policyEntityobjects.isEmpty()){
1272 for(Object object : policyEntityobjects){
1273 policyEntity = (PolicyEntity) object;
1274 String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
1275 int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf(".")+1));
1276 if(policyEntityVersion > highestVersion && policyEntityVersion != version){
1277 highestVersion = policyEntityVersion;
1282 //Policy Notification
1283 PolicyVersion entity = new PolicyVersion();
1284 entity.setPolicyName(policyNamewithoutExtension);
1285 entity.setActiveVersion(highestVersion);
1286 entity.setModifiedBy(userId);
1287 controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne");
1289 String updatequery = "update PolicyVersion set active_version='"+highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"'";
1290 controller.executeQuery(updatequery);
1292 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1293 if(policyVersionQuery != null){
1294 controller.executeQuery(policyVersionQuery);
1298 return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'");
1303 List<String> activePoliciesInPDP = new ArrayList<String>();
1304 if(!policyEntityobjects.isEmpty()){
1305 for(Object object : policyEntityobjects){
1306 policyEntity = (PolicyEntity) object;
1307 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId";
1308 SimpleBindings geParams = new SimpleBindings();
1309 geParams.put("policyEntityId", policyEntity.getPolicyId());
1310 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1311 if(!groupobject.isEmpty()){
1313 activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName());
1315 //Delete the entity from Elastic Search Database
1316 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1317 restController.deleteElasticData(searchFileName);
1318 //Delete the entity from Policy Entity table
1319 controller.deleteData(policyEntity);
1320 policyNamewithoutExtension = policyEntity.getPolicyName();
1321 if(policyNamewithoutExtension.contains("Config_")){
1322 controller.deleteData(policyEntity.getConfigurationData());
1323 }else if(policyNamewithoutExtension.contains("Action_")){
1324 controller.deleteData(policyEntity.getActionBodyEntity());
1328 //Delete from policyVersion and policyEditor Scope table
1329 String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1330 controller.executeQuery(policyVersionQuery);
1332 //Policy Notification
1333 PolicyVersion entity = new PolicyVersion();
1334 entity.setPolicyName(path);
1335 entity.setModifiedBy(userId);
1336 controller.watchPolicyFunction(entity, path, "DeleteScope");
1338 //Add Active Policies List to PolicyVersionTable
1339 for(int i =0; i < activePoliciesInPDP.size(); i++){
1340 String activePDPPolicyName = activePoliciesInPDP.get(i).replace(".xml", "");
1341 int activePDPPolicyVersion = Integer.parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf(".")+1));
1342 activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf(".")).replace(".", File.separator);
1343 PolicyVersion insertactivePDPVersion = new PolicyVersion();
1344 insertactivePDPVersion.setPolicyName(activePDPPolicyName);
1345 insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion);
1346 insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion);
1347 insertactivePDPVersion.setCreatedBy(userId);
1348 insertactivePDPVersion.setModifiedBy(userId);
1349 controller.saveData(insertactivePDPVersion);
1352 return error("All the Policies has been deleted in Scope. Except the following list of Policies:"+activePoliciesInPDP);
1354 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1355 controller.executeQuery(policyScopeQuery);
1358 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1359 controller.executeQuery(policyScopeQuery);
1363 } catch (Exception e) {
1364 LOGGER.error("delete", e);
1365 return error(e.getMessage());
1370 private JSONObject editFile(JSONObject params) throws ServletException {
1373 PolicyController controller = getPolicyControllerInstance();
1374 String mode = params.getString("mode");
1375 String path = params.getString("path");
1376 LOGGER.debug("editFile path: {}"+ path);
1378 String domain = path.substring(1, path.lastIndexOf("/"));
1379 domain = domain.replace("/", ".");
1381 path = path.substring(1);
1382 path = path.replace("/", ".");
1383 String dbCheckName = path;
1384 if(dbCheckName.contains("Config_")){
1385 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
1386 }else if(dbCheckName.contains("Action_")){
1387 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
1388 }else if(dbCheckName.contains("Decision_")){
1389 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
1392 String[] split = dbCheckName.split(":");
1393 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
1394 SimpleBindings peParams = new SimpleBindings();
1395 peParams.put("split_1", split[1]);
1396 peParams.put("split_0", split[0]);
1397 List<Object> queryData = controller.getDataByQuery(query, peParams);
1398 PolicyEntity entity = (PolicyEntity) queryData.get(0);
1399 InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
1402 Object policy = XACMLPolicyScanner.readPolicy(stream);
1403 PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
1404 policyAdapter.setData(policy);
1406 if("viewPolicy".equalsIgnoreCase(mode)){
1407 policyAdapter.setReadOnly(true);
1408 policyAdapter.setEditPolicy(false);
1410 policyAdapter.setReadOnly(false);
1411 policyAdapter.setEditPolicy(true);
1413 policyAdapter.setDomain(domain);
1414 policyAdapter.setDomainDir(domain);
1415 policyAdapter.setPolicyData(policy);
1416 String policyName = path.replace(".xml", "");
1417 policyName = policyName.substring(0, policyName.lastIndexOf("."));
1418 policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf(".")+1));
1420 PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance();
1421 setpolicyAdapter.configure(policyAdapter,entity);
1423 policyAdapter.setParentPath(null);
1424 ObjectMapper mapper = new ObjectMapper();
1425 String json = mapper.writeValueAsString(policyAdapter);
1426 JsonNode jsonNode = mapper.readTree(json);
1428 return new JSONObject().put(RESULT, jsonNode);
1429 } catch (Exception e) {
1430 LOGGER.error("editFile", e);
1431 return error(e.getMessage());
1436 private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
1437 PolicyController controller = getPolicyControllerInstance();
1440 String userId = UserUtils.getUserSession(request).getOrgUserId();
1441 String path = params.getString("path");
1443 if(params.has("subScopename")){
1444 if(!params.getString("subScopename").equals("")){
1445 name = params.getString("path").replace("/", File.separator) + File.separator +params.getString("subScopename");
1448 name = params.getString("name");
1450 }catch(Exception e){
1451 name = params.getString("name");
1452 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e);
1454 String validateName;
1455 if(name.contains(File.separator)){
1456 validateName = name.substring(name.lastIndexOf(File.separator)+1);
1458 validateName = name;
1460 if(!name.isEmpty()){
1461 String validate = PolicyUtils.emptyPolicyValidator(validateName);
1462 if(!validate.contains("success")){
1463 return error(validate);
1466 LOGGER.debug("addFolder path: {} name: {}" + path +name);
1467 if(!name.equals("")){
1468 if(name.startsWith(File.separator)){
1469 name = name.substring(1);
1471 PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, "scopeName", name);
1473 UserInfo userInfo = new UserInfo();
1474 userInfo.setUserLoginId(userId);
1475 PolicyEditorScopes newScope = new PolicyEditorScopes();
1476 newScope.setScopeName(name);
1477 newScope.setUserCreatedBy(userInfo);
1478 newScope.setUserModifiedBy(userInfo);
1479 controller.saveData(newScope);
1481 return error("Scope Already Exists");
1485 } catch (Exception e) {
1486 LOGGER.error("addFolder", e);
1487 return error(e.getMessage());
1491 //Return Error Object
1492 private JSONObject error(String msg) throws ServletException {
1494 JSONObject result = new JSONObject();
1495 result.put("success", false);
1496 result.put("error", msg);
1497 return new JSONObject().put(RESULT, result);
1498 } catch (JSONException e) {
1499 throw new ServletException(e);
1503 //Return Success Object
1504 private JSONObject success() throws ServletException {
1506 JSONObject result = new JSONObject();
1507 result.put("success", true);
1508 result.put("error", (Object) null);
1509 return new JSONObject().put(RESULT, result);
1510 } catch (JSONException e) {
1511 throw new ServletException(e);
1515 private PolicyController getPolicyControllerInstance(){
1516 return policyController != null ? getPolicyController() : new PolicyController();
1519 public String getTestUserId() {
1523 public static void setTestUserId(String testUserId) {
1524 PolicyManagerServlet.testUserId = testUserId;