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.openecomp.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.openecomp.policy.common.logging.flexlogger.FlexLogger;
65 import org.openecomp.policy.common.logging.flexlogger.Logger;
66 import org.openecomp.policy.components.HumanPolicyComponent;
67 import org.openecomp.policy.controller.PolicyController;
68 import org.openecomp.policy.controller.PolicyExportAndImportController;
69 import org.openecomp.policy.model.Roles;
70 import org.openecomp.policy.rest.XACMLRest;
71 import org.openecomp.policy.rest.XACMLRestProperties;
72 import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
73 import org.openecomp.policy.rest.jpa.ActionBodyEntity;
74 import org.openecomp.policy.rest.jpa.ConfigurationDataEntity;
75 import org.openecomp.policy.rest.jpa.PolicyEditorScopes;
76 import org.openecomp.policy.rest.jpa.PolicyEntity;
77 import org.openecomp.policy.rest.jpa.PolicyVersion;
78 import org.openecomp.policy.rest.jpa.UserInfo;
79 import org.openecomp.policy.utils.PolicyUtils;
80 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
81 import org.openecomp.policy.xacml.util.XACMLPolicyScanner;
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 PolicyController policyController;
99 public PolicyController getPolicyController() {
100 return policyController;
103 public void setPolicyController(PolicyController policyController) {
104 this.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 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<>();
129 private List<Object> policyData;
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) {
195 setError(e, response);
199 //Set Error Message for Exception
200 private void setError(Exception t, HttpServletResponse response) throws IOException {
202 JSONObject responseJsonObject = error(t.getMessage());
203 response.setContentType(CONTENTTYPE);
204 PrintWriter out = response.getWriter();
205 out.print(responseJsonObject);
207 } catch (Exception x) {
208 LOGGER.error("Exception Occured"+x);
209 response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage());
213 //Policy Import Functionality
214 private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException {
217 Map<String, InputStream> files = new HashMap<>();
219 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
220 for (FileItem item : items) {
221 if (!item.isFormField()) {
222 // Process form file field (input type="file").
223 files.put(item.getName(), item.getInputStream());
224 if(item.getName().endsWith(".xls")){
225 OutputStream outputStream = null;
227 File file = new File(item.getName());
228 outputStream = new FileOutputStream(file);
229 IOUtils.copy(item.getInputStream(), outputStream);
230 outputStream.close();
231 newFile = file.toString();
232 PolicyExportAndImportController importController = new PolicyExportAndImportController();
233 importController.importRepositoryFile(newFile, request);
235 LOGGER.error("Upload error : " + e);
237 if(outputStream != null){
238 outputStream.close();
245 JSONObject responseJsonObject = null;
246 responseJsonObject = this.success();
247 response.setContentType(CONTENTTYPE);
248 PrintWriter out = response.getWriter();
249 out.print(responseJsonObject);
251 } catch (Exception e) {
252 LOGGER.debug("Cannot write file");
253 throw new ServletException("Cannot write file", e);
257 //File Operation Functionality
258 private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
259 JSONObject responseJsonObject = null;
261 StringBuilder sb = new StringBuilder();
262 BufferedReader br = request.getReader();
264 while ((str = br.readLine()) != null) {
268 JSONObject jObj = new JSONObject(sb.toString());
269 JSONObject params = jObj.getJSONObject("params");
270 Mode mode = Mode.valueOf(params.getString("mode"));
273 responseJsonObject = addFolder(params, request);
276 responseJsonObject = copy(params, request);
279 responseJsonObject = delete(params, request);
282 responseJsonObject = editFile(params);
285 responseJsonObject = editFile(params);
288 responseJsonObject = list(params, request);
291 responseJsonObject = rename(params, request);
293 case DESCRIBEPOLICYFILE:
294 responseJsonObject = describePolicy(params);
297 responseJsonObject = addFolder(params, request);
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 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 List<Object> activeData = controller.getDataByQuery(policyVersionQuery);
377 if(!activeData.isEmpty()){
378 PolicyVersion policy = (PolicyVersion) activeData.get(0);
379 JSONObject el = new JSONObject();
380 el.put("name", policy.getPolicyName().replace(File.separator, "/"));
381 el.put("date", policy.getModifiedDate());
382 el.put("version", policy.getActiveVersion());
384 el.put("type", "file");
385 el.put("createdBy", getUserName(policy.getCreatedBy()));
386 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
391 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ){
392 policyData = controller.getData(PolicyVersion.class);
394 List<Object> filterdatas = controller.getData(PolicyVersion.class);
395 for(Object filter : filterdatas){
396 PolicyVersion filterdata = (PolicyVersion) filter;
398 String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator));
399 if(scopes.contains(scopeName)){
400 policyData.add(filterdata);
403 LOGGER.error("Exception occured while filtering policyversion data"+e);
408 if(!policyData.isEmpty()){
409 for(int i =0; i < policyData.size(); i++){
410 PolicyVersion policy = (PolicyVersion) policyData.get(i);
411 JSONObject el = new JSONObject();
412 el.put("name", policy.getPolicyName().replace(File.separator, "/"));
413 el.put("date", policy.getModifiedDate());
414 el.put("version", policy.getActiveVersion());
416 el.put("type", "file");
417 el.put("createdBy", getUserName(policy.getCreatedBy()));
418 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
424 LOGGER.error("Exception occured while reading policy Data from Policy Version table for Policy Search Data"+e);
427 return new JSONObject().put(RESULT, resultList);
430 //Switch Version Functionality
431 private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{
432 String path = params.getString("path");
433 String userId = null;
435 userId = UserUtils.getUserSession(request).getOrgUserId();
436 } catch (Exception e) {
437 LOGGER.error("Exception Occured while reading userid from cookie" +e);
440 String removeExtension = path.replace(".xml", "");
441 if(path.startsWith("/")){
442 policyName = removeExtension.substring(1, removeExtension.lastIndexOf("."));
444 policyName = removeExtension.substring(0, removeExtension.lastIndexOf("."));
447 String activePolicy = null;
448 PolicyController controller = getPolicyControllerInstance();
449 if(params.toString().contains("activeVersion")){
450 String activeVersion = params.getString("activeVersion");
451 String highestVersion = params.get("highestVersion").toString();
452 if(Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)){
453 return error("The Version shouldn't be greater than Highest Value");
455 activePolicy = policyName + "." + activeVersion + ".xml";
456 String dbCheckName = activePolicy.replace("/", ".");
457 if(dbCheckName.contains("Config_")){
458 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
459 }else if(dbCheckName.contains("Action_")){
460 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
461 }else if(dbCheckName.contains("Decision_")){
462 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
464 String[] splitDBCheckName = dbCheckName.split(":");
465 String peQuery = "FROM PolicyEntity where policyName = '"+splitDBCheckName[1]+"' and scope ='"+splitDBCheckName[0]+"'";
466 List<Object> policyEntity = controller.getDataByQuery(peQuery);
467 PolicyEntity pentity = (PolicyEntity) policyEntity.get(0);
468 if(pentity.isDeleted()){
469 return error("The Policy is Not Existing in Workspace");
471 if(policyName.contains("/")){
472 policyName = policyName.replace("/", File.separator);
474 policyName = policyName.substring(policyName.indexOf(File.separator)+1);
475 if(policyName.contains("\\")){
476 policyName = policyName.replace(File.separator, "\\");
478 policyName = splitDBCheckName[0].replace(".", File.separator)+File.separator+policyName;
479 String watchPolicyName = policyName;
480 if(policyName.contains("/")){
481 policyName = policyName.replace("/", File.separator);
483 if(policyName.contains("\\")){
484 policyName = policyName.replace("\\", "\\\\");
486 String query = "update PolicyVersion set active_version='"+activeVersion+"' where policy_name ='"+policyName+"' and id >0";
488 controller.executeQuery(query);
489 //Policy Notification
490 PolicyVersion entity = new PolicyVersion();
491 entity.setPolicyName(watchPolicyName);
492 entity.setActiveVersion(Integer.parseInt(activeVersion));
493 entity.setModifiedBy(userId);
494 controller.watchPolicyFunction(entity, activePolicy, "SwitchVersion");
499 return controller.switchVersionPolicyContent(policyName);
503 private JSONObject describePolicy(JSONObject params) throws ServletException{
504 JSONObject object = null;
505 String path = params.getString("path");
506 String policyName = null;
507 if(path.startsWith("/")){
508 path = path.substring(1);
509 policyName = path.substring(path.lastIndexOf("/") +1);
510 path = path.replace("/", ".");
512 path = path.replace("/", ".");
515 if(path.contains("Config_")){
516 path = path.replace(".Config_", ":Config_");
517 }else if(path.contains("Action_")){
518 path = path.replace(".Action_", ":Action_");
519 }else if(path.contains("Decision_")){
520 path = path.replace(".Decision_", ":Decision_");
522 PolicyController controller = getPolicyControllerInstance();
523 String[] split = path.split(":");
524 String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'";
525 List<Object> queryData = controller.getDataByQuery(query);
526 if(!queryData.isEmpty()){
527 PolicyEntity entity = (PolicyEntity) queryData.get(0);
529 BufferedWriter bw = null;
531 temp = File.createTempFile(policyName, ".tmp");
532 bw = new BufferedWriter(new FileWriter(temp));
533 bw.write(entity.getPolicyData());
535 object = HumanPolicyComponent.DescribePolicy(temp);
536 } catch (IOException e) {
537 LOGGER.error("Exception Occured while Describing the Policy"+e);
545 } catch (IOException e) {
546 LOGGER.error("Exception Occured while Closing the File Writer"+e);
551 return error("Error Occured while Describing the Policy");
557 //Get the List of Policies and Scopes for Showing in Editor tab
558 private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException {
559 Set<String> scopes = null;
560 List<String> roles = null;
562 PolicyController controller = getPolicyControllerInstance();
563 //Get the Login Id of the User from Request
564 String testUserID = getTestUserId();
565 String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId();
566 //Check if the Role and Scope Size are Null get the values from db.
567 List<Object> userRoles = controller.getRoles(userId);
568 roles = new ArrayList<>();
569 scopes = new HashSet<>();
570 for(Object role: userRoles){
571 Roles userRole = (Roles) role;
572 roles.add(userRole.getRole());
573 if(userRole.getScope() != null){
574 if(userRole.getScope().contains(",")){
575 String[] multipleScopes = userRole.getScope().split(",");
576 for(int i =0; i < multipleScopes.length; i++){
577 scopes.add(multipleScopes[i]);
580 scopes.add(userRole.getScope());
585 List<JSONObject> resultList = new ArrayList<>();
586 boolean onlyFolders = params.getBoolean("onlyFolders");
587 String path = params.getString("path");
588 if(path.contains("..xml")){
589 path = path.replaceAll("..xml", "").trim();
592 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
593 if(scopes.isEmpty()){
594 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
596 if(!"/".equals(path)){
597 String tempScope = path.substring(1, path.length());
598 tempScope = tempScope.replace("/", File.separator);
599 scopes.add(tempScope);
604 if("/".equals(path)){
605 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
606 List<Object> scopesList = queryPolicyEditorScopes(null);
607 for(Object list : scopesList){
608 PolicyEditorScopes scope = (PolicyEditorScopes) list;
609 if(!(scope.getScopeName().contains(File.separator))){
610 JSONObject el = new JSONObject();
611 el.put("name", scope.getScopeName());
612 el.put("date", scope.getCreatedDate());
614 el.put("type", "dir");
615 el.put("createdBy", scope.getUserCreatedBy().getUserName());
616 el.put("modifiedBy", scope.getUserModifiedBy().getUserName());
620 }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){
621 for(Object scope : scopes){
622 JSONObject el = new JSONObject();
623 List<Object> scopesList = queryPolicyEditorScopes(scope.toString());
624 if(!scopesList.isEmpty()){
625 PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
626 el.put("name", scopeById.getScopeName());
627 el.put("date", scopeById.getCreatedDate());
629 el.put("type", "dir");
630 el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
631 el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
638 String scopeName = path.substring(path.indexOf("/") +1);
639 activePolicyList(scopeName, resultList, roles, scopes, onlyFolders);
640 } catch (Exception ex) {
641 LOGGER.error("Error Occured While reading Policy Files List"+ex );
645 return new JSONObject().put(RESULT, resultList);
646 } catch (Exception e) {
647 LOGGER.error("list", e);
648 return error(e.getMessage());
652 private List<Object> queryPolicyEditorScopes(String scopeName){
653 String scopeNamequery = "";
654 if(scopeName == null){
655 scopeNamequery = "from PolicyEditorScopes";
657 scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"%'";
659 PolicyController controller = getPolicyControllerInstance();
660 List<Object> scopesList = controller.getDataByQuery(scopeNamequery);
664 //Get Active Policy List based on Scope Selection form Policy Version table
665 private void activePolicyList(String scopeName, List<JSONObject> resultList, List<String> roles, Set<String> scopes, boolean onlyFolders){
666 PolicyController controller = getPolicyControllerInstance();
667 if(scopeName.contains("/")){
668 scopeName = scopeName.replace("/", File.separator);
670 if(scopeName.contains("\\")){
671 scopeName = scopeName.replace("\\", "\\\\\\\\");
673 String query = "from PolicyVersion where POLICY_NAME like '" +scopeName+"%'";
674 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like '" +scopeName+"%'";
675 List<Object> activePolicies = controller.getDataByQuery(query);
676 List<Object> scopesList = controller.getDataByQuery(scopeNamequery);
677 for(Object list : scopesList){
678 PolicyEditorScopes scopeById = (PolicyEditorScopes) list;
679 String scope = scopeById.getScopeName();
680 if(scope.contains(File.separator)){
681 String checkScope = scope.substring(0, scope.lastIndexOf(File.separator));
682 if(scopeName.contains("\\\\")){
683 scopeName = scopeName.replace("\\\\", File.separator);
685 if(scope.contains(File.separator)){
686 scope = scope.substring(checkScope.length()+1);
687 if(scope.contains(File.separator)){
688 scope = scope.substring(0, scope.indexOf(File.separator));
691 if(scopeName.equalsIgnoreCase(checkScope)){
692 JSONObject el = new JSONObject();
693 el.put("name", scope);
694 el.put("date", scopeById.getModifiedDate());
696 el.put("type", "dir");
697 el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
698 el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
703 String scopeNameCheck = null;
704 for (Object list : activePolicies) {
705 PolicyVersion policy = (PolicyVersion) list;
706 String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator));
707 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
708 if((scopeName.contains("\\\\"))){
709 scopeNameCheck = scopeName.replace("\\\\", File.separator);
711 scopeNameCheck = scopeName;
713 if(scopeNameValue.equals(scopeNameCheck)){
714 JSONObject el = new JSONObject();
715 el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
716 el.put("date", policy.getModifiedDate());
717 el.put("version", policy.getActiveVersion());
719 el.put("type", "file");
720 el.put("createdBy", getUserName(policy.getCreatedBy()));
721 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
724 }else if(!scopes.isEmpty()){
725 if(scopes.contains(scopeNameValue)){
726 JSONObject el = new JSONObject();
727 el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
728 el.put("date", policy.getModifiedDate());
729 el.put("version", policy.getActiveVersion());
731 el.put("type", "file");
732 el.put("createdBy", getUserName(policy.getCreatedBy()));
733 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
740 private String getUserName(String loginId){
741 PolicyController controller = getPolicyControllerInstance();
742 UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
743 if(userInfo == null){
746 return userInfo.getUserName();
750 private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
752 boolean isActive = false;
753 List<String> policyActiveInPDP = new ArrayList<>();
754 Set<String> scopeOfPolicyActiveInPDP = new HashSet<>();
755 String userId = UserUtils.getUserSession(request).getOrgUserId();
756 String oldPath = params.getString("path");
757 String newPath = params.getString("newPath");
758 oldPath = oldPath.substring(oldPath.indexOf("/")+1);
759 newPath = newPath.substring(newPath.indexOf("/")+1);
760 if(oldPath.endsWith(".xml")){
761 JSONObject result = policyRename(oldPath, newPath, userId);
762 if(!(Boolean)(result.getJSONObject("result").get("success"))){
766 String scopeName = oldPath;
767 String newScopeName = newPath;
768 if(scopeName.contains("/")){
769 scopeName = scopeName.replace("/", File.separator);
770 newScopeName = newScopeName.replace("/", File.separator);
772 if(scopeName.contains("\\")){
773 scopeName = scopeName.replace("\\", "\\\\\\\\");
774 newScopeName = newScopeName.replace("\\", "\\\\\\\\");
776 PolicyController controller = getPolicyControllerInstance();
777 String query = "from PolicyVersion where POLICY_NAME like'" +scopeName+"%'";
778 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"%'";
779 List<Object> activePolicies = controller.getDataByQuery(query);
780 List<Object> scopesList = controller.getDataByQuery(scopeNamequery);
781 for(Object object : activePolicies){
782 PolicyVersion activeVersion = (PolicyVersion) object;
783 String policyOldPath = activeVersion.getPolicyName().replace(File.separator, "/") + "." + activeVersion.getActiveVersion() + ".xml";
784 String policyNewPath = policyOldPath.replace(oldPath, newPath);
785 JSONObject result = policyRename(policyOldPath, policyNewPath, userId);
786 if(!(Boolean)(result.getJSONObject("result").get("success"))){
788 policyActiveInPDP.add(policyOldPath);
789 String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf("/"));
790 scopeOfPolicyActiveInPDP.add(scope.replace("/", File.separator));
793 boolean rename = false;
794 if(activePolicies.size() != policyActiveInPDP.size()){
798 UserInfo userInfo = new UserInfo();
799 userInfo.setUserLoginId(userId);
800 if(policyActiveInPDP.size() == 0){
801 renameScope(scopesList, scopeName, newScopeName, controller);
803 renameScope(scopesList, scopeName, newScopeName, controller);
804 for(String scope : scopeOfPolicyActiveInPDP){
805 PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes();
806 editorScopeEntity.setScopeName(scope.replace("\\", "\\\\\\\\"));
807 editorScopeEntity.setUserCreatedBy(userInfo);
808 editorScopeEntity.setUserModifiedBy(userInfo);
809 controller.saveData(editorScopeEntity);
813 return error("The Following policies rename failed. Since they are active in PDP Groups" +policyActiveInPDP);
817 } catch (Exception e) {
818 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
819 return error(e.getMessage());
823 private void renameScope(List<Object> scopesList, String scopeName, String newScopeName, PolicyController controller){
824 for(Object object : scopesList){
825 PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object;
826 if(scopeName.contains("\\\\\\\\")){
827 scopeName = scopeName.replace("\\\\\\\\", File.separator);
828 newScopeName = newScopeName.replace("\\\\\\\\", File.separator);
830 String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName);
831 editorScopeEntity.setScopeName(scope);
832 controller.updateData(editorScopeEntity);
836 private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
838 PolicyEntity entity = null;
839 PolicyController controller = getPolicyControllerInstance();
841 String policyVersionName = newPath.replace(".xml", "");
842 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")).replace("/", File.separator);
844 String oldpolicyVersionName = oldPath.replace(".xml", "");
845 String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf(".")).replace("/", File.separator);
847 String newpolicyName = newPath.replace("/", ".");
848 String newPolicyCheck = newpolicyName;
849 if(newPolicyCheck.contains("Config_")){
850 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
851 }else if(newPolicyCheck.contains("Action_")){
852 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
853 }else if(newPolicyCheck.contains("Decision_")){
854 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
856 String[] newPolicySplit = newPolicyCheck.split(":");
858 String orignalPolicyName = oldPath.replace("/", ".");
859 String oldPolicyCheck = orignalPolicyName;
860 if(oldPolicyCheck.contains("Config_")){
861 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
862 }else if(oldPolicyCheck.contains("Action_")){
863 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
864 }else if(oldPolicyCheck.contains("Decision_")){
865 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
867 String[] oldPolicySplit = oldPolicyCheck.split(":");
869 //Check PolicyEntity table with newPolicy Name
870 String policyEntityquery = "FROM PolicyEntity where policyName = '"+newPolicySplit[1]+"' and scope ='"+newPolicySplit[0]+"'";
871 List<Object> queryData = controller.getDataByQuery(policyEntityquery);
872 if(!queryData.isEmpty()){
873 entity = (PolicyEntity) queryData.get(0);
874 return error("Policy rename failed. Since, the policy with same name already exists.");
877 //Query the Policy Entity with oldPolicy Name
878 String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf("."));
879 String oldpolicyEntityquery = "FROM PolicyEntity where policyName like '"+policyEntityCheck+"%' and scope ='"+oldPolicySplit[0]+"'";
880 List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery);
881 if(!oldEntityData.isEmpty()){
882 String groupQuery = "FROM PolicyGroupEntity where (";
883 for(int i=0; i<oldEntityData.size(); i++){
884 entity = (PolicyEntity) oldEntityData.get(i);
886 groupQuery = groupQuery + "policyid =" + entity.getPolicyId();
888 groupQuery = groupQuery + " or policyid =" + entity.getPolicyId();
891 groupQuery = groupQuery + ")";
892 List<Object> groupEntityData = controller.getDataByQuery(groupQuery);
893 if(groupEntityData.size() > 0){
894 return error("Policy rename failed. Since the policy or its version is active in PDP Groups.");
896 for(int i=0; i<oldEntityData.size(); i++){
897 entity = (PolicyEntity) oldEntityData.get(i);
898 checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0] , newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
901 return error("Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin.");
905 } catch (Exception e) {
906 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
907 return error(e.getMessage());
911 private JSONObject checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, String oldScope, String removeoldPolicyExtension,
912 String policyName, String newpolicyName, String oldpolicyName, String userId) throws ServletException{
914 ConfigurationDataEntity configEntity = entity.getConfigurationData();
915 ActionBodyEntity actionEntity = entity.getActionBodyEntity();
916 PolicyController controller = getPolicyControllerInstance();
918 String oldPolicyNameWithoutExtension = removeoldPolicyExtension;
919 String newPolicyNameWithoutExtension = removenewPolicyExtension;
920 if(removeoldPolicyExtension.endsWith(".xml")){
921 oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf("."));
922 newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf("."));
924 entity.setPolicyName(entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
925 entity.setPolicyData(entity.getPolicyData().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
926 entity.setScope(newScope);
927 entity.setModifiedBy(userId);
928 if(newpolicyName.contains("Config_")){
929 String oldConfigurationName = configEntity.getConfigurationName();
930 configEntity.setConfigurationName(configEntity.getConfigurationName().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
931 controller.updateData(configEntity);
932 String newConfigurationName = configEntity.getConfigurationName();
933 File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName);
935 File renamefile = new File(PolicyController.getConfigHome() + File.separator + newConfigurationName);
936 file.renameTo(renamefile);
938 }else if(newpolicyName.contains("Action_")){
939 String oldConfigurationName = actionEntity.getActionBodyName();
940 actionEntity.setActionBody(actionEntity.getActionBody().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
941 controller.updateData(actionEntity);
942 String newConfigurationName = actionEntity.getActionBodyName();
943 File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName);
945 File renamefile = new File(PolicyController.getActionHome() + File.separator + newConfigurationName);
946 file.renameTo(renamefile);
949 controller.updateData(entity);
951 PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldpolicyName);
952 versionEntity.setPolicyName(policyName);
953 versionEntity.setModifiedBy(userId);
954 controller.updateData(versionEntity);
955 String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator)+1);
956 String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
957 if(movePolicyCheck.equals(moveOldPolicyCheck)){
958 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move");
960 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename");
963 } catch (Exception e) {
964 LOGGER.error("Exception Occured"+e);
965 return error(e.getMessage());
969 private JSONObject cloneRecord(String newpolicyName, String oldScope, String removeoldPolicyExtension, String newScope, String removenewPolicyExtension, PolicyEntity entity, String userId) throws ServletException{
970 FileWriter fw = null;
971 String queryEntityName = null;
972 PolicyController controller = getPolicyControllerInstance();
973 PolicyEntity cloneEntity = new PolicyEntity();
974 cloneEntity.setPolicyName(newpolicyName);
975 removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
976 removenewPolicyExtension = removenewPolicyExtension.replace(".xml", "");
977 cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope+"."+removeoldPolicyExtension, newScope+"."+removenewPolicyExtension));
978 cloneEntity.setScope(entity.getScope());
979 String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
980 String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
981 if(newpolicyName.contains("Config_")){
982 ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
983 configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
984 queryEntityName = configurationDataEntity.getConfigurationName();
985 configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody());
986 configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType());
987 configurationDataEntity.setDeleted(false);
988 configurationDataEntity.setCreatedBy(userId);
989 configurationDataEntity.setModifiedBy(userId);
990 controller.saveData(configurationDataEntity);
991 ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
992 cloneEntity.setConfigurationData(configEntiy);
993 String newConfigurationName = configEntiy.getConfigurationName();
995 fw = new FileWriter(PolicyController.getConfigHome() + File.separator + newConfigurationName);
996 BufferedWriter bw = new BufferedWriter(fw);
997 bw.write(configEntiy.getConfigBody());
999 } catch (IOException e) {
1000 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1002 }else if(newpolicyName.contains("Action_")){
1003 ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
1004 actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1005 queryEntityName = actionBodyEntity.getActionBodyName();
1006 actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody());
1007 actionBodyEntity.setDeleted(false);
1008 actionBodyEntity.setCreatedBy(userId);
1009 actionBodyEntity.setModifiedBy(userId);
1010 controller.saveData(actionBodyEntity);
1011 ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class, "actionBodyName", queryEntityName);
1012 cloneEntity.setActionBodyEntity(actionEntiy);
1013 String newConfigurationName = actionEntiy.getActionBodyName();
1015 fw = new FileWriter(PolicyController.getActionHome() + File.separator + newConfigurationName);
1016 BufferedWriter bw = new BufferedWriter(fw);
1017 bw.write(actionEntiy.getActionBody());
1019 } catch (IOException e) {
1020 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1026 } catch (IOException e) {
1027 LOGGER.error("Exception Occured While closing the File input stream"+e);
1030 cloneEntity.setDeleted(entity.isDeleted());
1031 cloneEntity.setCreatedBy(userId);
1032 cloneEntity.setModifiedBy(userId);
1033 controller.saveData(cloneEntity);
1039 private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
1041 String userId = UserUtils.getUserSession(request).getOrgUserId();
1042 String oldPath = params.getString("path");
1043 String newPath = params.getString("newPath");
1044 oldPath = oldPath.substring(oldPath.indexOf("/")+1);
1045 newPath = newPath.substring(newPath.indexOf("/")+1);
1047 String policyVersionName = newPath.replace(".xml", "");
1048 String version = policyVersionName.substring(policyVersionName.indexOf(".")+1);
1049 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")).replace("/", File.separator);
1051 String newpolicyName = newPath.replace("/", ".");
1053 String orignalPolicyName = oldPath.replace("/", ".");
1055 String newPolicyCheck = newpolicyName;
1056 if(newPolicyCheck.contains("Config_")){
1057 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
1058 }else if(newPolicyCheck.contains("Action_")){
1059 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
1060 }else if(newPolicyCheck.contains("Decision_")){
1061 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
1063 String[] newPolicySplit = newPolicyCheck.split(":");
1065 String oldPolicyCheck = orignalPolicyName;
1066 if(oldPolicyCheck.contains("Config_")){
1067 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
1068 }else if(oldPolicyCheck.contains("Action_")){
1069 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
1070 }else if(oldPolicyCheck.contains("Decision_")){
1071 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
1073 String[] oldPolicySplit = oldPolicyCheck.split(":");
1075 PolicyController controller = getPolicyControllerInstance();
1077 PolicyEntity entity = null;
1078 boolean success = false;
1080 //Check PolicyEntity table with newPolicy Name
1081 String policyEntityquery = "FROM PolicyEntity where policyName = '"+newPolicySplit[1]+"' and scope ='"+newPolicySplit[0]+"'";
1082 List<Object> queryData = controller.getDataByQuery(policyEntityquery);
1083 if(!queryData.isEmpty()){
1084 return error("Policy already exists with same name");
1087 //Query the Policy Entity with oldPolicy Name
1088 policyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'";
1089 queryData = controller.getDataByQuery(policyEntityquery);
1090 if(!queryData.isEmpty()){
1091 entity = (PolicyEntity) queryData.get(0);
1094 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId);
1099 PolicyVersion entityItem = new PolicyVersion();
1100 entityItem.setActiveVersion(Integer.parseInt(version));
1101 entityItem.setHigherVersion(Integer.parseInt(version));
1102 entityItem.setPolicyName(policyName);
1103 entityItem.setCreatedBy(userId);
1104 entityItem.setModifiedBy(userId);
1105 controller.saveData(entityItem);
1108 LOGGER.debug("copy from: {} to: {}" + oldPath +newPath);
1111 } catch (Exception e) {
1112 LOGGER.error("copy", e);
1113 return error(e.getMessage());
1117 //Delete Policy or Scope Functionality
1118 private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
1119 PolicyController controller = getPolicyControllerInstance();
1120 PolicyRestController restController = new PolicyRestController();
1121 PolicyEntity policyEntity = null;
1122 String policyNamewithoutExtension;
1124 String userId = UserUtils.getUserSession(request).getOrgUserId();
1125 String deleteVersion = "";
1126 String path = params.getString("path");
1127 LOGGER.debug("delete {}" +path);
1128 if(params.has("deleteVersion")){
1129 deleteVersion = params.getString("deleteVersion");
1131 path = path.substring(path.indexOf("/")+1);
1132 String policyNamewithExtension = path.replace("/", File.separator);
1133 String policyVersionName = policyNamewithExtension.replace(".xml", "");
1135 if(path.endsWith(".xml")){
1136 policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf("."));
1137 policyNamewithoutExtension = policyNamewithoutExtension.replace(File.separator, ".");
1138 String splitPolicyName = null;
1139 if(policyNamewithoutExtension.contains("Config_")){
1140 splitPolicyName = policyNamewithoutExtension.replace(".Config_", ":Config_");
1141 }else if(policyNamewithoutExtension.contains("Action_")){
1142 splitPolicyName = policyNamewithoutExtension.replace(".Action_", ":Action_");
1143 }else if(policyNamewithoutExtension.contains("Decision_")){
1144 splitPolicyName = policyNamewithoutExtension.replace(".Decision_", ":Decision_");
1146 String[] split = splitPolicyName.split(":");
1147 query = "FROM PolicyEntity where policyName like '"+split[1]+"%' and scope ='"+split[0]+"'";
1149 policyNamewithoutExtension = path.replace(File.separator, ".");
1150 query = "FROM PolicyEntity where scope like '"+policyNamewithoutExtension+"%'";
1153 List<Object> policyEntityobjects = controller.getDataByQuery(query);
1154 String activePolicyName = null;
1155 boolean pdpCheck = false;
1156 if(path.endsWith(".xml")){
1157 policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator);
1158 int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf(".")+1));
1159 if("ALL".equals(deleteVersion)){
1160 if(!policyEntityobjects.isEmpty()){
1161 for(Object object : policyEntityobjects){
1162 policyEntity = (PolicyEntity) object;
1163 String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'";
1164 List<Object> groupobject = controller.getDataByQuery(groupEntityquery);
1165 if(!groupobject.isEmpty()){
1167 activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName();
1169 //Delete the entity from Elastic Search Database
1170 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1171 restController.deleteElasticData(searchFileName);
1172 //Delete the entity from Policy Entity table
1173 controller.deleteData(policyEntity);
1174 if(policyNamewithoutExtension.contains("Config_")){
1175 controller.deleteData(policyEntity.getConfigurationData());
1176 }else if(policyNamewithoutExtension.contains("Action_")){
1177 controller.deleteData(policyEntity.getActionBodyEntity());
1182 //Policy Notification
1183 PolicyVersion versionEntity = new PolicyVersion();
1184 versionEntity.setPolicyName(policyNamewithoutExtension);
1185 versionEntity.setModifiedBy(userId);
1186 controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll");
1188 //Delete from policyVersion table
1189 String getActivePDPPolicyVersion = activePolicyName.replace(".xml", "");
1190 getActivePDPPolicyVersion = getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf(".")+1);
1191 String policyVersionQuery = "update PolicyVersion set active_version='"+getActivePDPPolicyVersion+"' , highest_version='"+getActivePDPPolicyVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1192 if(policyVersionQuery != null){
1193 controller.executeQuery(policyVersionQuery);
1195 return error("Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "+activePolicyName);
1197 //No Active Policy in PDP. So, deleting all entries from policyVersion table
1198 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1199 if(policyVersionQuery != null){
1200 controller.executeQuery(policyVersionQuery);
1203 }else if("CURRENT".equals(deleteVersion)){
1204 String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1);
1205 String currentVersionScope = policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator)).replace(File.separator, ".");
1206 query = "FROM PolicyEntity where policyName = '"+currentVersionPolicyName+"' and scope ='"+currentVersionScope+"'";
1207 List<Object> policyEntitys = controller.getDataByQuery(query);
1208 if(!policyEntitys.isEmpty()){
1209 policyEntity = (PolicyEntity) policyEntitys.get(0);
1211 if(policyEntity != null){
1212 String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"' and policyid > 0";
1213 List<Object> groupobject = controller.getDataByQuery(groupEntityquery);
1214 if(groupobject.isEmpty()){
1215 //Delete the entity from Elastic Search Database
1216 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1217 restController.deleteElasticData(searchFileName);
1218 //Delete the entity from Policy Entity table
1219 controller.deleteData(policyEntity);
1220 if(policyNamewithoutExtension.contains("Config_")){
1221 controller.deleteData(policyEntity.getConfigurationData());
1222 }else if(policyNamewithoutExtension.contains("Action_")){
1223 controller.deleteData(policyEntity.getActionBodyEntity());
1227 int highestVersion = 0;
1228 if(!policyEntityobjects.isEmpty()){
1229 for(Object object : policyEntityobjects){
1230 policyEntity = (PolicyEntity) object;
1231 String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
1232 int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf(".")+1));
1233 if(policyEntityVersion > highestVersion){
1234 highestVersion = policyEntityVersion;
1239 //Policy Notification
1240 PolicyVersion entity = new PolicyVersion();
1241 entity.setPolicyName(policyNamewithoutExtension);
1242 entity.setActiveVersion(highestVersion);
1243 entity.setModifiedBy(userId);
1244 controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne");
1246 String updatequery = "update PolicyVersion set active_version='"+highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"'";
1247 controller.executeQuery(updatequery);
1249 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1250 if(policyVersionQuery != null){
1251 controller.executeQuery(policyVersionQuery);
1255 return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'");
1260 List<String> activePoliciesInPDP = new ArrayList<String>();
1261 if(!policyEntityobjects.isEmpty()){
1262 for(Object object : policyEntityobjects){
1263 policyEntity = (PolicyEntity) object;
1264 String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'";
1265 List<Object> groupobject = controller.getDataByQuery(groupEntityquery);
1266 if(!groupobject.isEmpty()){
1268 activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName());
1270 //Delete the entity from Elastic Search Database
1271 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1272 restController.deleteElasticData(searchFileName);
1273 //Delete the entity from Policy Entity table
1274 controller.deleteData(policyEntity);
1275 policyNamewithoutExtension = policyEntity.getPolicyName();
1276 if(policyNamewithoutExtension.contains("Config_")){
1277 controller.deleteData(policyEntity.getConfigurationData());
1278 }else if(policyNamewithoutExtension.contains("Action_")){
1279 controller.deleteData(policyEntity.getActionBodyEntity());
1283 //Delete from policyVersion and policyEditor Scope table
1284 String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1285 controller.executeQuery(policyVersionQuery);
1287 //Policy Notification
1288 PolicyVersion entity = new PolicyVersion();
1289 entity.setPolicyName(path);
1290 entity.setModifiedBy(userId);
1291 controller.watchPolicyFunction(entity, path, "DeleteScope");
1293 //Add Active Policies List to PolicyVersionTable
1294 for(int i =0; i < activePoliciesInPDP.size(); i++){
1295 String activePDPPolicyName = activePoliciesInPDP.get(i).replace(".xml", "");
1296 int activePDPPolicyVersion = Integer.parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf(".")+1));
1297 activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf(".")).replace(".", File.separator);
1298 PolicyVersion insertactivePDPVersion = new PolicyVersion();
1299 insertactivePDPVersion.setPolicyName(activePDPPolicyName);
1300 insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion);
1301 insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion);
1302 insertactivePDPVersion.setCreatedBy(userId);
1303 insertactivePDPVersion.setModifiedBy(userId);
1304 controller.saveData(insertactivePDPVersion);
1307 return error("All the Policies has been deleted in Scope. Except the following list of Policies:"+activePoliciesInPDP);
1309 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1310 controller.executeQuery(policyScopeQuery);
1313 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1314 controller.executeQuery(policyScopeQuery);
1318 } catch (Exception e) {
1319 LOGGER.error("delete", e);
1320 return error(e.getMessage());
1325 private JSONObject editFile(JSONObject params) throws ServletException {
1328 PolicyController controller = getPolicyControllerInstance();
1329 String mode = params.getString("mode");
1330 String path = params.getString("path");
1331 LOGGER.debug("editFile path: {}"+ path);
1333 String domain = path.substring(1, path.lastIndexOf("/"));
1334 domain = domain.replace("/", ".");
1336 path = path.substring(1);
1337 path = path.replace("/", ".");
1338 String dbCheckName = path;
1339 if(dbCheckName.contains("Config_")){
1340 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
1341 }else if(dbCheckName.contains("Action_")){
1342 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
1343 }else if(dbCheckName.contains("Decision_")){
1344 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
1347 String[] split = dbCheckName.split(":");
1348 String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'";
1349 List<Object> queryData = controller.getDataByQuery(query);
1350 PolicyEntity entity = (PolicyEntity) queryData.get(0);
1351 InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
1354 Object policy = XACMLPolicyScanner.readPolicy(stream);
1355 PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
1356 policyAdapter.setData(policy);
1358 if("viewPolicy".equalsIgnoreCase(mode)){
1359 policyAdapter.setReadOnly(true);
1360 policyAdapter.setEditPolicy(false);
1362 policyAdapter.setReadOnly(false);
1363 policyAdapter.setEditPolicy(true);
1365 policyAdapter.setDomain(domain);
1366 policyAdapter.setDomainDir(domain);
1367 policyAdapter.setPolicyData(policy);
1368 String policyName = path.replace(".xml", "");
1369 policyName = policyName.substring(0, policyName.lastIndexOf("."));
1370 policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf(".")+1));
1372 PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance();
1373 setpolicyAdapter.configure(policyAdapter,entity);
1375 policyAdapter.setParentPath(null);
1376 ObjectMapper mapper = new ObjectMapper();
1377 String json = mapper.writeValueAsString(policyAdapter);
1378 JsonNode jsonNode = mapper.readTree(json);
1380 return new JSONObject().put(RESULT, jsonNode);
1381 } catch (Exception e) {
1382 LOGGER.error("editFile", e);
1383 return error(e.getMessage());
1388 private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
1389 PolicyController controller = getPolicyControllerInstance();
1392 String userId = UserUtils.getUserSession(request).getOrgUserId();
1393 String path = params.getString("path");
1395 if(params.has("subScopename")){
1396 if(!params.getString("subScopename").equals("")){
1397 name = params.getString("path").replace("/", File.separator) + File.separator +params.getString("subScopename");
1400 name = params.getString("name");
1402 }catch(Exception e){
1403 name = params.getString("name");
1404 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e);
1406 String validateName;
1407 if(name.contains(File.separator)){
1408 validateName = name.substring(name.lastIndexOf(File.separator)+1);
1410 validateName = name;
1412 if(!name.isEmpty()){
1413 String validate = PolicyUtils.emptyPolicyValidator(validateName);
1414 if(!validate.contains("success")){
1415 return error(validate);
1418 LOGGER.debug("addFolder path: {} name: {}" + path +name);
1419 if(!name.equals("")){
1420 if(name.startsWith(File.separator)){
1421 name = name.substring(1);
1423 PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, "scopeName", name);
1425 UserInfo userInfo = new UserInfo();
1426 userInfo.setUserLoginId(userId);
1427 PolicyEditorScopes newScope = new PolicyEditorScopes();
1428 newScope.setScopeName(name);
1429 newScope.setUserCreatedBy(userInfo);
1430 newScope.setUserModifiedBy(userInfo);
1431 controller.saveData(newScope);
1433 return error("Scope Already Exists");
1437 } catch (Exception e) {
1438 LOGGER.error("addFolder", e);
1439 return error(e.getMessage());
1443 //Return Error Object
1444 private JSONObject error(String msg) throws ServletException {
1446 JSONObject result = new JSONObject();
1447 result.put("success", false);
1448 result.put("error", msg);
1449 return new JSONObject().put(RESULT, result);
1450 } catch (JSONException e) {
1451 throw new ServletException(e);
1455 //Return Success Object
1456 private JSONObject success() throws ServletException {
1458 JSONObject result = new JSONObject();
1459 result.put("success", true);
1460 result.put("error", (Object) null);
1461 return new JSONObject().put(RESULT, result);
1462 } catch (JSONException e) {
1463 throw new ServletException(e);
1467 private PolicyController getPolicyControllerInstance(){
1468 return policyController != null ? getPolicyController() : new PolicyController();
1471 public String getTestUserId() {
1475 public void setTestUserId(String testUserId) {
1476 this.testUserId = testUserId;