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 static String CONTENTTYPE = "application/json";
99 private static String SUPERADMIN = "super-admin";
100 private static String SUPEREDITOR = "super-editor";
101 private static String SUPERGUEST = "super-guest";
102 private static String ADMIN = "admin";
103 private static String EDITOR = "editor";
104 private static String GUEST = "guest";
105 private static String RESULT = "result";
107 private static Path closedLoopJsonLocation;
108 private static JsonArray policyNames;
110 public static JsonArray getPolicyNames() {
114 public static void setPolicyNames(JsonArray policyNames) {
115 PolicyManagerServlet.policyNames = policyNames;
118 private static List<String> serviceTypeNamesList = new ArrayList<>();
119 private List<Object> policyData;
121 public static List<String> getServiceTypeNamesList() {
122 return serviceTypeNamesList;
126 public void init(ServletConfig servletConfig) throws ServletException {
127 super.init(servletConfig);
129 // Common initialization
131 XACMLRest.xacmlInit(servletConfig);
133 //Initialize ClosedLoop JSON
135 PolicyManagerServlet.initializeJSONLoad();
138 protected static void initializeJSONLoad() {
139 closedLoopJsonLocation = Paths.get(XACMLProperties
140 .getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP));
141 FileInputStream inputStream = null;
142 String location = closedLoopJsonLocation.toString();
144 inputStream = new FileInputStream(location);
145 if (location.endsWith("json")) {
146 JsonReader jsonReader = null;
147 jsonReader = Json.createReader(inputStream);
148 policyNames = jsonReader.readArray();
149 serviceTypeNamesList = new ArrayList<>();
150 for (int i = 0; i < policyNames.size(); i++) {
151 javax.json.JsonObject policyName = policyNames.getJsonObject(i);
152 String name = policyName.getJsonString("serviceTypePolicyName").getString();
153 serviceTypeNamesList.add(name);
157 } catch (FileNotFoundException e) {
158 LOGGER.error("Exception Occured while initializing the JSONConfig file"+e);
162 } catch (IOException e) {
163 LOGGER.error("Exception Occured while closing the File InputStream"+e);
169 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
170 LOGGER.debug("doPost");
172 // if request contains multipart-form-data
173 if (ServletFileUpload.isMultipartContent(request)) {
174 uploadFile(request, response);
176 // all other post request has json params in body
178 fileOperation(request, response);
180 } catch (Exception e) {
181 setError(e, response);
185 //Set Error Message for Exception
186 private void setError(Exception t, HttpServletResponse response) throws IOException {
188 JSONObject responseJsonObject = error(t.getMessage());
189 response.setContentType(CONTENTTYPE);
190 PrintWriter out = response.getWriter();
191 out.print(responseJsonObject);
193 } catch (Exception x) {
194 LOGGER.error("Exception Occured"+x);
195 response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage());
199 //Policy Import Functionality
200 private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException {
203 Map<String, InputStream> files = new HashMap<>();
205 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
206 for (FileItem item : items) {
207 if (!item.isFormField()) {
208 // Process form file field (input type="file").
209 files.put(item.getName(), item.getInputStream());
210 if(item.getName().endsWith(".xls")){
212 File file = new File(item.getName());
213 OutputStream outputStream = new FileOutputStream(file);
214 IOUtils.copy(item.getInputStream(), outputStream);
215 outputStream.close();
216 newFile = file.toString();
217 PolicyExportAndImportController importController = new PolicyExportAndImportController();
218 importController.importRepositoryFile(newFile, request);
220 LOGGER.error("Upload error : " + e);
226 JSONObject responseJsonObject = null;
227 responseJsonObject = this.success();
228 response.setContentType(CONTENTTYPE);
229 PrintWriter out = response.getWriter();
230 out.print(responseJsonObject);
232 } catch (Exception e) {
233 LOGGER.debug("Cannot write file");
234 throw new ServletException("Cannot write file", e);
238 //File Operation Functionality
239 private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
240 JSONObject responseJsonObject = null;
242 StringBuilder sb = new StringBuilder();
243 BufferedReader br = request.getReader();
245 while ((str = br.readLine()) != null) {
249 JSONObject jObj = new JSONObject(sb.toString());
250 JSONObject params = jObj.getJSONObject("params");
251 Mode mode = Mode.valueOf(params.getString("mode"));
254 responseJsonObject = addFolder(params, request);
257 responseJsonObject = copy(params, request);
260 responseJsonObject = delete(params, request);
263 responseJsonObject = editFile(params);
266 responseJsonObject = editFile(params);
269 responseJsonObject = list(params, request);
272 responseJsonObject = rename(params, request);
274 case DESCRIBEPOLICYFILE:
275 responseJsonObject = describePolicy(params);
278 responseJsonObject = addFolder(params, request);
281 responseJsonObject = switchVersion(params, request);
284 responseJsonObject = searchPolicyList(params, request);
287 throw new ServletException("not implemented");
289 if (responseJsonObject == null) {
290 responseJsonObject = error("generic error : responseJsonObject is null");
292 } catch (Exception e) {
293 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While doing File Operation" + e);
294 responseJsonObject = error(e.getMessage());
296 response.setContentType(CONTENTTYPE);
297 PrintWriter out = response.getWriter();
298 out.print(responseJsonObject);
302 private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) {
303 Set<String> scopes = null;
304 List<String> roles = null;
305 policyData = new ArrayList<>();
306 JSONArray policyList = null;
307 if(params.has("policyList")){
308 policyList = (JSONArray) params.get("policyList");
310 PolicyController controller = new PolicyController();
311 List<JSONObject> resultList = new ArrayList<>();
313 //Get the Login Id of the User from Request
314 String userId = UserUtils.getUserSession(request).getOrgUserId();
315 //Check if the Role and Scope Size are Null get the values from db.
316 List<Object> userRoles = PolicyController.getRoles(userId);
317 roles = new ArrayList<>();
318 scopes = new HashSet<>();
319 for(Object role: userRoles){
320 Roles userRole = (Roles) role;
321 roles.add(userRole.getRole());
322 if(userRole.getScope() != null){
323 if(userRole.getScope().contains(",")){
324 String[] multipleScopes = userRole.getScope().split(",");
325 for(int i =0; i < multipleScopes.length; i++){
326 scopes.add(multipleScopes[i]);
329 scopes.add(userRole.getScope());
333 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
334 if(scopes.isEmpty()){
335 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
338 if(policyList!= null){
339 for(int i = 0; i < policyList.length(); i++){
340 String policyName = policyList.get(i).toString().replace(".xml", "");
341 String version = policyName.substring(policyName.lastIndexOf(".")+1);
342 policyName = policyName.substring(0, policyName.lastIndexOf(".")).replace(".", File.separator);
343 if(policyName.contains("\\")){
344 policyName = policyName.replace("\\", "\\\\");
346 String policyVersionQuery = "From PolicyVersion where policy_name ='"+policyName+"' and active_version = '"+version+"'and id >0";
347 List<Object> activeData = controller.getDataByQuery(policyVersionQuery);
348 if(!activeData.isEmpty()){
349 PolicyVersion policy = (PolicyVersion) activeData.get(0);
350 JSONObject el = new JSONObject();
351 el.put("name", policy.getPolicyName().replace(File.separator, "/"));
352 el.put("date", policy.getModifiedDate());
353 el.put("version", policy.getActiveVersion());
355 el.put("type", "file");
356 el.put("createdBy", getUserName(policy.getCreatedBy()));
357 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
362 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ){
363 policyData = controller.getData(PolicyVersion.class);
365 List<Object> filterdatas = controller.getData(PolicyVersion.class);
366 for(Object filter : filterdatas){
367 PolicyVersion filterdata = (PolicyVersion) filter;
368 String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator));
369 if(scopes.contains(scopeName)){
370 policyData.add(filterdata);
375 if(!policyData.isEmpty()){
376 for(int i =0; i < policyData.size(); i++){
377 PolicyVersion policy = (PolicyVersion) policyData.get(i);
378 JSONObject el = new JSONObject();
379 el.put("name", policy.getPolicyName().replace(File.separator, "/"));
380 el.put("date", policy.getModifiedDate());
381 el.put("version", policy.getActiveVersion());
383 el.put("type", "file");
384 el.put("createdBy", getUserName(policy.getCreatedBy()));
385 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
391 LOGGER.error("Exception occured while reading policy Data from Policy Version table for Policy Search Data"+e);
394 return new JSONObject().put(RESULT, resultList);
397 //Switch Version Functionality
398 private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{
399 String path = params.getString("path");
400 String userId = null;
402 userId = UserUtils.getUserSession(request).getOrgUserId();
403 } catch (Exception e) {
404 LOGGER.error("Exception Occured while reading userid from cookie" +e);
407 String removeExtension = path.replace(".xml", "");
408 if(path.startsWith("/")){
409 policyName = removeExtension.substring(1, removeExtension.lastIndexOf("."));
411 policyName = removeExtension.substring(0, removeExtension.lastIndexOf("."));
414 String activePolicy = null;
415 PolicyController controller = new PolicyController();
416 if(params.toString().contains("activeVersion")){
417 String activeVersion = params.getString("activeVersion");
418 String highestVersion = params.get("highestVersion").toString();
419 if(Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)){
420 return error("The Version shouldn't be greater than Highest Value");
422 activePolicy = policyName + "." + activeVersion + ".xml";
423 String dbCheckName = activePolicy.replace("/", ".");
424 if(dbCheckName.contains("Config_")){
425 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
426 }else if(dbCheckName.contains("Action_")){
427 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
428 }else if(dbCheckName.contains("Decision_")){
429 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
431 String[] splitDBCheckName = dbCheckName.split(":");
432 String peQuery = "FROM PolicyEntity where policyName = '"+splitDBCheckName[1]+"' and scope ='"+splitDBCheckName[0]+"'";
433 List<Object> policyEntity = controller.getDataByQuery(peQuery);
434 PolicyEntity pentity = (PolicyEntity) policyEntity.get(0);
435 if(pentity.isDeleted()){
436 return error("The Policy is Not Existing in Workspace");
438 if(policyName.contains("/")){
439 policyName = policyName.replace("/", File.separator);
441 policyName = policyName.substring(policyName.indexOf(File.separator)+1);
442 if(policyName.contains("\\")){
443 policyName = policyName.replace(File.separator, "\\");
445 policyName = splitDBCheckName[0].replace(".", File.separator)+File.separator+policyName;
446 String watchPolicyName = policyName;
447 if(policyName.contains("/")){
448 policyName = policyName.replace("/", File.separator);
450 if(policyName.contains("\\")){
451 policyName = policyName.replace("\\", "\\\\");
453 String query = "update PolicyVersion set active_version='"+activeVersion+"' where policy_name ='"+policyName+"' and id >0";
455 controller.executeQuery(query);
456 //Policy Notification
457 PolicyVersion entity = new PolicyVersion();
458 entity.setPolicyName(watchPolicyName);
459 entity.setActiveVersion(Integer.parseInt(activeVersion));
460 entity.setModifiedBy(userId);
461 controller.watchPolicyFunction(entity, activePolicy, "SwitchVersion");
466 return controller.switchVersionPolicyContent(policyName);
470 private JSONObject describePolicy(JSONObject params) throws ServletException{
471 JSONObject object = null;
472 String path = params.getString("path");
473 String policyName = null;
474 if(path.startsWith("/")){
475 path = path.substring(1);
476 policyName = path.substring(path.lastIndexOf("/") +1);
477 path = path.replace("/", ".");
479 path = path.replace("/", ".");
481 if(path.contains("Config_")){
482 path = path.replace(".Config_", ":Config_");
483 }else if(path.contains("Action_")){
484 path = path.replace(".Action_", ":Action_");
485 }else if(path.contains("Decision_")){
486 path = path.replace(".Decision_", ":Decision_");
488 PolicyController controller = new PolicyController();
489 String[] split = path.split(":");
490 String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'";
491 List<Object> queryData = controller.getDataByQuery(query);
492 if(!queryData.isEmpty()){
493 PolicyEntity entity = (PolicyEntity) queryData.get(0);
496 temp = File.createTempFile(policyName, ".tmp");
497 BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
498 bw.write(entity.getPolicyData());
500 object = HumanPolicyComponent.DescribePolicy(temp);
501 } catch (IOException e) {
502 LOGGER.error("Exception Occured while Describing the Policy"+e);
509 return error("Error Occured while Describing the Policy");
515 //Get the List of Policies and Scopes for Showing in Editor tab
516 private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException {
517 Set<String> scopes = null;
518 List<String> roles = null;
520 //Get the Login Id of the User from Request
521 String userId = UserUtils.getUserSession(request).getOrgUserId();
522 //Check if the Role and Scope Size are Null get the values from db.
523 List<Object> userRoles = PolicyController.getRoles(userId);
524 roles = new ArrayList<>();
525 scopes = new HashSet<>();
526 for(Object role: userRoles){
527 Roles userRole = (Roles) role;
528 roles.add(userRole.getRole());
529 if(userRole.getScope() != null){
530 if(userRole.getScope().contains(",")){
531 String[] multipleScopes = userRole.getScope().split(",");
532 for(int i =0; i < multipleScopes.length; i++){
533 scopes.add(multipleScopes[i]);
536 scopes.add(userRole.getScope());
540 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
541 if(scopes.isEmpty()){
542 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
546 List<JSONObject> resultList = new ArrayList<>();
547 boolean onlyFolders = params.getBoolean("onlyFolders");
548 String path = params.getString("path");
549 if(path.contains("..xml")){
550 path = path.replaceAll("..xml", "").trim();
554 if("/".equals(path)){
555 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
556 List<Object> scopesList = queryPolicyEditorScopes(null);
557 for(Object list : scopesList){
558 PolicyEditorScopes scope = (PolicyEditorScopes) list;
559 if(!(scope.getScopeName().contains(File.separator))){
560 JSONObject el = new JSONObject();
561 el.put("name", scope.getScopeName());
562 el.put("date", scope.getCreatedDate());
564 el.put("type", "dir");
565 el.put("createdBy", scope.getUserCreatedBy().getUserName());
566 el.put("modifiedBy", scope.getUserModifiedBy().getUserName());
570 }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){
571 for(Object scope : scopes){
572 JSONObject el = new JSONObject();
573 List<Object> scopesList = queryPolicyEditorScopes(scope.toString());
574 PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
575 el.put("name", scopeById.getScopeName());
576 el.put("date", scopeById.getCreatedDate());
578 el.put("type", "dir");
579 el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
580 el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
586 String scopeName = path.substring(path.indexOf("/") +1);
587 activePolicyList(scopeName, resultList, roles, scopes, onlyFolders);
588 } catch (Exception ex) {
589 LOGGER.error("Error Occured While reading Policy Files List"+ex );
593 return new JSONObject().put(RESULT, resultList);
594 } catch (Exception e) {
595 LOGGER.error("list", e);
596 return error(e.getMessage());
600 private List<Object> queryPolicyEditorScopes(String scopeName){
601 String scopeNamequery = "";
602 if(scopeName == null){
603 scopeNamequery = "from PolicyEditorScopes";
605 scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"'";
607 PolicyController controller = new PolicyController();
608 List<Object> scopesList = controller.getDataByQuery(scopeNamequery);
612 //Get Active Policy List based on Scope Selection form Policy Version table
613 private void activePolicyList(String scopeName, List<JSONObject> resultList, List<String> roles, Set<String> scopes, boolean onlyFolders){
614 PolicyController controller = new PolicyController();
615 if(scopeName.contains("/")){
616 scopeName = scopeName.replace("/", File.separator);
618 if(scopeName.contains("\\")){
619 scopeName = scopeName.replace("\\", "\\\\\\\\");
621 String query = "from PolicyVersion where POLICY_NAME like'" +scopeName+"%'";
622 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"%'";
623 List<Object> activePolicies = controller.getDataByQuery(query);
624 List<Object> scopesList = controller.getDataByQuery(scopeNamequery);
625 for(Object list : scopesList){
626 PolicyEditorScopes scopeById = (PolicyEditorScopes) list;
627 String scope = scopeById.getScopeName();
628 if(scope.contains(File.separator)){
629 String checkScope = scope.substring(0, scope.lastIndexOf(File.separator));
630 if(scopeName.contains("\\\\")){
631 scopeName = scopeName.replace("\\\\", File.separator);
633 if(scope.contains(File.separator)){
634 scope = scope.substring(checkScope.length()+1);
635 if(scope.contains(File.separator)){
636 scope = scope.substring(0, scope.indexOf(File.separator));
639 if(scopeName.equalsIgnoreCase(checkScope)){
640 JSONObject el = new JSONObject();
641 el.put("name", scope);
642 el.put("date", scopeById.getModifiedDate());
644 el.put("type", "dir");
645 el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
646 el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
651 String scopeNameCheck = null;
652 for (Object list : activePolicies) {
653 PolicyVersion policy = (PolicyVersion) list;
654 String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator));
655 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
656 if((scopeName.contains("\\\\"))){
657 scopeNameCheck = scopeName.replace("\\\\", File.separator);
659 scopeNameCheck = scopeName;
661 if(scopeNameValue.equals(scopeNameCheck)){
662 JSONObject el = new JSONObject();
663 el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
664 el.put("date", policy.getModifiedDate());
665 el.put("version", policy.getActiveVersion());
667 el.put("type", "file");
668 el.put("createdBy", getUserName(policy.getCreatedBy()));
669 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
672 }else if(!scopes.isEmpty()){
673 if(scopes.contains(scopeNameValue)){
674 JSONObject el = new JSONObject();
675 el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
676 el.put("date", policy.getModifiedDate());
677 el.put("version", policy.getActiveVersion());
679 el.put("type", "file");
680 el.put("createdBy", getUserName(policy.getCreatedBy()));
681 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
688 private String getUserName(String loginId){
689 PolicyController controller = new PolicyController();
690 UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
691 if(userInfo == null){
694 return userInfo.getUserName();
698 private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
700 boolean isActive = false;
701 List<String> policyActiveInPDP = new ArrayList<>();
702 Set<String> scopeOfPolicyActiveInPDP = new HashSet<>();
703 String userId = UserUtils.getUserSession(request).getOrgUserId();
704 String oldPath = params.getString("path");
705 String newPath = params.getString("newPath");
706 oldPath = oldPath.substring(oldPath.indexOf("/")+1);
707 newPath = newPath.substring(newPath.indexOf("/")+1);
708 if(oldPath.endsWith(".xml")){
709 JSONObject result = policyRename(oldPath, newPath, userId);
710 if(!(Boolean)(result.getJSONObject("result").get("success"))){
714 String scopeName = oldPath;
715 String newScopeName = newPath;
716 if(scopeName.contains("/")){
717 scopeName = scopeName.replace("/", File.separator);
718 newScopeName = newScopeName.replace("/", File.separator);
720 if(scopeName.contains("\\")){
721 scopeName = scopeName.replace("\\", "\\\\\\\\");
722 newScopeName = newScopeName.replace("\\", "\\\\\\\\");
724 PolicyController controller = new PolicyController();
725 String query = "from PolicyVersion where POLICY_NAME like'" +scopeName+"%'";
726 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"%'";
727 List<Object> activePolicies = controller.getDataByQuery(query);
728 List<Object> scopesList = controller.getDataByQuery(scopeNamequery);
729 for(Object object : activePolicies){
730 PolicyVersion activeVersion = (PolicyVersion) object;
731 String policyOldPath = activeVersion.getPolicyName().replace(File.separator, "/") + "." + activeVersion.getActiveVersion() + ".xml";
732 String policyNewPath = policyOldPath.replace(oldPath, newPath);
733 JSONObject result = policyRename(policyOldPath, policyNewPath, userId);
734 if(!(Boolean)(result.getJSONObject("result").get("success"))){
736 policyActiveInPDP.add(policyOldPath);
737 String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf("/"));
738 scopeOfPolicyActiveInPDP.add(scope.replace("/", File.separator));
741 boolean rename = false;
742 if(activePolicies.size() != policyActiveInPDP.size()){
746 UserInfo userInfo = new UserInfo();
747 userInfo.setUserLoginId(userId);
748 if(policyActiveInPDP.size() == 0){
749 renameScope(scopesList, scopeName, newScopeName, controller);
751 renameScope(scopesList, scopeName, newScopeName, controller);
752 for(String scope : scopeOfPolicyActiveInPDP){
753 PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes();
754 editorScopeEntity.setScopeName(scope.replace("\\", "\\\\\\\\"));
755 editorScopeEntity.setUserCreatedBy(userInfo);
756 editorScopeEntity.setUserModifiedBy(userInfo);
757 controller.saveData(editorScopeEntity);
761 return error("The Following policies rename failed. Since they are active in PDP Groups" +policyActiveInPDP);
765 } catch (Exception e) {
766 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
767 return error(e.getMessage());
771 private void renameScope(List<Object> scopesList, String scopeName, String newScopeName, PolicyController controller){
772 for(Object object : scopesList){
773 PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object;
774 if(scopeName.contains("\\\\\\\\")){
775 scopeName = scopeName.replace("\\\\\\\\", File.separator);
776 newScopeName = newScopeName.replace("\\\\\\\\", File.separator);
778 String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName);
779 editorScopeEntity.setScopeName(scope);
780 controller.updateData(editorScopeEntity);
784 private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
786 PolicyEntity entity = null;
787 PolicyController controller = new PolicyController();
789 String policyVersionName = newPath.replace(".xml", "");
790 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")).replace("/", File.separator);
792 String oldpolicyVersionName = oldPath.replace(".xml", "");
793 String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf(".")).replace("/", File.separator);
795 String newpolicyName = newPath.replace("/", ".");
796 String newPolicyCheck = newpolicyName;
797 if(newPolicyCheck.contains("Config_")){
798 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
799 }else if(newPolicyCheck.contains("Action_")){
800 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
801 }else if(newPolicyCheck.contains("Decision_")){
802 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
804 String[] newPolicySplit = newPolicyCheck.split(":");
806 String orignalPolicyName = oldPath.replace("/", ".");
807 String oldPolicyCheck = orignalPolicyName;
808 if(oldPolicyCheck.contains("Config_")){
809 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
810 }else if(oldPolicyCheck.contains("Action_")){
811 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
812 }else if(oldPolicyCheck.contains("Decision_")){
813 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
815 String[] oldPolicySplit = oldPolicyCheck.split(":");
817 //Check PolicyEntity table with newPolicy Name
818 String policyEntityquery = "FROM PolicyEntity where policyName = '"+newPolicySplit[1]+"' and scope ='"+newPolicySplit[0]+"'";
819 List<Object> queryData = controller.getDataByQuery(policyEntityquery);
820 if(!queryData.isEmpty()){
821 entity = (PolicyEntity) queryData.get(0);
822 return error("Policy rename failed. Since, the policy with same name already exists.");
825 //Query the Policy Entity with oldPolicy Name
826 String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf("."));
827 String oldpolicyEntityquery = "FROM PolicyEntity where policyName like '"+policyEntityCheck+"%' and scope ='"+oldPolicySplit[0]+"'";
828 List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery);
829 if(!oldEntityData.isEmpty()){
830 String groupQuery = "FROM PolicyGroupEntity where (";
831 for(int i=0; i<oldEntityData.size(); i++){
832 entity = (PolicyEntity) oldEntityData.get(i);
834 groupQuery = groupQuery + "policyid =" + entity.getPolicyId();
836 groupQuery = groupQuery + " or policyid =" + entity.getPolicyId();
839 groupQuery = groupQuery + ")";
840 List<Object> groupEntityData = controller.getDataByQuery(groupQuery);
841 if(groupEntityData.size() > 0){
842 return error("Policy rename failed. Since the policy or its version is active in PDP Groups.");
844 for(int i=0; i<oldEntityData.size(); i++){
845 entity = (PolicyEntity) oldEntityData.get(i);
846 checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0] , newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
849 return error("Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin.");
853 } catch (Exception e) {
854 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
855 return error(e.getMessage());
859 private JSONObject checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, String oldScope, String removeoldPolicyExtension,
860 String policyName, String newpolicyName, String oldpolicyName, String userId) throws ServletException{
862 ConfigurationDataEntity configEntity = entity.getConfigurationData();
863 ActionBodyEntity actionEntity = entity.getActionBodyEntity();
864 PolicyController controller = new PolicyController();
866 String oldPolicyNameWithoutExtension = removeoldPolicyExtension;
867 String newPolicyNameWithoutExtension = removenewPolicyExtension;
868 if(removeoldPolicyExtension.endsWith(".xml")){
869 oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf("."));
870 newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf("."));
872 entity.setPolicyName(entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
873 entity.setPolicyData(entity.getPolicyData().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
874 entity.setScope(newScope);
875 entity.setModifiedBy(userId);
876 if(newpolicyName.contains("Config_")){
877 String oldConfigurationName = configEntity.getConfigurationName();
878 configEntity.setConfigurationName(configEntity.getConfigurationName().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
879 controller.updateData(configEntity);
880 String newConfigurationName = configEntity.getConfigurationName();
881 File file = new File(PolicyController.configHome + File.separator + oldConfigurationName);
883 File renamefile = new File(PolicyController.configHome + File.separator + newConfigurationName);
884 file.renameTo(renamefile);
886 }else if(newpolicyName.contains("Action_")){
887 String oldConfigurationName = actionEntity.getActionBodyName();
888 actionEntity.setActionBody(actionEntity.getActionBody().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
889 controller.updateData(actionEntity);
890 String newConfigurationName = actionEntity.getActionBodyName();
891 File file = new File(PolicyController.actionHome + File.separator + oldConfigurationName);
893 File renamefile = new File(PolicyController.actionHome + File.separator + newConfigurationName);
894 file.renameTo(renamefile);
897 controller.updateData(entity);
899 PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldpolicyName);
900 versionEntity.setPolicyName(policyName);
901 versionEntity.setModifiedBy(userId);
902 controller.updateData(versionEntity);
903 String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator)+1);
904 String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
905 if(movePolicyCheck.equals(moveOldPolicyCheck)){
906 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move");
908 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename");
911 } catch (Exception e) {
912 LOGGER.error("Exception Occured"+e);
913 return error(e.getMessage());
917 private JSONObject cloneRecord(String newpolicyName, String oldScope, String removeoldPolicyExtension, String newScope, String removenewPolicyExtension, PolicyEntity entity, String userId) throws ServletException{
918 String queryEntityName = null;
919 PolicyController controller = new PolicyController();
920 PolicyEntity cloneEntity = new PolicyEntity();
921 cloneEntity.setPolicyName(newpolicyName);
922 removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
923 removenewPolicyExtension = removenewPolicyExtension.replace(".xml", "");
924 cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope+"."+removeoldPolicyExtension, newScope+"."+removenewPolicyExtension));
925 cloneEntity.setScope(entity.getScope());
926 String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
927 String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
928 if(newpolicyName.contains("Config_")){
929 ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
930 configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
931 queryEntityName = configurationDataEntity.getConfigurationName();
932 configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody());
933 configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType());
934 configurationDataEntity.setDeleted(false);
935 configurationDataEntity.setCreatedBy(userId);
936 configurationDataEntity.setModifiedBy(userId);
937 controller.saveData(configurationDataEntity);
938 ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
939 cloneEntity.setConfigurationData(configEntiy);
940 }else if(newpolicyName.contains("Action_")){
941 ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
942 actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
943 queryEntityName = actionBodyEntity.getActionBodyName();
944 actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody());
945 actionBodyEntity.setDeleted(false);
946 actionBodyEntity.setCreatedBy(userId);
947 actionBodyEntity.setModifiedBy(userId);
948 controller.saveData(actionBodyEntity);
949 ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class, "actionBodyName", queryEntityName);
950 cloneEntity.setActionBodyEntity(actionEntiy);
952 cloneEntity.setDeleted(entity.isDeleted());
953 cloneEntity.setCreatedBy(userId);
954 cloneEntity.setModifiedBy(userId);
955 controller.saveData(cloneEntity);
961 private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
963 String userId = UserUtils.getUserSession(request).getOrgUserId();
964 String oldPath = params.getString("path");
965 String newPath = params.getString("newPath");
966 oldPath = oldPath.substring(oldPath.indexOf("/")+1);
967 newPath = newPath.substring(newPath.indexOf("/")+1);
969 String policyVersionName = newPath.replace(".xml", "");
970 String version = policyVersionName.substring(policyVersionName.indexOf(".")+1);
971 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")).replace("/", File.separator);
973 String newpolicyName = newPath.replace("/", ".");
975 String orignalPolicyName = oldPath.replace("/", ".");
977 String newPolicyCheck = newpolicyName;
978 if(newPolicyCheck.contains("Config_")){
979 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
980 }else if(newPolicyCheck.contains("Action_")){
981 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
982 }else if(newPolicyCheck.contains("Decision_")){
983 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
985 String[] newPolicySplit = newPolicyCheck.split(":");
987 String oldPolicyCheck = orignalPolicyName;
988 if(oldPolicyCheck.contains("Config_")){
989 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
990 }else if(oldPolicyCheck.contains("Action_")){
991 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
992 }else if(oldPolicyCheck.contains("Decision_")){
993 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
995 String[] oldPolicySplit = oldPolicyCheck.split(":");
997 PolicyController controller = new PolicyController();
999 PolicyEntity entity = null;
1000 boolean success = false;
1002 //Check PolicyEntity table with newPolicy Name
1003 String policyEntityquery = "FROM PolicyEntity where policyName = '"+newPolicySplit[1]+"' and scope ='"+newPolicySplit[0]+"'";
1004 List<Object> queryData = controller.getDataByQuery(policyEntityquery);
1005 if(!queryData.isEmpty()){
1006 entity = (PolicyEntity) queryData.get(0);
1009 //if a policy exists with new name check if it is deleted or not
1010 if(entity.isDeleted()){
1011 //Check Policy Group Entity table if policy has been pushed or not
1012 String query = "from PolicyGroupEntity where policyid = '"+entity.getPolicyId()+"'";
1013 List<Object> object = controller.getDataByQuery(query);
1015 //if PolicyGroupEntity data is empty delete the entry from database
1016 controller.deleteData(entity);
1017 //Query the Policy Entity with oldPolicy Name
1018 policyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'";
1019 queryData = controller.getDataByQuery(policyEntityquery);
1020 if(!queryData.isEmpty()){
1021 entity = (PolicyEntity) queryData.get(0);
1024 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId);
1028 return error("Policy Clone failed due to policy with new name existing in PDP Group.");
1031 return error("Policy Clone failed due to same name existing.");
1034 //Query the Policy Entity with oldPolicy Name
1035 policyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'";
1036 queryData = controller.getDataByQuery(policyEntityquery);
1037 if(!queryData.isEmpty()){
1038 entity = (PolicyEntity) queryData.get(0);
1041 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId);
1046 PolicyVersion entityItem = new PolicyVersion();
1047 entityItem.setActiveVersion(Integer.parseInt(version));
1048 entityItem.setHigherVersion(Integer.parseInt(version));
1049 entityItem.setPolicyName(policyName);
1050 entityItem.setCreatedBy(userId);
1051 entityItem.setModifiedBy(userId);
1052 controller.saveData(entityItem);
1055 LOGGER.debug("copy from: {} to: {}" + oldPath +newPath);
1058 } catch (Exception e) {
1059 LOGGER.error("copy", e);
1060 return error(e.getMessage());
1064 //Delete Policy or Scope Functionality
1065 private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
1066 PolicyController controller = new PolicyController();
1067 PolicyRestController restController = new PolicyRestController();
1068 PolicyEntity policyEntity = null;
1069 String policyNamewithoutExtension;
1071 String userId = UserUtils.getUserSession(request).getOrgUserId();
1072 String deleteVersion = "";
1073 String path = params.getString("path");
1074 LOGGER.debug("delete {}" +path);
1075 if(params.has("deleteVersion")){
1076 deleteVersion = params.getString("deleteVersion");
1078 path = path.substring(path.indexOf("/")+1);
1079 String policyNamewithExtension = path.replace("/", File.separator);
1080 String policyVersionName = policyNamewithExtension.replace(".xml", "");
1082 if(path.endsWith(".xml")){
1083 policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf("."));
1084 policyNamewithoutExtension = policyNamewithoutExtension.replace(File.separator, ".");
1085 String splitPolicyName = null;
1086 if(policyNamewithoutExtension.contains("Config_")){
1087 splitPolicyName = policyNamewithoutExtension.replace(".Config_", ":Config_");
1088 }else if(policyNamewithoutExtension.contains("Action_")){
1089 splitPolicyName = policyNamewithoutExtension.replace(".Action_", ":Action_");
1090 }else if(policyNamewithoutExtension.contains("Decision_")){
1091 splitPolicyName = policyNamewithoutExtension.replace(".Decision_", ":Decision_");
1093 String[] split = splitPolicyName.split(":");
1094 query = "FROM PolicyEntity where policyName like '"+split[1]+"%' and scope ='"+split[0]+"'";
1096 policyNamewithoutExtension = path.replace(File.separator, ".");
1097 query = "FROM PolicyEntity where scope like '"+policyNamewithoutExtension+"%'";
1100 List<Object> policyEntityobjects = controller.getDataByQuery(query);
1101 String activePolicyName = null;
1102 boolean pdpCheck = false;
1103 if(path.endsWith(".xml")){
1104 policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator);
1105 int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf(".")+1));
1106 if("ALL".equals(deleteVersion)){
1107 if(!policyEntityobjects.isEmpty()){
1108 for(Object object : policyEntityobjects){
1109 policyEntity = (PolicyEntity) object;
1110 String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'";
1111 List<Object> groupobject = controller.getDataByQuery(groupEntityquery);
1112 if(!groupobject.isEmpty()){
1114 activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName();
1116 //Delete the entity from Elastic Search Database
1117 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1118 restController.deleteElasticData(searchFileName);
1119 //Delete the entity from Policy Entity table
1120 controller.deleteData(policyEntity);
1121 if(policyNamewithoutExtension.contains("Config_")){
1122 controller.deleteData(policyEntity.getConfigurationData());
1123 }else if(policyNamewithoutExtension.contains("Action_")){
1124 controller.deleteData(policyEntity.getActionBodyEntity());
1129 //Policy Notification
1130 PolicyVersion versionEntity = new PolicyVersion();
1131 versionEntity.setPolicyName(policyNamewithoutExtension);
1132 versionEntity.setModifiedBy(userId);
1133 controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll");
1135 //Delete from policyVersion table
1136 String getActivePDPPolicyVersion = activePolicyName.replace(".xml", "");
1137 getActivePDPPolicyVersion = getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf(".")+1);
1138 String policyVersionQuery = "update PolicyVersion set active_version='"+getActivePDPPolicyVersion+"' , highest_version='"+getActivePDPPolicyVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1139 if(policyVersionQuery != null){
1140 controller.executeQuery(policyVersionQuery);
1142 return error("Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "+activePolicyName);
1144 //No Active Policy in PDP. So, deleting all entries from policyVersion table
1145 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1146 if(policyVersionQuery != null){
1147 controller.executeQuery(policyVersionQuery);
1150 }else if("CURRENT".equals(deleteVersion)){
1151 String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1);
1152 String currentVersionScope = policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator)).replace(File.separator, ".");
1153 query = "FROM PolicyEntity where policyName = '"+currentVersionPolicyName+"' and scope ='"+currentVersionScope+"'";
1154 List<Object> policyEntitys = controller.getDataByQuery(query);
1155 if(!policyEntitys.isEmpty()){
1156 policyEntity = (PolicyEntity) policyEntitys.get(0);
1158 if(policyEntity != null){
1159 String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"' and policyid > 0";
1160 List<Object> groupobject = controller.getDataByQuery(groupEntityquery);
1161 if(groupobject.isEmpty()){
1162 //Delete the entity from Elastic Search Database
1163 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1164 restController.deleteElasticData(searchFileName);
1165 //Delete the entity from Policy Entity table
1166 controller.deleteData(policyEntity);
1167 if(policyNamewithoutExtension.contains("Config_")){
1168 controller.deleteData(policyEntity.getConfigurationData());
1169 }else if(policyNamewithoutExtension.contains("Action_")){
1170 controller.deleteData(policyEntity.getActionBodyEntity());
1174 int highestVersion = 0;
1175 if(!policyEntityobjects.isEmpty()){
1176 for(Object object : policyEntityobjects){
1177 policyEntity = (PolicyEntity) object;
1178 String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
1179 int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf(".")+1));
1180 if(policyEntityVersion > highestVersion){
1181 highestVersion = policyEntityVersion;
1186 //Policy Notification
1187 PolicyVersion entity = new PolicyVersion();
1188 entity.setPolicyName(policyNamewithoutExtension);
1189 entity.setActiveVersion(highestVersion);
1190 entity.setModifiedBy(userId);
1191 controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne");
1193 String updatequery = "update PolicyVersion set active_version='"+highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"'";
1194 controller.executeQuery(updatequery);
1196 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1197 if(policyVersionQuery != null){
1198 controller.executeQuery(policyVersionQuery);
1202 return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'");
1207 List<String> activePoliciesInPDP = new ArrayList<String>();
1208 if(!policyEntityobjects.isEmpty()){
1209 for(Object object : policyEntityobjects){
1210 policyEntity = (PolicyEntity) object;
1211 String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'";
1212 List<Object> groupobject = controller.getDataByQuery(groupEntityquery);
1213 if(!groupobject.isEmpty()){
1215 activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName());
1217 //Delete the entity from Elastic Search Database
1218 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1219 restController.deleteElasticData(searchFileName);
1220 //Delete the entity from Policy Entity table
1221 controller.deleteData(policyEntity);
1222 policyNamewithoutExtension = policyEntity.getPolicyName();
1223 if(policyNamewithoutExtension.contains("Config_")){
1224 controller.deleteData(policyEntity.getConfigurationData());
1225 }else if(policyNamewithoutExtension.contains("Action_")){
1226 controller.deleteData(policyEntity.getActionBodyEntity());
1230 //Delete from policyVersion and policyEditor Scope table
1231 String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1232 controller.executeQuery(policyVersionQuery);
1234 //Policy Notification
1235 PolicyVersion entity = new PolicyVersion();
1236 entity.setPolicyName(path);
1237 entity.setModifiedBy(userId);
1238 controller.watchPolicyFunction(entity, path, "DeleteScope");
1240 //Add Active Policies List to PolicyVersionTable
1241 for(int i =0; i < activePoliciesInPDP.size(); i++){
1242 String activePDPPolicyName = activePoliciesInPDP.get(i).replace(".xml", "");
1243 int activePDPPolicyVersion = Integer.parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf(".")+1));
1244 activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf(".")).replace(".", File.separator);
1245 PolicyVersion insertactivePDPVersion = new PolicyVersion();
1246 insertactivePDPVersion.setPolicyName(activePDPPolicyName);
1247 insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion);
1248 insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion);
1249 insertactivePDPVersion.setCreatedBy(userId);
1250 insertactivePDPVersion.setModifiedBy(userId);
1251 controller.saveData(insertactivePDPVersion);
1254 return error("All the Policies has been deleted in Scope. Except the following list of Policies:"+activePoliciesInPDP);
1256 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1257 controller.executeQuery(policyScopeQuery);
1260 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1261 controller.executeQuery(policyScopeQuery);
1265 } catch (Exception e) {
1266 LOGGER.error("delete", e);
1267 return error(e.getMessage());
1272 private JSONObject editFile(JSONObject params) throws ServletException {
1275 PolicyController controller = new PolicyController();
1276 String mode = params.getString("mode");
1277 String path = params.getString("path");
1278 LOGGER.debug("editFile path: {}"+ path);
1280 String domain = path.substring(1, path.lastIndexOf("/"));
1281 domain = domain.replace("/", ".");
1283 path = path.substring(1);
1284 path = path.replace("/", ".");
1285 String dbCheckName = path;
1286 if(dbCheckName.contains("Config_")){
1287 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
1288 }else if(dbCheckName.contains("Action_")){
1289 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
1290 }else if(dbCheckName.contains("Decision_")){
1291 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
1294 String[] split = dbCheckName.split(":");
1295 String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'";
1296 List<Object> queryData = controller.getDataByQuery(query);
1297 PolicyEntity entity = (PolicyEntity) queryData.get(0);
1298 InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
1301 Object policy = XACMLPolicyScanner.readPolicy(stream);
1302 PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
1303 policyAdapter.setData(policy);
1305 if("viewPolicy".equalsIgnoreCase(mode)){
1306 policyAdapter.setReadOnly(true);
1307 policyAdapter.setEditPolicy(false);
1309 policyAdapter.setReadOnly(false);
1310 policyAdapter.setEditPolicy(true);
1312 policyAdapter.setDomain(domain);
1313 policyAdapter.setDomainDir(domain);
1314 policyAdapter.setPolicyData(policy);
1315 String policyName = path.replace(".xml", "");
1316 policyName = policyName.substring(0, policyName.lastIndexOf("."));
1317 policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf(".")+1));
1319 PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance();
1320 setpolicyAdapter.configure(policyAdapter,entity);
1322 policyAdapter.setParentPath(null);
1323 ObjectMapper mapper = new ObjectMapper();
1324 String json = mapper.writeValueAsString(policyAdapter);
1325 JsonNode jsonNode = mapper.readTree(json);
1327 return new JSONObject().put(RESULT, jsonNode);
1328 } catch (Exception e) {
1329 LOGGER.error("editFile", e);
1330 return error(e.getMessage());
1335 private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
1336 PolicyController controller = new PolicyController();
1339 String userId = UserUtils.getUserSession(request).getOrgUserId();
1340 String path = params.getString("path");
1342 if(params.has("subScopename")){
1343 if(!params.getString("subScopename").equals("")){
1344 name = params.getString("path").replace("/", File.separator) + File.separator +params.getString("subScopename");
1347 name = params.getString("name");
1349 }catch(Exception e){
1350 name = params.getString("name");
1351 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e);
1353 String validateName;
1354 if(name.contains(File.separator)){
1355 validateName = name.substring(name.lastIndexOf(File.separator)+1);
1357 validateName = name;
1359 if(!name.isEmpty()){
1360 String validate = PolicyUtils.emptyPolicyValidator(validateName);
1361 if(!validate.contains("success")){
1362 return error(validate);
1365 LOGGER.debug("addFolder path: {} name: {}" + path +name);
1366 if(!name.equals("")){
1367 PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, "scopeName", name);
1369 UserInfo userInfo = new UserInfo();
1370 userInfo.setUserLoginId(userId);
1371 PolicyEditorScopes newScope = new PolicyEditorScopes();
1372 String scopeName = null;
1373 if(name.startsWith(File.separator)){
1374 scopeName = name.substring(1);
1378 newScope.setScopeName(scopeName);
1379 newScope.setUserCreatedBy(userInfo);
1380 newScope.setUserModifiedBy(userInfo);
1381 controller.saveData(newScope);
1383 return error("Scope Already Exists");
1387 } catch (Exception e) {
1388 LOGGER.error("addFolder", e);
1389 return error(e.getMessage());
1393 //Return Error Object
1394 private JSONObject error(String msg) throws ServletException {
1396 JSONObject result = new JSONObject();
1397 result.put("success", false);
1398 result.put("error", msg);
1399 return new JSONObject().put(RESULT, result);
1400 } catch (JSONException e) {
1401 throw new ServletException(e);
1405 //Return Success Object
1406 private JSONObject success() throws ServletException {
1408 JSONObject result = new JSONObject();
1409 result.put("success", true);
1410 result.put("error", (Object) null);
1411 return new JSONObject().put(RESULT, result);
1412 } catch (JSONException e) {
1413 throw new ServletException(e);