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.servlet.ServletConfig;
49 import javax.servlet.ServletException;
50 import javax.servlet.annotation.WebInitParam;
51 import javax.servlet.annotation.WebServlet;
52 import javax.servlet.http.HttpServlet;
53 import javax.servlet.http.HttpServletRequest;
54 import javax.servlet.http.HttpServletResponse;
56 import org.apache.commons.compress.utils.IOUtils;
57 import org.apache.commons.fileupload.FileItem;
58 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
59 import org.apache.commons.fileupload.servlet.ServletFileUpload;
60 import org.apache.http.HttpStatus;
61 import org.json.JSONArray;
62 import org.json.JSONException;
63 import org.json.JSONObject;
64 import org.onap.policy.common.logging.flexlogger.FlexLogger;
65 import org.onap.policy.common.logging.flexlogger.Logger;
66 import org.onap.policy.components.HumanPolicyComponent;
67 import org.onap.policy.controller.PolicyController;
68 import org.onap.policy.controller.PolicyExportAndImportController;
69 import org.onap.policy.rest.XACMLRest;
70 import org.onap.policy.rest.XACMLRestProperties;
71 import org.onap.policy.rest.adapter.PolicyRestAdapter;
72 import org.onap.policy.rest.jpa.ActionBodyEntity;
73 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
74 import org.onap.policy.rest.jpa.PolicyEditorScopes;
75 import org.onap.policy.rest.jpa.PolicyEntity;
76 import org.onap.policy.rest.jpa.PolicyVersion;
77 import org.onap.policy.rest.jpa.UserInfo;
78 import org.onap.policy.utils.PolicyUtils;
79 import org.onap.policy.xacml.api.XACMLErrorConstants;
80 import org.onap.policy.xacml.util.XACMLPolicyScanner;
81 import org.openecomp.policy.model.Roles;
82 import org.openecomp.portalsdk.core.web.support.UserUtils;
84 import com.att.research.xacml.util.XACMLProperties;
85 import com.fasterxml.jackson.databind.JsonNode;
86 import com.fasterxml.jackson.databind.ObjectMapper;
89 @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.") })
90 public class PolicyManagerServlet extends HttpServlet {
91 private static final Logger LOGGER = FlexLogger.getLogger(PolicyManagerServlet.class);
92 private static final long serialVersionUID = -8453502699403909016L;
95 LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT, SEARCHLIST
98 private static PolicyController policyController;
99 public synchronized PolicyController getPolicyController() {
100 return policyController;
103 public synchronized static void setPolicyController(PolicyController policyController) {
104 PolicyManagerServlet.policyController = policyController;
107 private static String CONTENTTYPE = "application/json";
108 private static String SUPERADMIN = "super-admin";
109 private static String SUPEREDITOR = "super-editor";
110 private static String SUPERGUEST = "super-guest";
111 private static String ADMIN = "admin";
112 private static String EDITOR = "editor";
113 private static String GUEST = "guest";
114 private static String RESULT = "result";
116 private static Path closedLoopJsonLocation;
117 private static JsonArray policyNames;
118 private static String testUserId = null;
120 public static JsonArray getPolicyNames() {
124 public static void setPolicyNames(JsonArray policyNames) {
125 PolicyManagerServlet.policyNames = policyNames;
128 private static List<String> serviceTypeNamesList = new ArrayList<>();
130 public static List<String> getServiceTypeNamesList() {
131 return serviceTypeNamesList;
135 public void init(ServletConfig servletConfig) throws ServletException {
136 super.init(servletConfig);
138 // Common initialization
140 XACMLRest.xacmlInit(servletConfig);
142 //Initialize ClosedLoop JSON
144 PolicyManagerServlet.initializeJSONLoad();
147 protected static void initializeJSONLoad() {
148 closedLoopJsonLocation = Paths.get(XACMLProperties
149 .getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP));
150 FileInputStream inputStream = null;
151 JsonReader jsonReader = null;
152 String location = closedLoopJsonLocation.toString();
154 inputStream = new FileInputStream(location);
155 if (location.endsWith("json")) {
156 jsonReader = Json.createReader(inputStream);
157 policyNames = jsonReader.readArray();
158 serviceTypeNamesList = new ArrayList<>();
159 for (int i = 0; i < policyNames.size(); i++) {
160 javax.json.JsonObject policyName = policyNames.getJsonObject(i);
161 String name = policyName.getJsonString("serviceTypePolicyName").getString();
162 serviceTypeNamesList.add(name);
165 } catch (FileNotFoundException e) {
166 LOGGER.error("Exception Occured while initializing the JSONConfig file"+e);
169 if(inputStream != null){
172 if(jsonReader != null){
175 } catch (IOException e) {
176 LOGGER.error("Exception Occured while closing the File InputStream"+e);
182 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
183 LOGGER.debug("doPost");
185 // if request contains multipart-form-data
186 if (ServletFileUpload.isMultipartContent(request)) {
187 uploadFile(request, response);
189 // all other post request has json params in body
191 fileOperation(request, response);
193 } catch (Exception e) {
195 setError(e, response);
196 }catch(Exception e1){
197 LOGGER.error("Exception Occured"+e1);
202 //Set Error Message for Exception
203 private void setError(Exception t, HttpServletResponse response) throws IOException {
205 JSONObject responseJsonObject = error(t.getMessage());
206 response.setContentType(CONTENTTYPE);
207 PrintWriter out = response.getWriter();
208 out.print(responseJsonObject);
210 } catch (Exception x) {
211 LOGGER.error("Exception Occured"+x);
212 response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage());
216 //Policy Import Functionality
217 private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException {
220 Map<String, InputStream> files = new HashMap<>();
222 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
223 for (FileItem item : items) {
224 if (!item.isFormField()) {
225 // Process form file field (input type="file").
226 files.put(item.getName(), item.getInputStream());
227 if(item.getName().endsWith(".xls")){
228 OutputStream outputStream = null;
230 File file = new File(item.getName());
231 outputStream = new FileOutputStream(file);
232 IOUtils.copy(item.getInputStream(), outputStream);
233 outputStream.close();
234 newFile = file.toString();
235 PolicyExportAndImportController importController = new PolicyExportAndImportController();
236 importController.importRepositoryFile(newFile, request);
238 LOGGER.error("Upload error : " + e);
240 if(outputStream != null){
241 outputStream.close();
248 JSONObject responseJsonObject = null;
249 responseJsonObject = this.success();
250 response.setContentType(CONTENTTYPE);
251 PrintWriter out = response.getWriter();
252 out.print(responseJsonObject);
254 } catch (Exception e) {
255 LOGGER.debug("Cannot write file");
256 throw new ServletException("Cannot write file", e);
260 //File Operation Functionality
261 private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
262 JSONObject responseJsonObject = null;
264 StringBuilder sb = new StringBuilder();
265 BufferedReader br = request.getReader();
267 while ((str = br.readLine()) != null) {
271 JSONObject jObj = new JSONObject(sb.toString());
272 JSONObject params = jObj.getJSONObject("params");
273 Mode mode = Mode.valueOf(params.getString("mode"));
277 responseJsonObject = addFolder(params, request);
280 responseJsonObject = copy(params, request);
283 responseJsonObject = delete(params, request);
287 responseJsonObject = editFile(params);
290 responseJsonObject = list(params, request);
293 responseJsonObject = rename(params, request);
295 case DESCRIBEPOLICYFILE:
296 responseJsonObject = describePolicy(params);
299 responseJsonObject = switchVersion(params, request);
302 responseJsonObject = searchPolicyList(params, request);
305 throw new ServletException("not implemented");
307 if (responseJsonObject == null) {
308 responseJsonObject = error("generic error : responseJsonObject is null");
310 } catch (Exception e) {
311 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While doing File Operation" + e);
312 responseJsonObject = error(e.getMessage());
314 response.setContentType(CONTENTTYPE);
315 PrintWriter out = response.getWriter();
316 out.print(responseJsonObject);
320 private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) {
321 Set<String> scopes = null;
322 List<String> roles = null;
323 List<Object> policyData = new ArrayList<>();
324 JSONArray policyList = null;
325 if(params.has("policyList")){
326 policyList = (JSONArray) params.get("policyList");
328 PolicyController controller = getPolicyControllerInstance();
329 List<JSONObject> resultList = new ArrayList<>();
331 //Get the Login Id of the User from Request
332 String userId = UserUtils.getUserSession(request).getOrgUserId();
333 //Check if the Role and Scope Size are Null get the values from db.
334 List<Object> userRoles = controller.getRoles(userId);
335 roles = new ArrayList<>();
336 scopes = new HashSet<>();
337 for(Object role: userRoles){
338 Roles userRole = (Roles) role;
339 roles.add(userRole.getRole());
340 if(userRole.getScope() != null){
341 if(userRole.getScope().contains(",")){
342 String[] multipleScopes = userRole.getScope().split(",");
343 for(int i =0; i < multipleScopes.length; i++){
344 scopes.add(multipleScopes[i]);
347 scopes.add(userRole.getScope());
351 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
352 if(scopes.isEmpty()){
353 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
355 Set<String> tempScopes = scopes;
356 for(String scope : tempScopes){
357 List<Object> scopesList = queryPolicyEditorScopes(scope);
358 if(!scopesList.isEmpty()){
359 for(int i = 0; i < scopesList.size(); i++){
360 PolicyEditorScopes tempScope = (PolicyEditorScopes) scopesList.get(i);
361 scopes.add(tempScope.getScopeName());
366 if(policyList!= null){
367 for(int i = 0; i < policyList.length(); i++){
368 String policyName = policyList.get(i).toString().replace(".xml", "");
369 String version = policyName.substring(policyName.lastIndexOf(".")+1);
370 policyName = policyName.substring(0, policyName.lastIndexOf(".")).replace(".", File.separator);
371 if(policyName.contains("\\")){
372 policyName = policyName.replace("\\", "\\\\");
374 String policyVersionQuery = "From PolicyVersion where policy_name ='"+policyName+"' and active_version = '"+version+"'and id >0";
375 List<Object> activeData = controller.getDataByQuery(policyVersionQuery);
376 if(!activeData.isEmpty()){
377 PolicyVersion policy = (PolicyVersion) activeData.get(0);
378 JSONObject el = new JSONObject();
379 el.put("name", policy.getPolicyName().replace(File.separator, "/"));
380 el.put("date", policy.getModifiedDate());
381 el.put("version", policy.getActiveVersion());
383 el.put("type", "file");
384 el.put("createdBy", getUserName(policy.getCreatedBy()));
385 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
390 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ){
391 policyData = controller.getData(PolicyVersion.class);
393 List<Object> filterdatas = controller.getData(PolicyVersion.class);
394 for(Object filter : filterdatas){
395 PolicyVersion filterdata = (PolicyVersion) filter;
397 String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator));
398 if(scopes.contains(scopeName)){
399 policyData.add(filterdata);
402 LOGGER.error("Exception occured while filtering policyversion data"+e);
407 if(!policyData.isEmpty()){
408 for(int i =0; i < policyData.size(); i++){
409 PolicyVersion policy = (PolicyVersion) policyData.get(i);
410 JSONObject el = new JSONObject();
411 el.put("name", policy.getPolicyName().replace(File.separator, "/"));
412 el.put("date", policy.getModifiedDate());
413 el.put("version", policy.getActiveVersion());
415 el.put("type", "file");
416 el.put("createdBy", getUserName(policy.getCreatedBy()));
417 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
423 LOGGER.error("Exception occured while reading policy Data from Policy Version table for Policy Search Data"+e);
426 return new JSONObject().put(RESULT, resultList);
429 //Switch Version Functionality
430 private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{
431 String path = params.getString("path");
432 String userId = null;
434 userId = UserUtils.getUserSession(request).getOrgUserId();
435 } catch (Exception e) {
436 LOGGER.error("Exception Occured while reading userid from cookie" +e);
439 String removeExtension = path.replace(".xml", "");
440 if(path.startsWith("/")){
441 policyName = removeExtension.substring(1, removeExtension.lastIndexOf("."));
443 policyName = removeExtension.substring(0, removeExtension.lastIndexOf("."));
446 String activePolicy = null;
447 PolicyController controller = getPolicyControllerInstance();
448 if(params.toString().contains("activeVersion")){
449 String activeVersion = params.getString("activeVersion");
450 String highestVersion = params.get("highestVersion").toString();
451 if(Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)){
452 return error("The Version shouldn't be greater than Highest Value");
454 activePolicy = policyName + "." + activeVersion + ".xml";
455 String dbCheckName = activePolicy.replace("/", ".");
456 if(dbCheckName.contains("Config_")){
457 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
458 }else if(dbCheckName.contains("Action_")){
459 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
460 }else if(dbCheckName.contains("Decision_")){
461 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
463 String[] splitDBCheckName = dbCheckName.split(":");
464 String peQuery = "FROM PolicyEntity where policyName = '"+splitDBCheckName[1]+"' and scope ='"+splitDBCheckName[0]+"'";
465 List<Object> policyEntity = controller.getDataByQuery(peQuery);
466 PolicyEntity pentity = (PolicyEntity) policyEntity.get(0);
467 if(pentity.isDeleted()){
468 return error("The Policy is Not Existing in Workspace");
470 if(policyName.contains("/")){
471 policyName = policyName.replace("/", File.separator);
473 policyName = policyName.substring(policyName.indexOf(File.separator)+1);
474 if(policyName.contains("\\")){
475 policyName = policyName.replace(File.separator, "\\");
477 policyName = splitDBCheckName[0].replace(".", File.separator)+File.separator+policyName;
478 String watchPolicyName = policyName;
479 if(policyName.contains("/")){
480 policyName = policyName.replace("/", File.separator);
482 if(policyName.contains("\\")){
483 policyName = policyName.replace("\\", "\\\\");
485 String query = "update PolicyVersion set active_version='"+activeVersion+"' where policy_name ='"+policyName+"' and id >0";
487 controller.executeQuery(query);
488 //Policy Notification
489 PolicyVersion entity = new PolicyVersion();
490 entity.setPolicyName(watchPolicyName);
491 entity.setActiveVersion(Integer.parseInt(activeVersion));
492 entity.setModifiedBy(userId);
493 controller.watchPolicyFunction(entity, activePolicy, "SwitchVersion");
498 return controller.switchVersionPolicyContent(policyName);
502 private JSONObject describePolicy(JSONObject params) throws ServletException{
503 JSONObject object = null;
504 String path = params.getString("path");
505 String policyName = null;
506 if(path.startsWith("/")){
507 path = path.substring(1);
508 policyName = path.substring(path.lastIndexOf("/") +1);
509 path = path.replace("/", ".");
511 path = path.replace("/", ".");
514 if(path.contains("Config_")){
515 path = path.replace(".Config_", ":Config_");
516 }else if(path.contains("Action_")){
517 path = path.replace(".Action_", ":Action_");
518 }else if(path.contains("Decision_")){
519 path = path.replace(".Decision_", ":Decision_");
521 PolicyController controller = getPolicyControllerInstance();
522 String[] split = path.split(":");
523 String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'";
524 List<Object> queryData = controller.getDataByQuery(query);
525 if(!queryData.isEmpty()){
526 PolicyEntity entity = (PolicyEntity) queryData.get(0);
528 BufferedWriter bw = null;
530 temp = File.createTempFile(policyName, ".tmp");
531 bw = new BufferedWriter(new FileWriter(temp));
532 bw.write(entity.getPolicyData());
534 object = HumanPolicyComponent.DescribePolicy(temp);
535 } catch (IOException e) {
536 LOGGER.error("Exception Occured while Describing the Policy"+e);
544 } catch (IOException e) {
545 LOGGER.error("Exception Occured while Closing the File Writer"+e);
550 return error("Error Occured while Describing the Policy");
556 //Get the List of Policies and Scopes for Showing in Editor tab
557 private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException {
558 Set<String> scopes = null;
559 List<String> roles = null;
561 PolicyController controller = getPolicyControllerInstance();
562 //Get the Login Id of the User from Request
563 String testUserID = getTestUserId();
564 String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId();
565 //Check if the Role and Scope Size are Null get the values from db.
566 List<Object> userRoles = controller.getRoles(userId);
567 roles = new ArrayList<>();
568 scopes = new HashSet<>();
569 for(Object role: userRoles){
570 Roles userRole = (Roles) role;
571 roles.add(userRole.getRole());
572 if(userRole.getScope() != null){
573 if(userRole.getScope().contains(",")){
574 String[] multipleScopes = userRole.getScope().split(",");
575 for(int i =0; i < multipleScopes.length; i++){
576 scopes.add(multipleScopes[i]);
579 scopes.add(userRole.getScope());
584 List<JSONObject> resultList = new ArrayList<>();
585 boolean onlyFolders = params.getBoolean("onlyFolders");
586 String path = params.getString("path");
587 if(path.contains("..xml")){
588 path = path.replaceAll("..xml", "").trim();
591 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
592 if(scopes.isEmpty()){
593 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
595 if(!"/".equals(path)){
596 String tempScope = path.substring(1, path.length());
597 tempScope = tempScope.replace("/", File.separator);
598 scopes.add(tempScope);
603 if("/".equals(path)){
604 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
605 List<Object> scopesList = queryPolicyEditorScopes(null);
606 for(Object list : scopesList){
607 PolicyEditorScopes scope = (PolicyEditorScopes) list;
608 if(!(scope.getScopeName().contains(File.separator))){
609 JSONObject el = new JSONObject();
610 el.put("name", scope.getScopeName());
611 el.put("date", scope.getCreatedDate());
613 el.put("type", "dir");
614 el.put("createdBy", scope.getUserCreatedBy().getUserName());
615 el.put("modifiedBy", scope.getUserModifiedBy().getUserName());
619 }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){
620 for(Object scope : scopes){
621 JSONObject el = new JSONObject();
622 List<Object> scopesList = queryPolicyEditorScopes(scope.toString());
623 if(!scopesList.isEmpty()){
624 PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
625 el.put("name", scopeById.getScopeName());
626 el.put("date", scopeById.getCreatedDate());
628 el.put("type", "dir");
629 el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
630 el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
637 String scopeName = path.substring(path.indexOf("/") +1);
638 activePolicyList(scopeName, resultList, roles, scopes, onlyFolders);
639 } catch (Exception ex) {
640 LOGGER.error("Error Occured While reading Policy Files List"+ex );
644 return new JSONObject().put(RESULT, resultList);
645 } catch (Exception e) {
646 LOGGER.error("list", e);
647 return error(e.getMessage());
651 private List<Object> queryPolicyEditorScopes(String scopeName){
652 String scopeNamequery = "";
653 if(scopeName == null){
654 scopeNamequery = "from PolicyEditorScopes";
656 scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"%'";
658 PolicyController controller = getPolicyControllerInstance();
659 List<Object> scopesList = controller.getDataByQuery(scopeNamequery);
663 //Get Active Policy List based on Scope Selection form Policy Version table
664 private void activePolicyList(String scopeName, List<JSONObject> resultList, List<String> roles, Set<String> scopes, boolean onlyFolders){
665 PolicyController controller = getPolicyControllerInstance();
666 if(scopeName.contains("/")){
667 scopeName = scopeName.replace("/", File.separator);
669 if(scopeName.contains("\\")){
670 scopeName = scopeName.replace("\\", "\\\\\\\\");
672 String query = "from PolicyVersion where POLICY_NAME like '" +scopeName+"%'";
673 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like '" +scopeName+"%'";
674 List<Object> activePolicies = controller.getDataByQuery(query);
675 List<Object> scopesList = controller.getDataByQuery(scopeNamequery);
676 for(Object list : scopesList){
677 PolicyEditorScopes scopeById = (PolicyEditorScopes) list;
678 String scope = scopeById.getScopeName();
679 if(scope.contains(File.separator)){
680 String checkScope = scope.substring(0, scope.lastIndexOf(File.separator));
681 if(scopeName.contains("\\\\")){
682 scopeName = scopeName.replace("\\\\", File.separator);
684 if(scope.contains(File.separator)){
685 scope = scope.substring(checkScope.length()+1);
686 if(scope.contains(File.separator)){
687 scope = scope.substring(0, scope.indexOf(File.separator));
690 if(scopeName.equalsIgnoreCase(checkScope)){
691 JSONObject el = new JSONObject();
692 el.put("name", scope);
693 el.put("date", scopeById.getModifiedDate());
695 el.put("type", "dir");
696 el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
697 el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
702 String scopeNameCheck = null;
703 for (Object list : activePolicies) {
704 PolicyVersion policy = (PolicyVersion) list;
705 String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator));
706 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
707 if((scopeName.contains("\\\\"))){
708 scopeNameCheck = scopeName.replace("\\\\", File.separator);
710 scopeNameCheck = scopeName;
712 if(scopeNameValue.equals(scopeNameCheck)){
713 JSONObject el = new JSONObject();
714 el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
715 el.put("date", policy.getModifiedDate());
716 el.put("version", policy.getActiveVersion());
718 el.put("type", "file");
719 el.put("createdBy", getUserName(policy.getCreatedBy()));
720 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
723 }else if(!scopes.isEmpty()){
724 if(scopes.contains(scopeNameValue)){
725 JSONObject el = new JSONObject();
726 el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
727 el.put("date", policy.getModifiedDate());
728 el.put("version", policy.getActiveVersion());
730 el.put("type", "file");
731 el.put("createdBy", getUserName(policy.getCreatedBy()));
732 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
739 private String getUserName(String loginId){
740 PolicyController controller = getPolicyControllerInstance();
741 UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
742 if(userInfo == null){
745 return userInfo.getUserName();
749 private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
751 boolean isActive = false;
752 List<String> policyActiveInPDP = new ArrayList<>();
753 Set<String> scopeOfPolicyActiveInPDP = new HashSet<>();
754 String userId = UserUtils.getUserSession(request).getOrgUserId();
755 String oldPath = params.getString("path");
756 String newPath = params.getString("newPath");
757 oldPath = oldPath.substring(oldPath.indexOf("/")+1);
758 newPath = newPath.substring(newPath.indexOf("/")+1);
759 if(oldPath.endsWith(".xml")){
760 JSONObject result = policyRename(oldPath, newPath, userId);
761 if(!(Boolean)(result.getJSONObject("result").get("success"))){
765 String scopeName = oldPath;
766 String newScopeName = newPath;
767 if(scopeName.contains("/")){
768 scopeName = scopeName.replace("/", File.separator);
769 newScopeName = newScopeName.replace("/", File.separator);
771 if(scopeName.contains("\\")){
772 scopeName = scopeName.replace("\\", "\\\\\\\\");
773 newScopeName = newScopeName.replace("\\", "\\\\\\\\");
775 PolicyController controller = getPolicyControllerInstance();
776 String query = "from PolicyVersion where POLICY_NAME like'" +scopeName+"%'";
777 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"%'";
778 List<Object> activePolicies = controller.getDataByQuery(query);
779 List<Object> scopesList = controller.getDataByQuery(scopeNamequery);
780 for(Object object : activePolicies){
781 PolicyVersion activeVersion = (PolicyVersion) object;
782 String policyOldPath = activeVersion.getPolicyName().replace(File.separator, "/") + "." + activeVersion.getActiveVersion() + ".xml";
783 String policyNewPath = policyOldPath.replace(oldPath, newPath);
784 JSONObject result = policyRename(policyOldPath, policyNewPath, userId);
785 if(!(Boolean)(result.getJSONObject("result").get("success"))){
787 policyActiveInPDP.add(policyOldPath);
788 String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf("/"));
789 scopeOfPolicyActiveInPDP.add(scope.replace("/", File.separator));
792 boolean rename = false;
793 if(activePolicies.size() != policyActiveInPDP.size()){
797 UserInfo userInfo = new UserInfo();
798 userInfo.setUserLoginId(userId);
799 if(policyActiveInPDP.size() == 0){
800 renameScope(scopesList, scopeName, newScopeName, controller);
802 renameScope(scopesList, scopeName, newScopeName, controller);
803 for(String scope : scopeOfPolicyActiveInPDP){
804 PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes();
805 editorScopeEntity.setScopeName(scope.replace("\\", "\\\\\\\\"));
806 editorScopeEntity.setUserCreatedBy(userInfo);
807 editorScopeEntity.setUserModifiedBy(userInfo);
808 controller.saveData(editorScopeEntity);
812 return error("The Following policies rename failed. Since they are active in PDP Groups" +policyActiveInPDP);
816 } catch (Exception e) {
817 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
818 return error(e.getMessage());
822 private void renameScope(List<Object> scopesList, String scopeName, String newScopeName, PolicyController controller){
823 for(Object object : scopesList){
824 PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object;
825 if(scopeName.contains("\\\\\\\\")){
826 scopeName = scopeName.replace("\\\\\\\\", File.separator);
827 newScopeName = newScopeName.replace("\\\\\\\\", File.separator);
829 String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName);
830 editorScopeEntity.setScopeName(scope);
831 controller.updateData(editorScopeEntity);
835 private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
837 PolicyEntity entity = null;
838 PolicyController controller = getPolicyControllerInstance();
840 String policyVersionName = newPath.replace(".xml", "");
841 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")).replace("/", File.separator);
843 String oldpolicyVersionName = oldPath.replace(".xml", "");
844 String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf(".")).replace("/", File.separator);
846 String newpolicyName = newPath.replace("/", ".");
847 String newPolicyCheck = newpolicyName;
848 if(newPolicyCheck.contains("Config_")){
849 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
850 }else if(newPolicyCheck.contains("Action_")){
851 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
852 }else if(newPolicyCheck.contains("Decision_")){
853 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
855 String[] newPolicySplit = newPolicyCheck.split(":");
857 String orignalPolicyName = oldPath.replace("/", ".");
858 String oldPolicyCheck = orignalPolicyName;
859 if(oldPolicyCheck.contains("Config_")){
860 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
861 }else if(oldPolicyCheck.contains("Action_")){
862 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
863 }else if(oldPolicyCheck.contains("Decision_")){
864 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
866 String[] oldPolicySplit = oldPolicyCheck.split(":");
868 //Check PolicyEntity table with newPolicy Name
869 String policyEntityquery = "FROM PolicyEntity where policyName = '"+newPolicySplit[1]+"' and scope ='"+newPolicySplit[0]+"'";
870 List<Object> queryData = controller.getDataByQuery(policyEntityquery);
871 if(!queryData.isEmpty()){
872 entity = (PolicyEntity) queryData.get(0);
873 return error("Policy rename failed. Since, the policy with same name already exists.");
876 //Query the Policy Entity with oldPolicy Name
877 String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf("."));
878 String oldpolicyEntityquery = "FROM PolicyEntity where policyName like '"+policyEntityCheck+"%' and scope ='"+oldPolicySplit[0]+"'";
879 List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery);
880 if(!oldEntityData.isEmpty()){
881 String groupQuery = "FROM PolicyGroupEntity where (";
882 for(int i=0; i<oldEntityData.size(); i++){
883 entity = (PolicyEntity) oldEntityData.get(i);
885 groupQuery = groupQuery + "policyid =" + entity.getPolicyId();
887 groupQuery = groupQuery + " or policyid =" + entity.getPolicyId();
890 groupQuery = groupQuery + ")";
891 List<Object> groupEntityData = controller.getDataByQuery(groupQuery);
892 if(groupEntityData.size() > 0){
893 return error("Policy rename failed. Since the policy or its version is active in PDP Groups.");
895 for(int i=0; i<oldEntityData.size(); i++){
896 entity = (PolicyEntity) oldEntityData.get(i);
897 checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0] , newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
900 return error("Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin.");
904 } catch (Exception e) {
905 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
906 return error(e.getMessage());
910 private JSONObject checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, String oldScope, String removeoldPolicyExtension,
911 String policyName, String newpolicyName, String oldpolicyName, String userId) throws ServletException{
913 ConfigurationDataEntity configEntity = entity.getConfigurationData();
914 ActionBodyEntity actionEntity = entity.getActionBodyEntity();
915 PolicyController controller = getPolicyControllerInstance();
917 String oldPolicyNameWithoutExtension = removeoldPolicyExtension;
918 String newPolicyNameWithoutExtension = removenewPolicyExtension;
919 if(removeoldPolicyExtension.endsWith(".xml")){
920 oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf("."));
921 newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf("."));
923 entity.setPolicyName(entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
924 entity.setPolicyData(entity.getPolicyData().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
925 entity.setScope(newScope);
926 entity.setModifiedBy(userId);
927 if(newpolicyName.contains("Config_")){
928 String oldConfigurationName = configEntity.getConfigurationName();
929 configEntity.setConfigurationName(configEntity.getConfigurationName().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
930 controller.updateData(configEntity);
931 String newConfigurationName = configEntity.getConfigurationName();
932 File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName);
934 File renamefile = new File(PolicyController.getConfigHome() + File.separator + newConfigurationName);
935 file.renameTo(renamefile);
937 }else if(newpolicyName.contains("Action_")){
938 String oldConfigurationName = actionEntity.getActionBodyName();
939 actionEntity.setActionBody(actionEntity.getActionBody().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
940 controller.updateData(actionEntity);
941 String newConfigurationName = actionEntity.getActionBodyName();
942 File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName);
944 File renamefile = new File(PolicyController.getActionHome() + File.separator + newConfigurationName);
945 file.renameTo(renamefile);
948 controller.updateData(entity);
950 PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldpolicyName);
951 versionEntity.setPolicyName(policyName);
952 versionEntity.setModifiedBy(userId);
953 controller.updateData(versionEntity);
954 String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator)+1);
955 String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
956 if(movePolicyCheck.equals(moveOldPolicyCheck)){
957 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move");
959 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename");
962 } catch (Exception e) {
963 LOGGER.error("Exception Occured"+e);
964 return error(e.getMessage());
968 private JSONObject cloneRecord(String newpolicyName, String oldScope, String removeoldPolicyExtension, String newScope, String removenewPolicyExtension, PolicyEntity entity, String userId) throws ServletException{
969 FileWriter fw = null;
970 String queryEntityName = null;
971 PolicyController controller = getPolicyControllerInstance();
972 PolicyEntity cloneEntity = new PolicyEntity();
973 cloneEntity.setPolicyName(newpolicyName);
974 removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
975 removenewPolicyExtension = removenewPolicyExtension.replace(".xml", "");
976 cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope+"."+removeoldPolicyExtension, newScope+"."+removenewPolicyExtension));
977 cloneEntity.setScope(entity.getScope());
978 String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
979 String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
980 if(newpolicyName.contains("Config_")){
981 ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
982 configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
983 queryEntityName = configurationDataEntity.getConfigurationName();
984 configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody());
985 configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType());
986 configurationDataEntity.setDeleted(false);
987 configurationDataEntity.setCreatedBy(userId);
988 configurationDataEntity.setModifiedBy(userId);
989 controller.saveData(configurationDataEntity);
990 ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
991 cloneEntity.setConfigurationData(configEntiy);
992 String newConfigurationName = configEntiy.getConfigurationName();
994 fw = new FileWriter(PolicyController.getConfigHome() + File.separator + newConfigurationName);
995 BufferedWriter bw = new BufferedWriter(fw);
996 bw.write(configEntiy.getConfigBody());
998 } catch (IOException e) {
999 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1001 }else if(newpolicyName.contains("Action_")){
1002 ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
1003 actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1004 queryEntityName = actionBodyEntity.getActionBodyName();
1005 actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody());
1006 actionBodyEntity.setDeleted(false);
1007 actionBodyEntity.setCreatedBy(userId);
1008 actionBodyEntity.setModifiedBy(userId);
1009 controller.saveData(actionBodyEntity);
1010 ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class, "actionBodyName", queryEntityName);
1011 cloneEntity.setActionBodyEntity(actionEntiy);
1012 String newConfigurationName = actionEntiy.getActionBodyName();
1014 fw = new FileWriter(PolicyController.getActionHome() + File.separator + newConfigurationName);
1015 BufferedWriter bw = new BufferedWriter(fw);
1016 bw.write(actionEntiy.getActionBody());
1018 } catch (IOException e) {
1019 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1025 } catch (IOException e) {
1026 LOGGER.error("Exception Occured While closing the File input stream"+e);
1029 cloneEntity.setDeleted(entity.isDeleted());
1030 cloneEntity.setCreatedBy(userId);
1031 cloneEntity.setModifiedBy(userId);
1032 controller.saveData(cloneEntity);
1038 private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
1040 String userId = UserUtils.getUserSession(request).getOrgUserId();
1041 String oldPath = params.getString("path");
1042 String newPath = params.getString("newPath");
1043 oldPath = oldPath.substring(oldPath.indexOf("/")+1);
1044 newPath = newPath.substring(newPath.indexOf("/")+1);
1046 String policyVersionName = newPath.replace(".xml", "");
1047 String version = policyVersionName.substring(policyVersionName.indexOf(".")+1);
1048 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")).replace("/", File.separator);
1050 String newpolicyName = newPath.replace("/", ".");
1052 String orignalPolicyName = oldPath.replace("/", ".");
1054 String newPolicyCheck = newpolicyName;
1055 if(newPolicyCheck.contains("Config_")){
1056 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
1057 }else if(newPolicyCheck.contains("Action_")){
1058 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
1059 }else if(newPolicyCheck.contains("Decision_")){
1060 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
1062 String[] newPolicySplit = newPolicyCheck.split(":");
1064 String oldPolicyCheck = orignalPolicyName;
1065 if(oldPolicyCheck.contains("Config_")){
1066 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
1067 }else if(oldPolicyCheck.contains("Action_")){
1068 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
1069 }else if(oldPolicyCheck.contains("Decision_")){
1070 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
1072 String[] oldPolicySplit = oldPolicyCheck.split(":");
1074 PolicyController controller = getPolicyControllerInstance();
1076 PolicyEntity entity = null;
1077 boolean success = false;
1079 //Check PolicyEntity table with newPolicy Name
1080 String policyEntityquery = "FROM PolicyEntity where policyName = '"+newPolicySplit[1]+"' and scope ='"+newPolicySplit[0]+"'";
1081 List<Object> queryData = controller.getDataByQuery(policyEntityquery);
1082 if(!queryData.isEmpty()){
1083 return error("Policy already exists with same name");
1086 //Query the Policy Entity with oldPolicy Name
1087 policyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'";
1088 queryData = controller.getDataByQuery(policyEntityquery);
1089 if(!queryData.isEmpty()){
1090 entity = (PolicyEntity) queryData.get(0);
1093 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId);
1098 PolicyVersion entityItem = new PolicyVersion();
1099 entityItem.setActiveVersion(Integer.parseInt(version));
1100 entityItem.setHigherVersion(Integer.parseInt(version));
1101 entityItem.setPolicyName(policyName);
1102 entityItem.setCreatedBy(userId);
1103 entityItem.setModifiedBy(userId);
1104 controller.saveData(entityItem);
1107 LOGGER.debug("copy from: {} to: {}" + oldPath +newPath);
1110 } catch (Exception e) {
1111 LOGGER.error("copy", e);
1112 return error(e.getMessage());
1116 //Delete Policy or Scope Functionality
1117 private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
1118 PolicyController controller = getPolicyControllerInstance();
1119 PolicyRestController restController = new PolicyRestController();
1120 PolicyEntity policyEntity = null;
1121 String policyNamewithoutExtension;
1123 String userId = UserUtils.getUserSession(request).getOrgUserId();
1124 String deleteVersion = "";
1125 String path = params.getString("path");
1126 LOGGER.debug("delete {}" +path);
1127 if(params.has("deleteVersion")){
1128 deleteVersion = params.getString("deleteVersion");
1130 path = path.substring(path.indexOf("/")+1);
1131 String policyNamewithExtension = path.replace("/", File.separator);
1132 String policyVersionName = policyNamewithExtension.replace(".xml", "");
1134 if(path.endsWith(".xml")){
1135 policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf("."));
1136 policyNamewithoutExtension = policyNamewithoutExtension.replace(File.separator, ".");
1137 String splitPolicyName = null;
1138 if(policyNamewithoutExtension.contains("Config_")){
1139 splitPolicyName = policyNamewithoutExtension.replace(".Config_", ":Config_");
1140 }else if(policyNamewithoutExtension.contains("Action_")){
1141 splitPolicyName = policyNamewithoutExtension.replace(".Action_", ":Action_");
1142 }else if(policyNamewithoutExtension.contains("Decision_")){
1143 splitPolicyName = policyNamewithoutExtension.replace(".Decision_", ":Decision_");
1145 String[] split = splitPolicyName.split(":");
1146 query = "FROM PolicyEntity where policyName like '"+split[1]+"%' and scope ='"+split[0]+"'";
1148 policyNamewithoutExtension = path.replace(File.separator, ".");
1149 query = "FROM PolicyEntity where scope like '"+policyNamewithoutExtension+"%'";
1152 List<Object> policyEntityobjects = controller.getDataByQuery(query);
1153 String activePolicyName = null;
1154 boolean pdpCheck = false;
1155 if(path.endsWith(".xml")){
1156 policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator);
1157 int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf(".")+1));
1158 if("ALL".equals(deleteVersion)){
1159 if(!policyEntityobjects.isEmpty()){
1160 for(Object object : policyEntityobjects){
1161 policyEntity = (PolicyEntity) object;
1162 String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'";
1163 List<Object> groupobject = controller.getDataByQuery(groupEntityquery);
1164 if(!groupobject.isEmpty()){
1166 activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName();
1168 //Delete the entity from Elastic Search Database
1169 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1170 restController.deleteElasticData(searchFileName);
1171 //Delete the entity from Policy Entity table
1172 controller.deleteData(policyEntity);
1173 if(policyNamewithoutExtension.contains("Config_")){
1174 controller.deleteData(policyEntity.getConfigurationData());
1175 }else if(policyNamewithoutExtension.contains("Action_")){
1176 controller.deleteData(policyEntity.getActionBodyEntity());
1181 //Policy Notification
1182 PolicyVersion versionEntity = new PolicyVersion();
1183 versionEntity.setPolicyName(policyNamewithoutExtension);
1184 versionEntity.setModifiedBy(userId);
1185 controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll");
1187 //Delete from policyVersion table
1188 String getActivePDPPolicyVersion = activePolicyName.replace(".xml", "");
1189 getActivePDPPolicyVersion = getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf(".")+1);
1190 String policyVersionQuery = "update PolicyVersion set active_version='"+getActivePDPPolicyVersion+"' , highest_version='"+getActivePDPPolicyVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1191 if(policyVersionQuery != null){
1192 controller.executeQuery(policyVersionQuery);
1194 return error("Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "+activePolicyName);
1196 //No Active Policy in PDP. So, deleting all entries from policyVersion table
1197 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1198 if(policyVersionQuery != null){
1199 controller.executeQuery(policyVersionQuery);
1202 }else if("CURRENT".equals(deleteVersion)){
1203 String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1);
1204 String currentVersionScope = policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator)).replace(File.separator, ".");
1205 query = "FROM PolicyEntity where policyName = '"+currentVersionPolicyName+"' and scope ='"+currentVersionScope+"'";
1206 List<Object> policyEntitys = controller.getDataByQuery(query);
1207 if(!policyEntitys.isEmpty()){
1208 policyEntity = (PolicyEntity) policyEntitys.get(0);
1210 if(policyEntity != null){
1211 String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"' and policyid > 0";
1212 List<Object> groupobject = controller.getDataByQuery(groupEntityquery);
1213 if(groupobject.isEmpty()){
1214 //Delete the entity from Elastic Search Database
1215 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1216 restController.deleteElasticData(searchFileName);
1217 //Delete the entity from Policy Entity table
1218 controller.deleteData(policyEntity);
1219 if(policyNamewithoutExtension.contains("Config_")){
1220 controller.deleteData(policyEntity.getConfigurationData());
1221 }else if(policyNamewithoutExtension.contains("Action_")){
1222 controller.deleteData(policyEntity.getActionBodyEntity());
1226 int highestVersion = 0;
1227 if(!policyEntityobjects.isEmpty()){
1228 for(Object object : policyEntityobjects){
1229 policyEntity = (PolicyEntity) object;
1230 String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
1231 int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf(".")+1));
1232 if(policyEntityVersion > highestVersion && policyEntityVersion != version){
1233 highestVersion = policyEntityVersion;
1238 //Policy Notification
1239 PolicyVersion entity = new PolicyVersion();
1240 entity.setPolicyName(policyNamewithoutExtension);
1241 entity.setActiveVersion(highestVersion);
1242 entity.setModifiedBy(userId);
1243 controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne");
1245 String updatequery = "update PolicyVersion set active_version='"+highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"'";
1246 controller.executeQuery(updatequery);
1248 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1249 if(policyVersionQuery != null){
1250 controller.executeQuery(policyVersionQuery);
1254 return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'");
1259 List<String> activePoliciesInPDP = new ArrayList<String>();
1260 if(!policyEntityobjects.isEmpty()){
1261 for(Object object : policyEntityobjects){
1262 policyEntity = (PolicyEntity) object;
1263 String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'";
1264 List<Object> groupobject = controller.getDataByQuery(groupEntityquery);
1265 if(!groupobject.isEmpty()){
1267 activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName());
1269 //Delete the entity from Elastic Search Database
1270 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1271 restController.deleteElasticData(searchFileName);
1272 //Delete the entity from Policy Entity table
1273 controller.deleteData(policyEntity);
1274 policyNamewithoutExtension = policyEntity.getPolicyName();
1275 if(policyNamewithoutExtension.contains("Config_")){
1276 controller.deleteData(policyEntity.getConfigurationData());
1277 }else if(policyNamewithoutExtension.contains("Action_")){
1278 controller.deleteData(policyEntity.getActionBodyEntity());
1282 //Delete from policyVersion and policyEditor Scope table
1283 String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1284 controller.executeQuery(policyVersionQuery);
1286 //Policy Notification
1287 PolicyVersion entity = new PolicyVersion();
1288 entity.setPolicyName(path);
1289 entity.setModifiedBy(userId);
1290 controller.watchPolicyFunction(entity, path, "DeleteScope");
1292 //Add Active Policies List to PolicyVersionTable
1293 for(int i =0; i < activePoliciesInPDP.size(); i++){
1294 String activePDPPolicyName = activePoliciesInPDP.get(i).replace(".xml", "");
1295 int activePDPPolicyVersion = Integer.parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf(".")+1));
1296 activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf(".")).replace(".", File.separator);
1297 PolicyVersion insertactivePDPVersion = new PolicyVersion();
1298 insertactivePDPVersion.setPolicyName(activePDPPolicyName);
1299 insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion);
1300 insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion);
1301 insertactivePDPVersion.setCreatedBy(userId);
1302 insertactivePDPVersion.setModifiedBy(userId);
1303 controller.saveData(insertactivePDPVersion);
1306 return error("All the Policies has been deleted in Scope. Except the following list of Policies:"+activePoliciesInPDP);
1308 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1309 controller.executeQuery(policyScopeQuery);
1312 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1313 controller.executeQuery(policyScopeQuery);
1317 } catch (Exception e) {
1318 LOGGER.error("delete", e);
1319 return error(e.getMessage());
1324 private JSONObject editFile(JSONObject params) throws ServletException {
1327 PolicyController controller = getPolicyControllerInstance();
1328 String mode = params.getString("mode");
1329 String path = params.getString("path");
1330 LOGGER.debug("editFile path: {}"+ path);
1332 String domain = path.substring(1, path.lastIndexOf("/"));
1333 domain = domain.replace("/", ".");
1335 path = path.substring(1);
1336 path = path.replace("/", ".");
1337 String dbCheckName = path;
1338 if(dbCheckName.contains("Config_")){
1339 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
1340 }else if(dbCheckName.contains("Action_")){
1341 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
1342 }else if(dbCheckName.contains("Decision_")){
1343 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
1346 String[] split = dbCheckName.split(":");
1347 String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'";
1348 List<Object> queryData = controller.getDataByQuery(query);
1349 PolicyEntity entity = (PolicyEntity) queryData.get(0);
1350 InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
1353 Object policy = XACMLPolicyScanner.readPolicy(stream);
1354 PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
1355 policyAdapter.setData(policy);
1357 if("viewPolicy".equalsIgnoreCase(mode)){
1358 policyAdapter.setReadOnly(true);
1359 policyAdapter.setEditPolicy(false);
1361 policyAdapter.setReadOnly(false);
1362 policyAdapter.setEditPolicy(true);
1364 policyAdapter.setDomain(domain);
1365 policyAdapter.setDomainDir(domain);
1366 policyAdapter.setPolicyData(policy);
1367 String policyName = path.replace(".xml", "");
1368 policyName = policyName.substring(0, policyName.lastIndexOf("."));
1369 policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf(".")+1));
1371 PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance();
1372 setpolicyAdapter.configure(policyAdapter,entity);
1374 policyAdapter.setParentPath(null);
1375 ObjectMapper mapper = new ObjectMapper();
1376 String json = mapper.writeValueAsString(policyAdapter);
1377 JsonNode jsonNode = mapper.readTree(json);
1379 return new JSONObject().put(RESULT, jsonNode);
1380 } catch (Exception e) {
1381 LOGGER.error("editFile", e);
1382 return error(e.getMessage());
1387 private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
1388 PolicyController controller = getPolicyControllerInstance();
1391 String userId = UserUtils.getUserSession(request).getOrgUserId();
1392 String path = params.getString("path");
1394 if(params.has("subScopename")){
1395 if(!params.getString("subScopename").equals("")){
1396 name = params.getString("path").replace("/", File.separator) + File.separator +params.getString("subScopename");
1399 name = params.getString("name");
1401 }catch(Exception e){
1402 name = params.getString("name");
1403 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e);
1405 String validateName;
1406 if(name.contains(File.separator)){
1407 validateName = name.substring(name.lastIndexOf(File.separator)+1);
1409 validateName = name;
1411 if(!name.isEmpty()){
1412 String validate = PolicyUtils.emptyPolicyValidator(validateName);
1413 if(!validate.contains("success")){
1414 return error(validate);
1417 LOGGER.debug("addFolder path: {} name: {}" + path +name);
1418 if(!name.equals("")){
1419 if(name.startsWith(File.separator)){
1420 name = name.substring(1);
1422 PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, "scopeName", name);
1424 UserInfo userInfo = new UserInfo();
1425 userInfo.setUserLoginId(userId);
1426 PolicyEditorScopes newScope = new PolicyEditorScopes();
1427 newScope.setScopeName(name);
1428 newScope.setUserCreatedBy(userInfo);
1429 newScope.setUserModifiedBy(userInfo);
1430 controller.saveData(newScope);
1432 return error("Scope Already Exists");
1436 } catch (Exception e) {
1437 LOGGER.error("addFolder", e);
1438 return error(e.getMessage());
1442 //Return Error Object
1443 private JSONObject error(String msg) throws ServletException {
1445 JSONObject result = new JSONObject();
1446 result.put("success", false);
1447 result.put("error", msg);
1448 return new JSONObject().put(RESULT, result);
1449 } catch (JSONException e) {
1450 throw new ServletException(e);
1454 //Return Success Object
1455 private JSONObject success() throws ServletException {
1457 JSONObject result = new JSONObject();
1458 result.put("success", true);
1459 result.put("error", (Object) null);
1460 return new JSONObject().put(RESULT, result);
1461 } catch (JSONException e) {
1462 throw new ServletException(e);
1466 private PolicyController getPolicyControllerInstance(){
1467 return policyController != null ? getPolicyController() : new PolicyController();
1470 public String getTestUserId() {
1474 public static void setTestUserId(String testUserId) {
1475 PolicyManagerServlet.testUserId = testUserId;