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");
357 if(policyList!= null){
358 for(int i = 0; i < policyList.length(); i++){
359 String policyName = policyList.get(i).toString().replace(".xml", "");
360 String version = policyName.substring(policyName.lastIndexOf(".")+1);
361 policyName = policyName.substring(0, policyName.lastIndexOf(".")).replace(".", File.separator);
362 if(policyName.contains("\\")){
363 policyName = policyName.replace("\\", "\\\\");
365 String policyVersionQuery = "From PolicyVersion where policy_name ='"+policyName+"' and active_version = '"+version+"'and id >0";
366 List<Object> activeData = controller.getDataByQuery(policyVersionQuery);
367 if(!activeData.isEmpty()){
368 PolicyVersion policy = (PolicyVersion) activeData.get(0);
369 JSONObject el = new JSONObject();
370 el.put("name", policy.getPolicyName().replace(File.separator, "/"));
371 el.put("date", policy.getModifiedDate());
372 el.put("version", policy.getActiveVersion());
374 el.put("type", "file");
375 el.put("createdBy", getUserName(policy.getCreatedBy()));
376 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
381 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ){
382 policyData = controller.getData(PolicyVersion.class);
384 List<Object> filterdatas = controller.getData(PolicyVersion.class);
385 for(Object filter : filterdatas){
386 PolicyVersion filterdata = (PolicyVersion) filter;
387 String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator));
388 if(scopes.contains(scopeName)){
389 policyData.add(filterdata);
394 if(!policyData.isEmpty()){
395 for(int i =0; i < policyData.size(); i++){
396 PolicyVersion policy = (PolicyVersion) policyData.get(i);
397 JSONObject el = new JSONObject();
398 el.put("name", policy.getPolicyName().replace(File.separator, "/"));
399 el.put("date", policy.getModifiedDate());
400 el.put("version", policy.getActiveVersion());
402 el.put("type", "file");
403 el.put("createdBy", getUserName(policy.getCreatedBy()));
404 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
410 LOGGER.error("Exception occured while reading policy Data from Policy Version table for Policy Search Data"+e);
413 return new JSONObject().put(RESULT, resultList);
416 //Switch Version Functionality
417 private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{
418 String path = params.getString("path");
419 String userId = null;
421 userId = UserUtils.getUserSession(request).getOrgUserId();
422 } catch (Exception e) {
423 LOGGER.error("Exception Occured while reading userid from cookie" +e);
426 String removeExtension = path.replace(".xml", "");
427 if(path.startsWith("/")){
428 policyName = removeExtension.substring(1, removeExtension.lastIndexOf("."));
430 policyName = removeExtension.substring(0, removeExtension.lastIndexOf("."));
433 String activePolicy = null;
434 PolicyController controller = getPolicyControllerInstance();
435 if(params.toString().contains("activeVersion")){
436 String activeVersion = params.getString("activeVersion");
437 String highestVersion = params.get("highestVersion").toString();
438 if(Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)){
439 return error("The Version shouldn't be greater than Highest Value");
441 activePolicy = policyName + "." + activeVersion + ".xml";
442 String dbCheckName = activePolicy.replace("/", ".");
443 if(dbCheckName.contains("Config_")){
444 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
445 }else if(dbCheckName.contains("Action_")){
446 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
447 }else if(dbCheckName.contains("Decision_")){
448 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
450 String[] splitDBCheckName = dbCheckName.split(":");
451 String peQuery = "FROM PolicyEntity where policyName = '"+splitDBCheckName[1]+"' and scope ='"+splitDBCheckName[0]+"'";
452 List<Object> policyEntity = controller.getDataByQuery(peQuery);
453 PolicyEntity pentity = (PolicyEntity) policyEntity.get(0);
454 if(pentity.isDeleted()){
455 return error("The Policy is Not Existing in Workspace");
457 if(policyName.contains("/")){
458 policyName = policyName.replace("/", File.separator);
460 policyName = policyName.substring(policyName.indexOf(File.separator)+1);
461 if(policyName.contains("\\")){
462 policyName = policyName.replace(File.separator, "\\");
464 policyName = splitDBCheckName[0].replace(".", File.separator)+File.separator+policyName;
465 String watchPolicyName = policyName;
466 if(policyName.contains("/")){
467 policyName = policyName.replace("/", File.separator);
469 if(policyName.contains("\\")){
470 policyName = policyName.replace("\\", "\\\\");
472 String query = "update PolicyVersion set active_version='"+activeVersion+"' where policy_name ='"+policyName+"' and id >0";
474 controller.executeQuery(query);
475 //Policy Notification
476 PolicyVersion entity = new PolicyVersion();
477 entity.setPolicyName(watchPolicyName);
478 entity.setActiveVersion(Integer.parseInt(activeVersion));
479 entity.setModifiedBy(userId);
480 controller.watchPolicyFunction(entity, activePolicy, "SwitchVersion");
485 return controller.switchVersionPolicyContent(policyName);
489 private JSONObject describePolicy(JSONObject params) throws ServletException{
490 JSONObject object = null;
491 String path = params.getString("path");
492 String policyName = null;
493 if(path.startsWith("/")){
494 path = path.substring(1);
495 policyName = path.substring(path.lastIndexOf("/") +1);
496 path = path.replace("/", ".");
498 path = path.replace("/", ".");
501 if(path.contains("Config_")){
502 path = path.replace(".Config_", ":Config_");
503 }else if(path.contains("Action_")){
504 path = path.replace(".Action_", ":Action_");
505 }else if(path.contains("Decision_")){
506 path = path.replace(".Decision_", ":Decision_");
508 PolicyController controller = getPolicyControllerInstance();
509 String[] split = path.split(":");
510 String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'";
511 List<Object> queryData = controller.getDataByQuery(query);
512 if(!queryData.isEmpty()){
513 PolicyEntity entity = (PolicyEntity) queryData.get(0);
515 BufferedWriter bw = null;
517 temp = File.createTempFile(policyName, ".tmp");
518 bw = new BufferedWriter(new FileWriter(temp));
519 bw.write(entity.getPolicyData());
521 object = HumanPolicyComponent.DescribePolicy(temp);
522 } catch (IOException e) {
523 LOGGER.error("Exception Occured while Describing the Policy"+e);
531 } catch (IOException e) {
532 LOGGER.error("Exception Occured while Closing the File Writer"+e);
537 return error("Error Occured while Describing the Policy");
543 //Get the List of Policies and Scopes for Showing in Editor tab
544 private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException {
545 Set<String> scopes = null;
546 List<String> roles = null;
548 PolicyController controller = getPolicyControllerInstance();
549 //Get the Login Id of the User from Request
550 String testUserID = getTestUserId();
551 String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId();
552 //Check if the Role and Scope Size are Null get the values from db.
553 List<Object> userRoles = controller.getRoles(userId);
554 roles = new ArrayList<>();
555 scopes = new HashSet<>();
556 for(Object role: userRoles){
557 Roles userRole = (Roles) role;
558 roles.add(userRole.getRole());
559 if(userRole.getScope() != null){
560 if(userRole.getScope().contains(",")){
561 String[] multipleScopes = userRole.getScope().split(",");
562 for(int i =0; i < multipleScopes.length; i++){
563 scopes.add(multipleScopes[i]);
566 scopes.add(userRole.getScope());
570 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
571 if(scopes.isEmpty()){
572 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
576 List<JSONObject> resultList = new ArrayList<>();
577 boolean onlyFolders = params.getBoolean("onlyFolders");
578 String path = params.getString("path");
579 if(path.contains("..xml")){
580 path = path.replaceAll("..xml", "").trim();
584 if("/".equals(path)){
585 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
586 List<Object> scopesList = queryPolicyEditorScopes(null);
587 for(Object list : scopesList){
588 PolicyEditorScopes scope = (PolicyEditorScopes) list;
589 if(!(scope.getScopeName().contains(File.separator))){
590 JSONObject el = new JSONObject();
591 el.put("name", scope.getScopeName());
592 el.put("date", scope.getCreatedDate());
594 el.put("type", "dir");
595 el.put("createdBy", scope.getUserCreatedBy().getUserName());
596 el.put("modifiedBy", scope.getUserModifiedBy().getUserName());
600 }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){
601 for(Object scope : scopes){
602 JSONObject el = new JSONObject();
603 List<Object> scopesList = queryPolicyEditorScopes(scope.toString());
604 PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
605 el.put("name", scopeById.getScopeName());
606 el.put("date", scopeById.getCreatedDate());
608 el.put("type", "dir");
609 el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
610 el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
616 String scopeName = path.substring(path.indexOf("/") +1);
617 activePolicyList(scopeName, resultList, roles, scopes, onlyFolders);
618 } catch (Exception ex) {
619 LOGGER.error("Error Occured While reading Policy Files List"+ex );
623 return new JSONObject().put(RESULT, resultList);
624 } catch (Exception e) {
625 LOGGER.error("list", e);
626 return error(e.getMessage());
630 private List<Object> queryPolicyEditorScopes(String scopeName){
631 String scopeNamequery = "";
632 if(scopeName == null){
633 scopeNamequery = "from PolicyEditorScopes";
635 scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"'";
637 PolicyController controller = getPolicyControllerInstance();
638 List<Object> scopesList = controller.getDataByQuery(scopeNamequery);
642 //Get Active Policy List based on Scope Selection form Policy Version table
643 private void activePolicyList(String scopeName, List<JSONObject> resultList, List<String> roles, Set<String> scopes, boolean onlyFolders){
644 PolicyController controller = getPolicyControllerInstance();
645 if(scopeName.contains("/")){
646 scopeName = scopeName.replace("/", File.separator);
648 if(scopeName.contains("\\")){
649 scopeName = scopeName.replace("\\", "\\\\\\\\");
651 String query = "from PolicyVersion where POLICY_NAME like '" +scopeName+"%'";
652 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like '" +scopeName+"%'";
653 List<Object> activePolicies = controller.getDataByQuery(query);
654 List<Object> scopesList = controller.getDataByQuery(scopeNamequery);
655 for(Object list : scopesList){
656 PolicyEditorScopes scopeById = (PolicyEditorScopes) list;
657 String scope = scopeById.getScopeName();
658 if(scope.contains(File.separator)){
659 String checkScope = scope.substring(0, scope.lastIndexOf(File.separator));
660 if(scopeName.contains("\\\\")){
661 scopeName = scopeName.replace("\\\\", File.separator);
663 if(scope.contains(File.separator)){
664 scope = scope.substring(checkScope.length()+1);
665 if(scope.contains(File.separator)){
666 scope = scope.substring(0, scope.indexOf(File.separator));
669 if(scopeName.equalsIgnoreCase(checkScope)){
670 JSONObject el = new JSONObject();
671 el.put("name", scope);
672 el.put("date", scopeById.getModifiedDate());
674 el.put("type", "dir");
675 el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
676 el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
681 String scopeNameCheck = null;
682 for (Object list : activePolicies) {
683 PolicyVersion policy = (PolicyVersion) list;
684 String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator));
685 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
686 if((scopeName.contains("\\\\"))){
687 scopeNameCheck = scopeName.replace("\\\\", File.separator);
689 scopeNameCheck = scopeName;
691 if(scopeNameValue.equals(scopeNameCheck)){
692 JSONObject el = new JSONObject();
693 el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
694 el.put("date", policy.getModifiedDate());
695 el.put("version", policy.getActiveVersion());
697 el.put("type", "file");
698 el.put("createdBy", getUserName(policy.getCreatedBy()));
699 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
702 }else if(!scopes.isEmpty()){
703 if(scopes.contains(scopeNameValue)){
704 JSONObject el = new JSONObject();
705 el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
706 el.put("date", policy.getModifiedDate());
707 el.put("version", policy.getActiveVersion());
709 el.put("type", "file");
710 el.put("createdBy", getUserName(policy.getCreatedBy()));
711 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
718 private String getUserName(String loginId){
719 PolicyController controller = getPolicyControllerInstance();
720 UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
721 if(userInfo == null){
724 return userInfo.getUserName();
728 private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
730 boolean isActive = false;
731 List<String> policyActiveInPDP = new ArrayList<>();
732 Set<String> scopeOfPolicyActiveInPDP = new HashSet<>();
733 String userId = UserUtils.getUserSession(request).getOrgUserId();
734 String oldPath = params.getString("path");
735 String newPath = params.getString("newPath");
736 oldPath = oldPath.substring(oldPath.indexOf("/")+1);
737 newPath = newPath.substring(newPath.indexOf("/")+1);
738 if(oldPath.endsWith(".xml")){
739 JSONObject result = policyRename(oldPath, newPath, userId);
740 if(!(Boolean)(result.getJSONObject("result").get("success"))){
744 String scopeName = oldPath;
745 String newScopeName = newPath;
746 if(scopeName.contains("/")){
747 scopeName = scopeName.replace("/", File.separator);
748 newScopeName = newScopeName.replace("/", File.separator);
750 if(scopeName.contains("\\")){
751 scopeName = scopeName.replace("\\", "\\\\\\\\");
752 newScopeName = newScopeName.replace("\\", "\\\\\\\\");
754 PolicyController controller = getPolicyControllerInstance();
755 String query = "from PolicyVersion where POLICY_NAME like'" +scopeName+"%'";
756 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"%'";
757 List<Object> activePolicies = controller.getDataByQuery(query);
758 List<Object> scopesList = controller.getDataByQuery(scopeNamequery);
759 for(Object object : activePolicies){
760 PolicyVersion activeVersion = (PolicyVersion) object;
761 String policyOldPath = activeVersion.getPolicyName().replace(File.separator, "/") + "." + activeVersion.getActiveVersion() + ".xml";
762 String policyNewPath = policyOldPath.replace(oldPath, newPath);
763 JSONObject result = policyRename(policyOldPath, policyNewPath, userId);
764 if(!(Boolean)(result.getJSONObject("result").get("success"))){
766 policyActiveInPDP.add(policyOldPath);
767 String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf("/"));
768 scopeOfPolicyActiveInPDP.add(scope.replace("/", File.separator));
771 boolean rename = false;
772 if(activePolicies.size() != policyActiveInPDP.size()){
776 UserInfo userInfo = new UserInfo();
777 userInfo.setUserLoginId(userId);
778 if(policyActiveInPDP.size() == 0){
779 renameScope(scopesList, scopeName, newScopeName, controller);
781 renameScope(scopesList, scopeName, newScopeName, controller);
782 for(String scope : scopeOfPolicyActiveInPDP){
783 PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes();
784 editorScopeEntity.setScopeName(scope.replace("\\", "\\\\\\\\"));
785 editorScopeEntity.setUserCreatedBy(userInfo);
786 editorScopeEntity.setUserModifiedBy(userInfo);
787 controller.saveData(editorScopeEntity);
791 return error("The Following policies rename failed. Since they are active in PDP Groups" +policyActiveInPDP);
795 } catch (Exception e) {
796 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
797 return error(e.getMessage());
801 private void renameScope(List<Object> scopesList, String scopeName, String newScopeName, PolicyController controller){
802 for(Object object : scopesList){
803 PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object;
804 if(scopeName.contains("\\\\\\\\")){
805 scopeName = scopeName.replace("\\\\\\\\", File.separator);
806 newScopeName = newScopeName.replace("\\\\\\\\", File.separator);
808 String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName);
809 editorScopeEntity.setScopeName(scope);
810 controller.updateData(editorScopeEntity);
814 private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
816 PolicyEntity entity = null;
817 PolicyController controller = getPolicyControllerInstance();
819 String policyVersionName = newPath.replace(".xml", "");
820 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")).replace("/", File.separator);
822 String oldpolicyVersionName = oldPath.replace(".xml", "");
823 String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf(".")).replace("/", File.separator);
825 String newpolicyName = newPath.replace("/", ".");
826 String newPolicyCheck = newpolicyName;
827 if(newPolicyCheck.contains("Config_")){
828 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
829 }else if(newPolicyCheck.contains("Action_")){
830 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
831 }else if(newPolicyCheck.contains("Decision_")){
832 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
834 String[] newPolicySplit = newPolicyCheck.split(":");
836 String orignalPolicyName = oldPath.replace("/", ".");
837 String oldPolicyCheck = orignalPolicyName;
838 if(oldPolicyCheck.contains("Config_")){
839 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
840 }else if(oldPolicyCheck.contains("Action_")){
841 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
842 }else if(oldPolicyCheck.contains("Decision_")){
843 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
845 String[] oldPolicySplit = oldPolicyCheck.split(":");
847 //Check PolicyEntity table with newPolicy Name
848 String policyEntityquery = "FROM PolicyEntity where policyName = '"+newPolicySplit[1]+"' and scope ='"+newPolicySplit[0]+"'";
849 List<Object> queryData = controller.getDataByQuery(policyEntityquery);
850 if(!queryData.isEmpty()){
851 entity = (PolicyEntity) queryData.get(0);
852 return error("Policy rename failed. Since, the policy with same name already exists.");
855 //Query the Policy Entity with oldPolicy Name
856 String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf("."));
857 String oldpolicyEntityquery = "FROM PolicyEntity where policyName like '"+policyEntityCheck+"%' and scope ='"+oldPolicySplit[0]+"'";
858 List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery);
859 if(!oldEntityData.isEmpty()){
860 String groupQuery = "FROM PolicyGroupEntity where (";
861 for(int i=0; i<oldEntityData.size(); i++){
862 entity = (PolicyEntity) oldEntityData.get(i);
864 groupQuery = groupQuery + "policyid =" + entity.getPolicyId();
866 groupQuery = groupQuery + " or policyid =" + entity.getPolicyId();
869 groupQuery = groupQuery + ")";
870 List<Object> groupEntityData = controller.getDataByQuery(groupQuery);
871 if(groupEntityData.size() > 0){
872 return error("Policy rename failed. Since the policy or its version is active in PDP Groups.");
874 for(int i=0; i<oldEntityData.size(); i++){
875 entity = (PolicyEntity) oldEntityData.get(i);
876 checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0] , newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
879 return error("Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin.");
883 } catch (Exception e) {
884 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
885 return error(e.getMessage());
889 private JSONObject checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, String oldScope, String removeoldPolicyExtension,
890 String policyName, String newpolicyName, String oldpolicyName, String userId) throws ServletException{
892 ConfigurationDataEntity configEntity = entity.getConfigurationData();
893 ActionBodyEntity actionEntity = entity.getActionBodyEntity();
894 PolicyController controller = getPolicyControllerInstance();
896 String oldPolicyNameWithoutExtension = removeoldPolicyExtension;
897 String newPolicyNameWithoutExtension = removenewPolicyExtension;
898 if(removeoldPolicyExtension.endsWith(".xml")){
899 oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf("."));
900 newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf("."));
902 entity.setPolicyName(entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
903 entity.setPolicyData(entity.getPolicyData().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
904 entity.setScope(newScope);
905 entity.setModifiedBy(userId);
906 if(newpolicyName.contains("Config_")){
907 String oldConfigurationName = configEntity.getConfigurationName();
908 configEntity.setConfigurationName(configEntity.getConfigurationName().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
909 controller.updateData(configEntity);
910 String newConfigurationName = configEntity.getConfigurationName();
911 File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName);
913 File renamefile = new File(PolicyController.getConfigHome() + File.separator + newConfigurationName);
914 file.renameTo(renamefile);
916 }else if(newpolicyName.contains("Action_")){
917 String oldConfigurationName = actionEntity.getActionBodyName();
918 actionEntity.setActionBody(actionEntity.getActionBody().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
919 controller.updateData(actionEntity);
920 String newConfigurationName = actionEntity.getActionBodyName();
921 File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName);
923 File renamefile = new File(PolicyController.getActionHome() + File.separator + newConfigurationName);
924 file.renameTo(renamefile);
927 controller.updateData(entity);
929 PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldpolicyName);
930 versionEntity.setPolicyName(policyName);
931 versionEntity.setModifiedBy(userId);
932 controller.updateData(versionEntity);
933 String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator)+1);
934 String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
935 if(movePolicyCheck.equals(moveOldPolicyCheck)){
936 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move");
938 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename");
941 } catch (Exception e) {
942 LOGGER.error("Exception Occured"+e);
943 return error(e.getMessage());
947 private JSONObject cloneRecord(String newpolicyName, String oldScope, String removeoldPolicyExtension, String newScope, String removenewPolicyExtension, PolicyEntity entity, String userId) throws ServletException{
948 String queryEntityName = null;
949 PolicyController controller = getPolicyControllerInstance();
950 PolicyEntity cloneEntity = new PolicyEntity();
951 cloneEntity.setPolicyName(newpolicyName);
952 removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
953 removenewPolicyExtension = removenewPolicyExtension.replace(".xml", "");
954 cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope+"."+removeoldPolicyExtension, newScope+"."+removenewPolicyExtension));
955 cloneEntity.setScope(entity.getScope());
956 String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
957 String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
958 if(newpolicyName.contains("Config_")){
959 ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
960 configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
961 queryEntityName = configurationDataEntity.getConfigurationName();
962 configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody());
963 configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType());
964 configurationDataEntity.setDeleted(false);
965 configurationDataEntity.setCreatedBy(userId);
966 configurationDataEntity.setModifiedBy(userId);
967 controller.saveData(configurationDataEntity);
968 ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
969 cloneEntity.setConfigurationData(configEntiy);
970 }else if(newpolicyName.contains("Action_")){
971 ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
972 actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
973 queryEntityName = actionBodyEntity.getActionBodyName();
974 actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody());
975 actionBodyEntity.setDeleted(false);
976 actionBodyEntity.setCreatedBy(userId);
977 actionBodyEntity.setModifiedBy(userId);
978 controller.saveData(actionBodyEntity);
979 ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class, "actionBodyName", queryEntityName);
980 cloneEntity.setActionBodyEntity(actionEntiy);
982 cloneEntity.setDeleted(entity.isDeleted());
983 cloneEntity.setCreatedBy(userId);
984 cloneEntity.setModifiedBy(userId);
985 controller.saveData(cloneEntity);
991 private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
993 String userId = UserUtils.getUserSession(request).getOrgUserId();
994 String oldPath = params.getString("path");
995 String newPath = params.getString("newPath");
996 oldPath = oldPath.substring(oldPath.indexOf("/")+1);
997 newPath = newPath.substring(newPath.indexOf("/")+1);
999 String policyVersionName = newPath.replace(".xml", "");
1000 String version = policyVersionName.substring(policyVersionName.indexOf(".")+1);
1001 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")).replace("/", File.separator);
1003 String newpolicyName = newPath.replace("/", ".");
1005 String orignalPolicyName = oldPath.replace("/", ".");
1007 String newPolicyCheck = newpolicyName;
1008 if(newPolicyCheck.contains("Config_")){
1009 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
1010 }else if(newPolicyCheck.contains("Action_")){
1011 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
1012 }else if(newPolicyCheck.contains("Decision_")){
1013 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
1015 String[] newPolicySplit = newPolicyCheck.split(":");
1017 String oldPolicyCheck = orignalPolicyName;
1018 if(oldPolicyCheck.contains("Config_")){
1019 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
1020 }else if(oldPolicyCheck.contains("Action_")){
1021 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
1022 }else if(oldPolicyCheck.contains("Decision_")){
1023 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
1025 String[] oldPolicySplit = oldPolicyCheck.split(":");
1027 PolicyController controller = getPolicyControllerInstance();
1029 PolicyEntity entity = null;
1030 boolean success = false;
1032 //Check PolicyEntity table with newPolicy Name
1033 String policyEntityquery = "FROM PolicyEntity where policyName = '"+newPolicySplit[1]+"' and scope ='"+newPolicySplit[0]+"'";
1034 List<Object> queryData = controller.getDataByQuery(policyEntityquery);
1035 if(!queryData.isEmpty()){
1036 entity = (PolicyEntity) queryData.get(0);
1039 //if a policy exists with new name check if it is deleted or not
1040 if(entity.isDeleted()){
1041 //Check Policy Group Entity table if policy has been pushed or not
1042 String query = "from PolicyGroupEntity where policyid = '"+entity.getPolicyId()+"'";
1043 List<Object> object = controller.getDataByQuery(query);
1045 //if PolicyGroupEntity data is empty delete the entry from database
1046 controller.deleteData(entity);
1047 //Query the Policy Entity with oldPolicy Name
1048 policyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'";
1049 queryData = controller.getDataByQuery(policyEntityquery);
1050 if(!queryData.isEmpty()){
1051 entity = (PolicyEntity) queryData.get(0);
1054 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId);
1058 return error("Policy Clone failed due to policy with new name existing in PDP Group.");
1061 return error("Policy Clone failed due to same name existing.");
1064 //Query the Policy Entity with oldPolicy Name
1065 policyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'";
1066 queryData = controller.getDataByQuery(policyEntityquery);
1067 if(!queryData.isEmpty()){
1068 entity = (PolicyEntity) queryData.get(0);
1071 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId);
1076 PolicyVersion entityItem = new PolicyVersion();
1077 entityItem.setActiveVersion(Integer.parseInt(version));
1078 entityItem.setHigherVersion(Integer.parseInt(version));
1079 entityItem.setPolicyName(policyName);
1080 entityItem.setCreatedBy(userId);
1081 entityItem.setModifiedBy(userId);
1082 controller.saveData(entityItem);
1085 LOGGER.debug("copy from: {} to: {}" + oldPath +newPath);
1088 } catch (Exception e) {
1089 LOGGER.error("copy", e);
1090 return error(e.getMessage());
1094 //Delete Policy or Scope Functionality
1095 private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
1096 PolicyController controller = getPolicyControllerInstance();
1097 PolicyRestController restController = new PolicyRestController();
1098 PolicyEntity policyEntity = null;
1099 String policyNamewithoutExtension;
1101 String userId = UserUtils.getUserSession(request).getOrgUserId();
1102 String deleteVersion = "";
1103 String path = params.getString("path");
1104 LOGGER.debug("delete {}" +path);
1105 if(params.has("deleteVersion")){
1106 deleteVersion = params.getString("deleteVersion");
1108 path = path.substring(path.indexOf("/")+1);
1109 String policyNamewithExtension = path.replace("/", File.separator);
1110 String policyVersionName = policyNamewithExtension.replace(".xml", "");
1112 if(path.endsWith(".xml")){
1113 policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf("."));
1114 policyNamewithoutExtension = policyNamewithoutExtension.replace(File.separator, ".");
1115 String splitPolicyName = null;
1116 if(policyNamewithoutExtension.contains("Config_")){
1117 splitPolicyName = policyNamewithoutExtension.replace(".Config_", ":Config_");
1118 }else if(policyNamewithoutExtension.contains("Action_")){
1119 splitPolicyName = policyNamewithoutExtension.replace(".Action_", ":Action_");
1120 }else if(policyNamewithoutExtension.contains("Decision_")){
1121 splitPolicyName = policyNamewithoutExtension.replace(".Decision_", ":Decision_");
1123 String[] split = splitPolicyName.split(":");
1124 query = "FROM PolicyEntity where policyName like '"+split[1]+"%' and scope ='"+split[0]+"'";
1126 policyNamewithoutExtension = path.replace(File.separator, ".");
1127 query = "FROM PolicyEntity where scope like '"+policyNamewithoutExtension+"%'";
1130 List<Object> policyEntityobjects = controller.getDataByQuery(query);
1131 String activePolicyName = null;
1132 boolean pdpCheck = false;
1133 if(path.endsWith(".xml")){
1134 policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator);
1135 int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf(".")+1));
1136 if("ALL".equals(deleteVersion)){
1137 if(!policyEntityobjects.isEmpty()){
1138 for(Object object : policyEntityobjects){
1139 policyEntity = (PolicyEntity) object;
1140 String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'";
1141 List<Object> groupobject = controller.getDataByQuery(groupEntityquery);
1142 if(!groupobject.isEmpty()){
1144 activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName();
1146 //Delete the entity from Elastic Search Database
1147 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1148 restController.deleteElasticData(searchFileName);
1149 //Delete the entity from Policy Entity table
1150 controller.deleteData(policyEntity);
1151 if(policyNamewithoutExtension.contains("Config_")){
1152 controller.deleteData(policyEntity.getConfigurationData());
1153 }else if(policyNamewithoutExtension.contains("Action_")){
1154 controller.deleteData(policyEntity.getActionBodyEntity());
1159 //Policy Notification
1160 PolicyVersion versionEntity = new PolicyVersion();
1161 versionEntity.setPolicyName(policyNamewithoutExtension);
1162 versionEntity.setModifiedBy(userId);
1163 controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll");
1165 //Delete from policyVersion table
1166 String getActivePDPPolicyVersion = activePolicyName.replace(".xml", "");
1167 getActivePDPPolicyVersion = getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf(".")+1);
1168 String policyVersionQuery = "update PolicyVersion set active_version='"+getActivePDPPolicyVersion+"' , highest_version='"+getActivePDPPolicyVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1169 if(policyVersionQuery != null){
1170 controller.executeQuery(policyVersionQuery);
1172 return error("Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "+activePolicyName);
1174 //No Active Policy in PDP. So, deleting all entries from policyVersion table
1175 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1176 if(policyVersionQuery != null){
1177 controller.executeQuery(policyVersionQuery);
1180 }else if("CURRENT".equals(deleteVersion)){
1181 String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1);
1182 String currentVersionScope = policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator)).replace(File.separator, ".");
1183 query = "FROM PolicyEntity where policyName = '"+currentVersionPolicyName+"' and scope ='"+currentVersionScope+"'";
1184 List<Object> policyEntitys = controller.getDataByQuery(query);
1185 if(!policyEntitys.isEmpty()){
1186 policyEntity = (PolicyEntity) policyEntitys.get(0);
1188 if(policyEntity != null){
1189 String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"' and policyid > 0";
1190 List<Object> groupobject = controller.getDataByQuery(groupEntityquery);
1191 if(groupobject.isEmpty()){
1192 //Delete the entity from Elastic Search Database
1193 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1194 restController.deleteElasticData(searchFileName);
1195 //Delete the entity from Policy Entity table
1196 controller.deleteData(policyEntity);
1197 if(policyNamewithoutExtension.contains("Config_")){
1198 controller.deleteData(policyEntity.getConfigurationData());
1199 }else if(policyNamewithoutExtension.contains("Action_")){
1200 controller.deleteData(policyEntity.getActionBodyEntity());
1204 int highestVersion = 0;
1205 if(!policyEntityobjects.isEmpty()){
1206 for(Object object : policyEntityobjects){
1207 policyEntity = (PolicyEntity) object;
1208 String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
1209 int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf(".")+1));
1210 if(policyEntityVersion > highestVersion){
1211 highestVersion = policyEntityVersion;
1216 //Policy Notification
1217 PolicyVersion entity = new PolicyVersion();
1218 entity.setPolicyName(policyNamewithoutExtension);
1219 entity.setActiveVersion(highestVersion);
1220 entity.setModifiedBy(userId);
1221 controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne");
1223 String updatequery = "update PolicyVersion set active_version='"+highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"'";
1224 controller.executeQuery(updatequery);
1226 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1227 if(policyVersionQuery != null){
1228 controller.executeQuery(policyVersionQuery);
1232 return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'");
1237 List<String> activePoliciesInPDP = new ArrayList<String>();
1238 if(!policyEntityobjects.isEmpty()){
1239 for(Object object : policyEntityobjects){
1240 policyEntity = (PolicyEntity) object;
1241 String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'";
1242 List<Object> groupobject = controller.getDataByQuery(groupEntityquery);
1243 if(!groupobject.isEmpty()){
1245 activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName());
1247 //Delete the entity from Elastic Search Database
1248 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1249 restController.deleteElasticData(searchFileName);
1250 //Delete the entity from Policy Entity table
1251 controller.deleteData(policyEntity);
1252 policyNamewithoutExtension = policyEntity.getPolicyName();
1253 if(policyNamewithoutExtension.contains("Config_")){
1254 controller.deleteData(policyEntity.getConfigurationData());
1255 }else if(policyNamewithoutExtension.contains("Action_")){
1256 controller.deleteData(policyEntity.getActionBodyEntity());
1260 //Delete from policyVersion and policyEditor Scope table
1261 String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1262 controller.executeQuery(policyVersionQuery);
1264 //Policy Notification
1265 PolicyVersion entity = new PolicyVersion();
1266 entity.setPolicyName(path);
1267 entity.setModifiedBy(userId);
1268 controller.watchPolicyFunction(entity, path, "DeleteScope");
1270 //Add Active Policies List to PolicyVersionTable
1271 for(int i =0; i < activePoliciesInPDP.size(); i++){
1272 String activePDPPolicyName = activePoliciesInPDP.get(i).replace(".xml", "");
1273 int activePDPPolicyVersion = Integer.parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf(".")+1));
1274 activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf(".")).replace(".", File.separator);
1275 PolicyVersion insertactivePDPVersion = new PolicyVersion();
1276 insertactivePDPVersion.setPolicyName(activePDPPolicyName);
1277 insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion);
1278 insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion);
1279 insertactivePDPVersion.setCreatedBy(userId);
1280 insertactivePDPVersion.setModifiedBy(userId);
1281 controller.saveData(insertactivePDPVersion);
1284 return error("All the Policies has been deleted in Scope. Except the following list of Policies:"+activePoliciesInPDP);
1286 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1287 controller.executeQuery(policyScopeQuery);
1290 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1291 controller.executeQuery(policyScopeQuery);
1295 } catch (Exception e) {
1296 LOGGER.error("delete", e);
1297 return error(e.getMessage());
1302 private JSONObject editFile(JSONObject params) throws ServletException {
1305 PolicyController controller = getPolicyControllerInstance();
1306 String mode = params.getString("mode");
1307 String path = params.getString("path");
1308 LOGGER.debug("editFile path: {}"+ path);
1310 String domain = path.substring(1, path.lastIndexOf("/"));
1311 domain = domain.replace("/", ".");
1313 path = path.substring(1);
1314 path = path.replace("/", ".");
1315 String dbCheckName = path;
1316 if(dbCheckName.contains("Config_")){
1317 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
1318 }else if(dbCheckName.contains("Action_")){
1319 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
1320 }else if(dbCheckName.contains("Decision_")){
1321 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
1324 String[] split = dbCheckName.split(":");
1325 String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'";
1326 List<Object> queryData = controller.getDataByQuery(query);
1327 PolicyEntity entity = (PolicyEntity) queryData.get(0);
1328 InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
1331 Object policy = XACMLPolicyScanner.readPolicy(stream);
1332 PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
1333 policyAdapter.setData(policy);
1335 if("viewPolicy".equalsIgnoreCase(mode)){
1336 policyAdapter.setReadOnly(true);
1337 policyAdapter.setEditPolicy(false);
1339 policyAdapter.setReadOnly(false);
1340 policyAdapter.setEditPolicy(true);
1342 policyAdapter.setDomain(domain);
1343 policyAdapter.setDomainDir(domain);
1344 policyAdapter.setPolicyData(policy);
1345 String policyName = path.replace(".xml", "");
1346 policyName = policyName.substring(0, policyName.lastIndexOf("."));
1347 policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf(".")+1));
1349 PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance();
1350 setpolicyAdapter.configure(policyAdapter,entity);
1352 policyAdapter.setParentPath(null);
1353 ObjectMapper mapper = new ObjectMapper();
1354 String json = mapper.writeValueAsString(policyAdapter);
1355 JsonNode jsonNode = mapper.readTree(json);
1357 return new JSONObject().put(RESULT, jsonNode);
1358 } catch (Exception e) {
1359 LOGGER.error("editFile", e);
1360 return error(e.getMessage());
1365 private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
1366 PolicyController controller = getPolicyControllerInstance();
1369 String userId = UserUtils.getUserSession(request).getOrgUserId();
1370 String path = params.getString("path");
1372 if(params.has("subScopename")){
1373 if(!params.getString("subScopename").equals("")){
1374 name = params.getString("path").replace("/", File.separator) + File.separator +params.getString("subScopename");
1377 name = params.getString("name");
1379 }catch(Exception e){
1380 name = params.getString("name");
1381 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e);
1383 String validateName;
1384 if(name.contains(File.separator)){
1385 validateName = name.substring(name.lastIndexOf(File.separator)+1);
1387 validateName = name;
1389 if(!name.isEmpty()){
1390 String validate = PolicyUtils.emptyPolicyValidator(validateName);
1391 if(!validate.contains("success")){
1392 return error(validate);
1395 LOGGER.debug("addFolder path: {} name: {}" + path +name);
1396 if(!name.equals("")){
1397 PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, "scopeName", name);
1399 UserInfo userInfo = new UserInfo();
1400 userInfo.setUserLoginId(userId);
1401 PolicyEditorScopes newScope = new PolicyEditorScopes();
1402 String scopeName = null;
1403 if(name.startsWith(File.separator)){
1404 scopeName = name.substring(1);
1408 newScope.setScopeName(scopeName);
1409 newScope.setUserCreatedBy(userInfo);
1410 newScope.setUserModifiedBy(userInfo);
1411 controller.saveData(newScope);
1413 return error("Scope Already Exists");
1417 } catch (Exception e) {
1418 LOGGER.error("addFolder", e);
1419 return error(e.getMessage());
1423 //Return Error Object
1424 private JSONObject error(String msg) throws ServletException {
1426 JSONObject result = new JSONObject();
1427 result.put("success", false);
1428 result.put("error", msg);
1429 return new JSONObject().put(RESULT, result);
1430 } catch (JSONException e) {
1431 throw new ServletException(e);
1435 //Return Success Object
1436 private JSONObject success() throws ServletException {
1438 JSONObject result = new JSONObject();
1439 result.put("success", true);
1440 result.put("error", (Object) null);
1441 return new JSONObject().put(RESULT, result);
1442 } catch (JSONException e) {
1443 throw new ServletException(e);
1447 private PolicyController getPolicyControllerInstance(){
1448 return policyController != null ? getPolicyController() : new PolicyController();
1451 public String getTestUserId() {
1455 public void setTestUserId(String testUserId) {
1456 this.testUserId = testUserId;