2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.admin;
23 import java.io.BufferedReader;
24 import java.io.BufferedWriter;
25 import java.io.ByteArrayInputStream;
27 import java.io.FileInputStream;
28 import java.io.FileNotFoundException;
29 import java.io.FileOutputStream;
30 import java.io.FileWriter;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.io.OutputStream;
34 import java.io.PrintWriter;
35 import java.nio.charset.StandardCharsets;
36 import java.nio.file.Path;
37 import java.nio.file.Paths;
38 import java.util.ArrayList;
39 import java.util.HashMap;
40 import java.util.HashSet;
41 import java.util.List;
45 import javax.json.Json;
46 import javax.json.JsonArray;
47 import javax.json.JsonReader;
48 import javax.script.SimpleBindings;
49 import javax.servlet.ServletConfig;
50 import javax.servlet.ServletException;
51 import javax.servlet.annotation.WebInitParam;
52 import javax.servlet.annotation.WebServlet;
53 import javax.servlet.http.HttpServlet;
54 import javax.servlet.http.HttpServletRequest;
55 import javax.servlet.http.HttpServletResponse;
57 import org.apache.commons.compress.utils.IOUtils;
58 import org.apache.commons.fileupload.FileItem;
59 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
60 import org.apache.commons.fileupload.servlet.ServletFileUpload;
61 import org.apache.http.HttpStatus;
62 import org.json.JSONArray;
63 import org.json.JSONException;
64 import org.json.JSONObject;
65 import org.onap.policy.common.logging.flexlogger.FlexLogger;
66 import org.onap.policy.common.logging.flexlogger.Logger;
67 import org.onap.policy.components.HumanPolicyComponent;
68 import org.onap.policy.controller.PolicyController;
69 import org.onap.policy.controller.PolicyExportAndImportController;
70 import org.onap.policy.rest.XACMLRest;
71 import org.onap.policy.rest.XACMLRestProperties;
72 import org.onap.policy.rest.adapter.PolicyRestAdapter;
73 import org.onap.policy.rest.jpa.ActionBodyEntity;
74 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
75 import org.onap.policy.rest.jpa.PolicyEditorScopes;
76 import org.onap.policy.rest.jpa.PolicyEntity;
77 import org.onap.policy.rest.jpa.PolicyVersion;
78 import org.onap.policy.rest.jpa.UserInfo;
79 import org.onap.policy.utils.PolicyUtils;
80 import org.onap.policy.xacml.api.XACMLErrorConstants;
81 import org.onap.policy.xacml.util.XACMLPolicyScanner;
82 import org.openecomp.policy.model.Roles;
83 import org.openecomp.portalsdk.core.web.support.UserUtils;
85 import com.att.research.xacml.util.XACMLProperties;
86 import com.fasterxml.jackson.databind.JsonNode;
87 import com.fasterxml.jackson.databind.ObjectMapper;
90 @WebServlet(value ="/fm/*", loadOnStartup = 1, initParams = { @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.admin.properties", description = "The location of the properties file holding configuration information.") })
91 public class PolicyManagerServlet extends HttpServlet {
92 private static final Logger LOGGER = FlexLogger.getLogger(PolicyManagerServlet.class);
93 private static final long serialVersionUID = -8453502699403909016L;
95 private static boolean jUnit = false;
97 public static boolean isjUnit() {
101 public static void setjUnit(boolean jUnit) {
102 PolicyManagerServlet.jUnit = jUnit;
106 LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT, SEARCHLIST
109 private static PolicyController policyController;
110 public synchronized PolicyController getPolicyController() {
111 return policyController;
114 public synchronized static void setPolicyController(PolicyController policyController) {
115 PolicyManagerServlet.policyController = policyController;
118 private static String CONTENTTYPE = "application/json";
119 private static String SUPERADMIN = "super-admin";
120 private static String SUPEREDITOR = "super-editor";
121 private static String SUPERGUEST = "super-guest";
122 private static String ADMIN = "admin";
123 private static String EDITOR = "editor";
124 private static String GUEST = "guest";
125 private static String RESULT = "result";
127 private static Path closedLoopJsonLocation;
128 private static JsonArray policyNames;
129 private static String testUserId = null;
131 public static JsonArray getPolicyNames() {
135 public static void setPolicyNames(JsonArray policyNames) {
136 PolicyManagerServlet.policyNames = policyNames;
139 private static List<String> serviceTypeNamesList = new ArrayList<>();
141 public static List<String> getServiceTypeNamesList() {
142 return serviceTypeNamesList;
146 public void init(ServletConfig servletConfig) throws ServletException {
147 super.init(servletConfig);
149 // Common initialization
151 XACMLRest.xacmlInit(servletConfig);
153 //Initialize ClosedLoop JSON
155 PolicyManagerServlet.initializeJSONLoad();
158 protected static void initializeJSONLoad() {
159 closedLoopJsonLocation = Paths.get(XACMLProperties
160 .getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP));
161 FileInputStream inputStream = null;
162 JsonReader jsonReader = null;
163 String location = closedLoopJsonLocation.toString();
165 inputStream = new FileInputStream(location);
166 if (location.endsWith("json")) {
167 jsonReader = Json.createReader(inputStream);
168 policyNames = jsonReader.readArray();
169 serviceTypeNamesList = new ArrayList<>();
170 for (int i = 0; i < policyNames.size(); i++) {
171 javax.json.JsonObject policyName = policyNames.getJsonObject(i);
172 String name = policyName.getJsonString("serviceTypePolicyName").getString();
173 serviceTypeNamesList.add(name);
176 } catch (FileNotFoundException e) {
177 LOGGER.error("Exception Occured while initializing the JSONConfig file"+e);
180 if(inputStream != null){
183 if(jsonReader != null){
186 } catch (IOException e) {
187 LOGGER.error("Exception Occured while closing the File InputStream"+e);
193 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
194 LOGGER.debug("doPost");
196 // if request contains multipart-form-data
197 if (ServletFileUpload.isMultipartContent(request)) {
198 uploadFile(request, response);
200 // all other post request has json params in body
202 fileOperation(request, response);
204 } catch (Exception e) {
206 setError(e, response);
207 }catch(Exception e1){
208 LOGGER.error("Exception Occured"+e1);
213 //Set Error Message for Exception
214 private void setError(Exception t, HttpServletResponse response) throws IOException {
216 JSONObject responseJsonObject = error(t.getMessage());
217 response.setContentType(CONTENTTYPE);
218 PrintWriter out = response.getWriter();
219 out.print(responseJsonObject);
221 } catch (Exception x) {
222 LOGGER.error("Exception Occured"+x);
223 response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage());
227 //Policy Import Functionality
228 private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException {
231 Map<String, InputStream> files = new HashMap<>();
233 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
234 for (FileItem item : items) {
235 if (!item.isFormField()) {
236 // Process form file field (input type="file").
237 files.put(item.getName(), item.getInputStream());
238 if(item.getName().endsWith(".xls")){
239 OutputStream outputStream = null;
241 File file = new File(item.getName());
242 outputStream = new FileOutputStream(file);
243 IOUtils.copy(item.getInputStream(), outputStream);
244 outputStream.close();
245 newFile = file.toString();
246 PolicyExportAndImportController importController = new PolicyExportAndImportController();
247 importController.importRepositoryFile(newFile, request);
249 LOGGER.error("Upload error : " + e);
251 if(outputStream != null){
252 outputStream.close();
259 JSONObject responseJsonObject = null;
260 responseJsonObject = this.success();
261 response.setContentType(CONTENTTYPE);
262 PrintWriter out = response.getWriter();
263 out.print(responseJsonObject);
265 } catch (Exception e) {
266 LOGGER.debug("Cannot write file");
267 throw new ServletException("Cannot write file", e);
271 //File Operation Functionality
272 private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
273 JSONObject responseJsonObject = null;
275 StringBuilder sb = new StringBuilder();
276 BufferedReader br = request.getReader();
278 while ((str = br.readLine()) != null) {
282 JSONObject jObj = new JSONObject(sb.toString());
283 JSONObject params = jObj.getJSONObject("params");
284 Mode mode = Mode.valueOf(params.getString("mode"));
288 responseJsonObject = addFolder(params, request);
291 responseJsonObject = copy(params, request);
294 responseJsonObject = delete(params, request);
298 responseJsonObject = editFile(params);
301 responseJsonObject = list(params, request);
304 responseJsonObject = rename(params, request);
306 case DESCRIBEPOLICYFILE:
307 responseJsonObject = describePolicy(params);
310 responseJsonObject = switchVersion(params, request);
313 responseJsonObject = searchPolicyList(params, request);
316 throw new ServletException("not implemented");
318 if (responseJsonObject == null) {
319 responseJsonObject = error("generic error : responseJsonObject is null");
321 } catch (Exception e) {
322 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While doing File Operation" + e);
323 responseJsonObject = error(e.getMessage());
325 response.setContentType(CONTENTTYPE);
326 PrintWriter out = response.getWriter();
327 out.print(responseJsonObject);
331 private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) {
332 Set<String> scopes = null;
333 List<String> roles = null;
334 List<Object> policyData = new ArrayList<>();
335 JSONArray policyList = null;
336 if(params.has("policyList")){
337 policyList = (JSONArray) params.get("policyList");
339 PolicyController controller = getPolicyControllerInstance();
340 List<JSONObject> resultList = new ArrayList<>();
342 //Get the Login Id of the User from Request
343 String userId = UserUtils.getUserSession(request).getOrgUserId();
344 //Check if the Role and Scope Size are Null get the values from db.
345 List<Object> userRoles = controller.getRoles(userId);
346 roles = new ArrayList<>();
347 scopes = new HashSet<>();
348 for(Object role: userRoles){
349 Roles userRole = (Roles) role;
350 roles.add(userRole.getRole());
351 if(userRole.getScope() != null){
352 if(userRole.getScope().contains(",")){
353 String[] multipleScopes = userRole.getScope().split(",");
354 for(int i =0; i < multipleScopes.length; i++){
355 scopes.add(multipleScopes[i]);
358 scopes.add(userRole.getScope());
362 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
363 if(scopes.isEmpty()){
364 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
366 Set<String> tempScopes = scopes;
367 for(String scope : tempScopes){
368 List<Object> scopesList = queryPolicyEditorScopes(scope);
369 if(!scopesList.isEmpty()){
370 for(int i = 0; i < scopesList.size(); i++){
371 PolicyEditorScopes tempScope = (PolicyEditorScopes) scopesList.get(i);
372 scopes.add(tempScope.getScopeName());
377 if(policyList!= null){
378 for(int i = 0; i < policyList.length(); i++){
379 String policyName = policyList.get(i).toString().replace(".xml", "");
380 String version = policyName.substring(policyName.lastIndexOf(".")+1);
381 policyName = policyName.substring(0, policyName.lastIndexOf(".")).replace(".", File.separator);
382 if(policyName.contains("\\")){
383 policyName = policyName.replace("\\", "\\\\");
385 String policyVersionQuery = "From PolicyVersion where policy_name = :policyName and active_version = :version and id >0";
386 SimpleBindings pvParams = new SimpleBindings();
387 pvParams.put("policyName", policyName);
388 pvParams.put("version", version);
389 List<Object> activeData = controller.getDataByQuery(policyVersionQuery, pvParams);
390 if(!activeData.isEmpty()){
391 PolicyVersion policy = (PolicyVersion) activeData.get(0);
392 JSONObject el = new JSONObject();
393 el.put("name", policy.getPolicyName().replace(File.separator, "/"));
394 el.put("date", policy.getModifiedDate());
395 el.put("version", policy.getActiveVersion());
397 el.put("type", "file");
398 el.put("createdBy", getUserName(policy.getCreatedBy()));
399 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
404 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ){
405 policyData = controller.getData(PolicyVersion.class);
407 List<Object> filterdatas = controller.getData(PolicyVersion.class);
408 for(Object filter : filterdatas){
409 PolicyVersion filterdata = (PolicyVersion) filter;
411 String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator));
412 if(scopes.contains(scopeName)){
413 policyData.add(filterdata);
416 LOGGER.error("Exception occured while filtering policyversion data"+e);
421 if(!policyData.isEmpty()){
422 for(int i =0; i < policyData.size(); i++){
423 PolicyVersion policy = (PolicyVersion) policyData.get(i);
424 JSONObject el = new JSONObject();
425 el.put("name", policy.getPolicyName().replace(File.separator, "/"));
426 el.put("date", policy.getModifiedDate());
427 el.put("version", policy.getActiveVersion());
429 el.put("type", "file");
430 el.put("createdBy", getUserName(policy.getCreatedBy()));
431 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
437 LOGGER.error("Exception occured while reading policy Data from Policy Version table for Policy Search Data"+e);
440 return new JSONObject().put(RESULT, resultList);
443 //Switch Version Functionality
444 private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{
445 String path = params.getString("path");
446 String userId = null;
448 userId = UserUtils.getUserSession(request).getOrgUserId();
449 } catch (Exception e) {
450 LOGGER.error("Exception Occured while reading userid from cookie" +e);
453 String removeExtension = path.replace(".xml", "");
454 if(path.startsWith("/")){
455 policyName = removeExtension.substring(1, removeExtension.lastIndexOf("."));
457 policyName = removeExtension.substring(0, removeExtension.lastIndexOf("."));
460 String activePolicy = null;
461 PolicyController controller = getPolicyControllerInstance();
462 if(params.toString().contains("activeVersion")){
463 String activeVersion = params.getString("activeVersion");
464 String highestVersion = params.get("highestVersion").toString();
465 if(Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)){
466 return error("The Version shouldn't be greater than Highest Value");
468 activePolicy = policyName + "." + activeVersion + ".xml";
469 String dbCheckName = activePolicy.replace("/", ".");
470 if(dbCheckName.contains("Config_")){
471 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
472 }else if(dbCheckName.contains("Action_")){
473 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
474 }else if(dbCheckName.contains("Decision_")){
475 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
477 String[] splitDBCheckName = dbCheckName.split(":");
478 String peQuery = "FROM PolicyEntity where policyName = :splitDBCheckName_1 and scope = :splitDBCheckName_0";
479 SimpleBindings policyParams = new SimpleBindings();
480 policyParams.put("splitDBCheckName_1", splitDBCheckName[1]);
481 policyParams.put("splitDBCheckName_0", splitDBCheckName[0]);
482 List<Object> policyEntity = controller.getDataByQuery(peQuery, policyParams);
483 PolicyEntity pentity = (PolicyEntity) policyEntity.get(0);
484 if(pentity.isDeleted()){
485 return error("The Policy is Not Existing in Workspace");
487 if(policyName.contains("/")){
488 policyName = policyName.replace("/", File.separator);
490 policyName = policyName.substring(policyName.indexOf(File.separator)+1);
491 if(policyName.contains("\\")){
492 policyName = policyName.replace(File.separator, "\\");
494 policyName = splitDBCheckName[0].replace(".", File.separator)+File.separator+policyName;
495 String watchPolicyName = policyName;
496 if(policyName.contains("/")){
497 policyName = policyName.replace("/", File.separator);
499 if(policyName.contains("\\")){
500 policyName = policyName.replace("\\", "\\\\");
502 String query = "update PolicyVersion set active_version='"+activeVersion+"' where policy_name ='"+policyName+"' and id >0";
504 controller.executeQuery(query);
505 //Policy Notification
506 PolicyVersion entity = new PolicyVersion();
507 entity.setPolicyName(watchPolicyName);
508 entity.setActiveVersion(Integer.parseInt(activeVersion));
509 entity.setModifiedBy(userId);
510 controller.watchPolicyFunction(entity, activePolicy, "SwitchVersion");
515 return controller.switchVersionPolicyContent(policyName);
519 private JSONObject describePolicy(JSONObject params) throws ServletException{
520 JSONObject object = null;
521 String path = params.getString("path");
522 String policyName = null;
523 if(path.startsWith("/")){
524 path = path.substring(1);
525 policyName = path.substring(path.lastIndexOf("/") +1);
526 path = path.replace("/", ".");
528 path = path.replace("/", ".");
531 if(path.contains("Config_")){
532 path = path.replace(".Config_", ":Config_");
533 }else if(path.contains("Action_")){
534 path = path.replace(".Action_", ":Action_");
535 }else if(path.contains("Decision_")){
536 path = path.replace(".Decision_", ":Decision_");
538 PolicyController controller = getPolicyControllerInstance();
539 String[] split = path.split(":");
540 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
541 SimpleBindings peParams = new SimpleBindings();
542 peParams.put("split_1", split[1]);
543 peParams.put("split_0", split[0]);
544 List<Object> queryData = null;
546 queryData = controller.getDataByQuery(query, null);
548 queryData = controller.getDataByQuery(query, peParams);
550 if(!queryData.isEmpty()){
551 PolicyEntity entity = (PolicyEntity) queryData.get(0);
553 BufferedWriter bw = null;
555 temp = File.createTempFile(policyName, ".tmp");
556 bw = new BufferedWriter(new FileWriter(temp));
557 bw.write(entity.getPolicyData());
559 object = HumanPolicyComponent.DescribePolicy(temp);
560 } catch (IOException e) {
561 LOGGER.error("Exception Occured while Describing the Policy"+e);
569 } catch (IOException e) {
570 LOGGER.error("Exception Occured while Closing the File Writer"+e);
575 return error("Error Occured while Describing the Policy");
581 //Get the List of Policies and Scopes for Showing in Editor tab
582 private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException {
583 Set<String> scopes = null;
584 List<String> roles = null;
586 PolicyController controller = getPolicyControllerInstance();
587 //Get the Login Id of the User from Request
588 String testUserID = getTestUserId();
589 String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId();
590 //Check if the Role and Scope Size are Null get the values from db.
591 List<Object> userRoles = controller.getRoles(userId);
592 roles = new ArrayList<>();
593 scopes = new HashSet<>();
594 for(Object role: userRoles){
595 Roles userRole = (Roles) role;
596 roles.add(userRole.getRole());
597 if(userRole.getScope() != null){
598 if(userRole.getScope().contains(",")){
599 String[] multipleScopes = userRole.getScope().split(",");
600 for(int i =0; i < multipleScopes.length; i++){
601 scopes.add(multipleScopes[i]);
604 scopes.add(userRole.getScope());
609 List<JSONObject> resultList = new ArrayList<>();
610 boolean onlyFolders = params.getBoolean("onlyFolders");
611 String path = params.getString("path");
612 if(path.contains("..xml")){
613 path = path.replaceAll("..xml", "").trim();
616 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
617 if(scopes.isEmpty()){
618 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
620 if(!"/".equals(path)){
621 String tempScope = path.substring(1, path.length());
622 tempScope = tempScope.replace("/", File.separator);
623 scopes.add(tempScope);
628 if("/".equals(path)){
629 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
630 List<Object> scopesList = queryPolicyEditorScopes(null);
631 for(Object list : scopesList){
632 PolicyEditorScopes scope = (PolicyEditorScopes) list;
633 if(!(scope.getScopeName().contains(File.separator))){
634 JSONObject el = new JSONObject();
635 el.put("name", scope.getScopeName());
636 el.put("date", scope.getCreatedDate());
638 el.put("type", "dir");
639 el.put("createdBy", scope.getUserCreatedBy().getUserName());
640 el.put("modifiedBy", scope.getUserModifiedBy().getUserName());
644 }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){
645 for(Object scope : scopes){
646 JSONObject el = new JSONObject();
647 List<Object> scopesList = queryPolicyEditorScopes(scope.toString());
648 if(!scopesList.isEmpty()){
649 PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
650 el.put("name", scopeById.getScopeName());
651 el.put("date", scopeById.getCreatedDate());
653 el.put("type", "dir");
654 el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
655 el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
662 String scopeName = path.substring(path.indexOf("/") +1);
663 activePolicyList(scopeName, resultList, roles, scopes, onlyFolders);
664 } catch (Exception ex) {
665 LOGGER.error("Error Occured While reading Policy Files List"+ex );
669 return new JSONObject().put(RESULT, resultList);
670 } catch (Exception e) {
671 LOGGER.error("list", e);
672 return error(e.getMessage());
676 private List<Object> queryPolicyEditorScopes(String scopeName){
677 String scopeNamequery = "";
678 SimpleBindings params = new SimpleBindings();
679 if(scopeName == null){
680 scopeNamequery = "from PolicyEditorScopes";
682 scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
683 params.put("scopeName", scopeName + "%");
685 PolicyController controller = getPolicyControllerInstance();
686 List<Object> scopesList = null;
688 scopesList = controller.getDataByQuery(scopeNamequery, null);
690 scopesList = controller.getDataByQuery(scopeNamequery, params);
695 //Get Active Policy List based on Scope Selection form Policy Version table
696 private void activePolicyList(String scopeName, List<JSONObject> resultList, List<String> roles, Set<String> scopes, boolean onlyFolders){
697 PolicyController controller = getPolicyControllerInstance();
698 if(scopeName.contains("/")){
699 scopeName = scopeName.replace("/", File.separator);
701 if(scopeName.contains("\\")){
702 scopeName = scopeName.replace("\\", "\\\\\\\\");
704 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
705 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
707 SimpleBindings params = new SimpleBindings();
708 params.put("scopeName", scopeName + "%");
710 List<Object> activePolicies = null;
711 List<Object> scopesList = null;
713 activePolicies = controller.getDataByQuery(query, null);
714 scopesList = controller.getDataByQuery(scopeNamequery, null);
716 activePolicies = controller.getDataByQuery(query, params);
717 scopesList = controller.getDataByQuery(scopeNamequery, params);
719 for(Object list : scopesList){
720 PolicyEditorScopes scopeById = (PolicyEditorScopes) list;
721 String scope = scopeById.getScopeName();
722 if(scope.contains(File.separator)){
723 String checkScope = scope.substring(0, scope.lastIndexOf(File.separator));
724 if(scopeName.contains("\\\\")){
725 scopeName = scopeName.replace("\\\\", File.separator);
727 if(scope.contains(File.separator)){
728 scope = scope.substring(checkScope.length()+1);
729 if(scope.contains(File.separator)){
730 scope = scope.substring(0, scope.indexOf(File.separator));
733 if(scopeName.equalsIgnoreCase(checkScope)){
734 JSONObject el = new JSONObject();
735 el.put("name", scope);
736 el.put("date", scopeById.getModifiedDate());
738 el.put("type", "dir");
739 el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
740 el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
745 String scopeNameCheck = null;
746 for (Object list : activePolicies) {
747 PolicyVersion policy = (PolicyVersion) list;
748 String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator));
749 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
750 if((scopeName.contains("\\\\"))){
751 scopeNameCheck = scopeName.replace("\\\\", File.separator);
753 scopeNameCheck = scopeName;
755 if(scopeNameValue.equals(scopeNameCheck)){
756 JSONObject el = new JSONObject();
757 el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
758 el.put("date", policy.getModifiedDate());
759 el.put("version", policy.getActiveVersion());
761 el.put("type", "file");
762 el.put("createdBy", getUserName(policy.getCreatedBy()));
763 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
766 }else if(!scopes.isEmpty() && scopes.contains(scopeNameValue)){
767 JSONObject el = new JSONObject();
768 el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
769 el.put("date", policy.getModifiedDate());
770 el.put("version", policy.getActiveVersion());
772 el.put("type", "file");
773 el.put("createdBy", getUserName(policy.getCreatedBy()));
774 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
780 private String getUserName(String loginId){
781 PolicyController controller = getPolicyControllerInstance();
782 UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
783 if(userInfo == null){
786 return userInfo.getUserName();
790 private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
792 boolean isActive = false;
793 List<String> policyActiveInPDP = new ArrayList<>();
794 Set<String> scopeOfPolicyActiveInPDP = new HashSet<>();
795 String userId = UserUtils.getUserSession(request).getOrgUserId();
796 String oldPath = params.getString("path");
797 String newPath = params.getString("newPath");
798 oldPath = oldPath.substring(oldPath.indexOf("/")+1);
799 newPath = newPath.substring(newPath.indexOf("/")+1);
800 if(oldPath.endsWith(".xml")){
801 JSONObject result = policyRename(oldPath, newPath, userId);
802 if(!(Boolean)(result.getJSONObject("result").get("success"))){
806 String scopeName = oldPath;
807 String newScopeName = newPath;
808 if(scopeName.contains("/")){
809 scopeName = scopeName.replace("/", File.separator);
810 newScopeName = newScopeName.replace("/", File.separator);
812 if(scopeName.contains("\\")){
813 scopeName = scopeName.replace("\\", "\\\\\\\\");
814 newScopeName = newScopeName.replace("\\", "\\\\\\\\");
816 PolicyController controller = getPolicyControllerInstance();
817 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
818 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
819 SimpleBindings pvParams = new SimpleBindings();
820 pvParams.put("scopeName", scopeName + "%");
821 List<Object> activePolicies = controller.getDataByQuery(query, pvParams);
822 List<Object> scopesList = controller.getDataByQuery(scopeNamequery, pvParams);
823 for(Object object : activePolicies){
824 PolicyVersion activeVersion = (PolicyVersion) object;
825 String policyOldPath = activeVersion.getPolicyName().replace(File.separator, "/") + "." + activeVersion.getActiveVersion() + ".xml";
826 String policyNewPath = policyOldPath.replace(oldPath, newPath);
827 JSONObject result = policyRename(policyOldPath, policyNewPath, userId);
828 if(!(Boolean)(result.getJSONObject("result").get("success"))){
830 policyActiveInPDP.add(policyOldPath);
831 String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf("/"));
832 scopeOfPolicyActiveInPDP.add(scope.replace("/", File.separator));
835 boolean rename = false;
836 if(activePolicies.size() != policyActiveInPDP.size()){
840 UserInfo userInfo = new UserInfo();
841 userInfo.setUserLoginId(userId);
842 if(policyActiveInPDP.size() == 0){
843 renameScope(scopesList, scopeName, newScopeName, controller);
845 renameScope(scopesList, scopeName, newScopeName, controller);
846 for(String scope : scopeOfPolicyActiveInPDP){
847 PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes();
848 editorScopeEntity.setScopeName(scope.replace("\\", "\\\\\\\\"));
849 editorScopeEntity.setUserCreatedBy(userInfo);
850 editorScopeEntity.setUserModifiedBy(userInfo);
851 controller.saveData(editorScopeEntity);
855 return error("The Following policies rename failed. Since they are active in PDP Groups" +policyActiveInPDP);
859 } catch (Exception e) {
860 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
861 return error(e.getMessage());
865 private void renameScope(List<Object> scopesList, String scopeName, String newScopeName, PolicyController controller){
866 for(Object object : scopesList){
867 PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object;
868 if(scopeName.contains("\\\\\\\\")){
869 scopeName = scopeName.replace("\\\\\\\\", File.separator);
870 newScopeName = newScopeName.replace("\\\\\\\\", File.separator);
872 String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName);
873 editorScopeEntity.setScopeName(scope);
874 controller.updateData(editorScopeEntity);
878 private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
880 PolicyEntity entity = null;
881 PolicyController controller = getPolicyControllerInstance();
883 String policyVersionName = newPath.replace(".xml", "");
884 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")).replace("/", File.separator);
886 String oldpolicyVersionName = oldPath.replace(".xml", "");
887 String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf(".")).replace("/", File.separator);
889 String newpolicyName = newPath.replace("/", ".");
890 String newPolicyCheck = newpolicyName;
891 if(newPolicyCheck.contains("Config_")){
892 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
893 }else if(newPolicyCheck.contains("Action_")){
894 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
895 }else if(newPolicyCheck.contains("Decision_")){
896 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
898 String[] newPolicySplit = newPolicyCheck.split(":");
900 String orignalPolicyName = oldPath.replace("/", ".");
901 String oldPolicyCheck = orignalPolicyName;
902 if(oldPolicyCheck.contains("Config_")){
903 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
904 }else if(oldPolicyCheck.contains("Action_")){
905 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
906 }else if(oldPolicyCheck.contains("Decision_")){
907 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
909 String[] oldPolicySplit = oldPolicyCheck.split(":");
911 //Check PolicyEntity table with newPolicy Name
912 String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_1";
913 SimpleBindings policyParams = new SimpleBindings();
914 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
915 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
916 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
917 if(!queryData.isEmpty()){
918 entity = (PolicyEntity) queryData.get(0);
919 return error("Policy rename failed. Since, the policy with same name already exists.");
922 //Query the Policy Entity with oldPolicy Name
923 String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf("."));
924 String oldpolicyEntityquery = "FROM PolicyEntity where policyName like :policyEntityCheck and scope = :oldPolicySplit_0";
925 SimpleBindings params = new SimpleBindings();
926 params.put("policyEntityCheck", policyEntityCheck + "%");
927 params.put("oldPolicySplit_0", oldPolicySplit[0]);
928 List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery, params);
929 if(!oldEntityData.isEmpty()){
930 String groupQuery = "FROM PolicyGroupEntity where (";
931 SimpleBindings geParams = new SimpleBindings();
932 for(int i=0; i<oldEntityData.size(); i++){
933 entity = (PolicyEntity) oldEntityData.get(i);
935 groupQuery = groupQuery + "policyid = :policyId";
936 geParams.put("policyId", entity.getPolicyId());
938 groupQuery = groupQuery + " or policyid = :policyId" + i;
939 geParams.put("policyId" + i, entity.getPolicyId());
942 groupQuery = groupQuery + ")";
943 List<Object> groupEntityData = controller.getDataByQuery(groupQuery, geParams);
944 if(groupEntityData.size() > 0){
945 return error("Policy rename failed. Since the policy or its version is active in PDP Groups.");
947 for(int i=0; i<oldEntityData.size(); i++){
948 entity = (PolicyEntity) oldEntityData.get(i);
949 checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0] , newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
952 return error("Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin.");
956 } catch (Exception e) {
957 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
958 return error(e.getMessage());
962 private JSONObject checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, String oldScope, String removeoldPolicyExtension,
963 String policyName, String newpolicyName, String oldpolicyName, String userId) throws ServletException{
965 ConfigurationDataEntity configEntity = entity.getConfigurationData();
966 ActionBodyEntity actionEntity = entity.getActionBodyEntity();
967 PolicyController controller = getPolicyControllerInstance();
969 String oldPolicyNameWithoutExtension = removeoldPolicyExtension;
970 String newPolicyNameWithoutExtension = removenewPolicyExtension;
971 if(removeoldPolicyExtension.endsWith(".xml")){
972 oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf("."));
973 newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf("."));
975 entity.setPolicyName(entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
976 entity.setPolicyData(entity.getPolicyData().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
977 entity.setScope(newScope);
978 entity.setModifiedBy(userId);
979 if(newpolicyName.contains("Config_")){
980 String oldConfigurationName = configEntity.getConfigurationName();
981 configEntity.setConfigurationName(configEntity.getConfigurationName().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
982 controller.updateData(configEntity);
983 String newConfigurationName = configEntity.getConfigurationName();
984 File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName);
986 File renamefile = new File(PolicyController.getConfigHome() + File.separator + newConfigurationName);
987 file.renameTo(renamefile);
989 }else if(newpolicyName.contains("Action_")){
990 String oldConfigurationName = actionEntity.getActionBodyName();
991 actionEntity.setActionBody(actionEntity.getActionBody().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
992 controller.updateData(actionEntity);
993 String newConfigurationName = actionEntity.getActionBodyName();
994 File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName);
996 File renamefile = new File(PolicyController.getActionHome() + File.separator + newConfigurationName);
997 file.renameTo(renamefile);
1000 controller.updateData(entity);
1002 PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldpolicyName);
1003 versionEntity.setPolicyName(policyName);
1004 versionEntity.setModifiedBy(userId);
1005 controller.updateData(versionEntity);
1006 String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator)+1);
1007 String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
1008 if(movePolicyCheck.equals(moveOldPolicyCheck)){
1009 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move");
1011 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename");
1014 } catch (Exception e) {
1015 LOGGER.error("Exception Occured"+e);
1016 return error(e.getMessage());
1020 private JSONObject cloneRecord(String newpolicyName, String oldScope, String removeoldPolicyExtension, String newScope, String removenewPolicyExtension, PolicyEntity entity, String userId) throws ServletException{
1021 FileWriter fw = null;
1022 String queryEntityName = null;
1023 PolicyController controller = getPolicyControllerInstance();
1024 PolicyEntity cloneEntity = new PolicyEntity();
1025 cloneEntity.setPolicyName(newpolicyName);
1026 removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
1027 removenewPolicyExtension = removenewPolicyExtension.replace(".xml", "");
1028 cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope+"."+removeoldPolicyExtension, newScope+"."+removenewPolicyExtension));
1029 cloneEntity.setScope(entity.getScope());
1030 String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
1031 String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
1032 if(newpolicyName.contains("Config_")){
1033 ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
1034 configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1035 queryEntityName = configurationDataEntity.getConfigurationName();
1036 configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody());
1037 configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType());
1038 configurationDataEntity.setDeleted(false);
1039 configurationDataEntity.setCreatedBy(userId);
1040 configurationDataEntity.setModifiedBy(userId);
1041 controller.saveData(configurationDataEntity);
1042 ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
1043 cloneEntity.setConfigurationData(configEntiy);
1044 String newConfigurationName = configEntiy.getConfigurationName();
1046 fw = new FileWriter(PolicyController.getConfigHome() + File.separator + newConfigurationName);
1047 BufferedWriter bw = new BufferedWriter(fw);
1048 bw.write(configEntiy.getConfigBody());
1050 } catch (IOException e) {
1051 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1053 }else if(newpolicyName.contains("Action_")){
1054 ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
1055 actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1056 queryEntityName = actionBodyEntity.getActionBodyName();
1057 actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody());
1058 actionBodyEntity.setDeleted(false);
1059 actionBodyEntity.setCreatedBy(userId);
1060 actionBodyEntity.setModifiedBy(userId);
1061 controller.saveData(actionBodyEntity);
1062 ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class, "actionBodyName", queryEntityName);
1063 cloneEntity.setActionBodyEntity(actionEntiy);
1064 String newConfigurationName = actionEntiy.getActionBodyName();
1066 fw = new FileWriter(PolicyController.getActionHome() + File.separator + newConfigurationName);
1067 BufferedWriter bw = new BufferedWriter(fw);
1068 bw.write(actionEntiy.getActionBody());
1070 } catch (IOException e) {
1071 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1077 } catch (IOException e) {
1078 LOGGER.error("Exception Occured While closing the File input stream"+e);
1081 cloneEntity.setDeleted(entity.isDeleted());
1082 cloneEntity.setCreatedBy(userId);
1083 cloneEntity.setModifiedBy(userId);
1084 controller.saveData(cloneEntity);
1090 private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
1092 String userId = UserUtils.getUserSession(request).getOrgUserId();
1093 String oldPath = params.getString("path");
1094 String newPath = params.getString("newPath");
1095 oldPath = oldPath.substring(oldPath.indexOf("/")+1);
1096 newPath = newPath.substring(newPath.indexOf("/")+1);
1098 String policyVersionName = newPath.replace(".xml", "");
1099 String version = policyVersionName.substring(policyVersionName.indexOf(".")+1);
1100 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")).replace("/", File.separator);
1102 String newpolicyName = newPath.replace("/", ".");
1104 String orignalPolicyName = oldPath.replace("/", ".");
1106 String newPolicyCheck = newpolicyName;
1107 if(newPolicyCheck.contains("Config_")){
1108 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
1109 }else if(newPolicyCheck.contains("Action_")){
1110 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
1111 }else if(newPolicyCheck.contains("Decision_")){
1112 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
1114 String[] newPolicySplit = newPolicyCheck.split(":");
1116 String oldPolicyCheck = orignalPolicyName;
1117 if(oldPolicyCheck.contains("Config_")){
1118 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
1119 }else if(oldPolicyCheck.contains("Action_")){
1120 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
1121 }else if(oldPolicyCheck.contains("Decision_")){
1122 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
1124 String[] oldPolicySplit = oldPolicyCheck.split(":");
1126 PolicyController controller = getPolicyControllerInstance();
1128 PolicyEntity entity = null;
1129 boolean success = false;
1131 //Check PolicyEntity table with newPolicy Name
1132 String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
1133 SimpleBindings policyParams = new SimpleBindings();
1134 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
1135 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
1136 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
1137 if(!queryData.isEmpty()){
1138 return error("Policy already exists with same name");
1141 //Query the Policy Entity with oldPolicy Name
1142 policyEntityquery = "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0";
1143 SimpleBindings peParams = new SimpleBindings();
1144 peParams.put("oldPolicySplit_1", oldPolicySplit[1]);
1145 peParams.put("oldPolicySplit_0", oldPolicySplit[0]);
1146 queryData = controller.getDataByQuery(policyEntityquery, peParams);
1147 if(!queryData.isEmpty()){
1148 entity = (PolicyEntity) queryData.get(0);
1151 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId);
1156 PolicyVersion entityItem = new PolicyVersion();
1157 entityItem.setActiveVersion(Integer.parseInt(version));
1158 entityItem.setHigherVersion(Integer.parseInt(version));
1159 entityItem.setPolicyName(policyName);
1160 entityItem.setCreatedBy(userId);
1161 entityItem.setModifiedBy(userId);
1162 controller.saveData(entityItem);
1165 LOGGER.debug("copy from: {} to: {}" + oldPath +newPath);
1168 } catch (Exception e) {
1169 LOGGER.error("copy", e);
1170 return error(e.getMessage());
1174 //Delete Policy or Scope Functionality
1175 private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
1176 PolicyController controller = getPolicyControllerInstance();
1177 PolicyRestController restController = new PolicyRestController();
1178 PolicyEntity policyEntity = null;
1179 String policyNamewithoutExtension;
1181 String userId = UserUtils.getUserSession(request).getOrgUserId();
1182 String deleteVersion = "";
1183 String path = params.getString("path");
1184 LOGGER.debug("delete {}" +path);
1185 if(params.has("deleteVersion")){
1186 deleteVersion = params.getString("deleteVersion");
1188 path = path.substring(path.indexOf("/")+1);
1189 String policyNamewithExtension = path.replace("/", File.separator);
1190 String policyVersionName = policyNamewithExtension.replace(".xml", "");
1192 SimpleBindings policyParams = new SimpleBindings();
1193 if(path.endsWith(".xml")){
1194 policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf("."));
1195 policyNamewithoutExtension = policyNamewithoutExtension.replace(File.separator, ".");
1196 String splitPolicyName = null;
1197 if(policyNamewithoutExtension.contains("Config_")){
1198 splitPolicyName = policyNamewithoutExtension.replace(".Config_", ":Config_");
1199 }else if(policyNamewithoutExtension.contains("Action_")){
1200 splitPolicyName = policyNamewithoutExtension.replace(".Action_", ":Action_");
1201 }else if(policyNamewithoutExtension.contains("Decision_")){
1202 splitPolicyName = policyNamewithoutExtension.replace(".Decision_", ":Decision_");
1204 String[] split = splitPolicyName.split(":");
1205 query = "FROM PolicyEntity where policyName like split_1 and scope = split_0";
1206 policyParams.put("split_1", split[1] + "%");
1207 policyParams.put("split_0", split[0]);
1209 policyNamewithoutExtension = path.replace(File.separator, ".");
1210 query = "FROM PolicyEntity where scope like :policyNamewithoutExtension";
1211 policyParams.put("policyNamewithoutExtension", policyNamewithoutExtension + "%");
1214 List<Object> policyEntityobjects = controller.getDataByQuery(query, policyParams);
1215 String activePolicyName = null;
1216 boolean pdpCheck = false;
1217 if(path.endsWith(".xml")){
1218 policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator);
1219 int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf(".")+1));
1220 if("ALL".equals(deleteVersion)){
1221 if(!policyEntityobjects.isEmpty()){
1222 for(Object object : policyEntityobjects){
1223 policyEntity = (PolicyEntity) object;
1224 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyId";
1225 SimpleBindings pgeParams = new SimpleBindings();
1226 pgeParams.put("policyId", policyEntity.getPolicyId());
1227 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, pgeParams);
1228 if(!groupobject.isEmpty()){
1230 activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName();
1232 //Delete the entity from Elastic Search Database
1233 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1234 restController.deleteElasticData(searchFileName);
1235 //Delete the entity from Policy Entity table
1236 controller.deleteData(policyEntity);
1237 if(policyNamewithoutExtension.contains("Config_")){
1238 controller.deleteData(policyEntity.getConfigurationData());
1239 }else if(policyNamewithoutExtension.contains("Action_")){
1240 controller.deleteData(policyEntity.getActionBodyEntity());
1245 //Policy Notification
1246 PolicyVersion versionEntity = new PolicyVersion();
1247 versionEntity.setPolicyName(policyNamewithoutExtension);
1248 versionEntity.setModifiedBy(userId);
1249 controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll");
1251 //Delete from policyVersion table
1252 String getActivePDPPolicyVersion = activePolicyName.replace(".xml", "");
1253 getActivePDPPolicyVersion = getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf(".")+1);
1254 String policyVersionQuery = "update PolicyVersion set active_version='"+getActivePDPPolicyVersion+"' , highest_version='"+getActivePDPPolicyVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1255 if(policyVersionQuery != null){
1256 controller.executeQuery(policyVersionQuery);
1258 return error("Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "+activePolicyName);
1260 //No Active Policy in PDP. So, deleting all entries from policyVersion table
1261 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1262 if(policyVersionQuery != null){
1263 controller.executeQuery(policyVersionQuery);
1266 }else if("CURRENT".equals(deleteVersion)){
1267 String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1);
1268 String currentVersionScope = policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator)).replace(File.separator, ".");
1269 query = "FROM PolicyEntity where policyName = :currentVersionPolicyName and scope = :currentVersionScope";
1271 SimpleBindings peParams = new SimpleBindings();
1272 peParams.put("currentVersionPolicyName", currentVersionPolicyName);
1273 peParams.put("currentVersionScope", currentVersionScope);
1275 List<Object> policyEntitys = controller.getDataByQuery(query, peParams);
1276 if(!policyEntitys.isEmpty()){
1277 policyEntity = (PolicyEntity) policyEntitys.get(0);
1279 if(policyEntity != null){
1280 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId and policyid > 0";
1281 SimpleBindings geParams = new SimpleBindings();
1282 geParams.put("policyEntityId", policyEntity.getPolicyId());
1283 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1284 if(groupobject.isEmpty()){
1285 //Delete the entity from Elastic Search Database
1286 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1287 restController.deleteElasticData(searchFileName);
1288 //Delete the entity from Policy Entity table
1289 controller.deleteData(policyEntity);
1290 if(policyNamewithoutExtension.contains("Config_")){
1291 controller.deleteData(policyEntity.getConfigurationData());
1292 }else if(policyNamewithoutExtension.contains("Action_")){
1293 controller.deleteData(policyEntity.getActionBodyEntity());
1297 int highestVersion = 0;
1298 if(!policyEntityobjects.isEmpty()){
1299 for(Object object : policyEntityobjects){
1300 policyEntity = (PolicyEntity) object;
1301 String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
1302 int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf(".")+1));
1303 if(policyEntityVersion > highestVersion && policyEntityVersion != version){
1304 highestVersion = policyEntityVersion;
1309 //Policy Notification
1310 PolicyVersion entity = new PolicyVersion();
1311 entity.setPolicyName(policyNamewithoutExtension);
1312 entity.setActiveVersion(highestVersion);
1313 entity.setModifiedBy(userId);
1314 controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne");
1316 String updatequery = "update PolicyVersion set active_version='"+highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"'";
1317 controller.executeQuery(updatequery);
1319 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1320 if(policyVersionQuery != null){
1321 controller.executeQuery(policyVersionQuery);
1325 return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'");
1330 List<String> activePoliciesInPDP = new ArrayList<String>();
1331 if(!policyEntityobjects.isEmpty()){
1332 for(Object object : policyEntityobjects){
1333 policyEntity = (PolicyEntity) object;
1334 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId";
1335 SimpleBindings geParams = new SimpleBindings();
1336 geParams.put("policyEntityId", policyEntity.getPolicyId());
1337 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1338 if(!groupobject.isEmpty()){
1340 activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName());
1342 //Delete the entity from Elastic Search Database
1343 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1344 restController.deleteElasticData(searchFileName);
1345 //Delete the entity from Policy Entity table
1346 controller.deleteData(policyEntity);
1347 policyNamewithoutExtension = policyEntity.getPolicyName();
1348 if(policyNamewithoutExtension.contains("Config_")){
1349 controller.deleteData(policyEntity.getConfigurationData());
1350 }else if(policyNamewithoutExtension.contains("Action_")){
1351 controller.deleteData(policyEntity.getActionBodyEntity());
1355 //Delete from policyVersion and policyEditor Scope table
1356 String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1357 controller.executeQuery(policyVersionQuery);
1359 //Policy Notification
1360 PolicyVersion entity = new PolicyVersion();
1361 entity.setPolicyName(path);
1362 entity.setModifiedBy(userId);
1363 controller.watchPolicyFunction(entity, path, "DeleteScope");
1365 //Add Active Policies List to PolicyVersionTable
1366 for(int i =0; i < activePoliciesInPDP.size(); i++){
1367 String activePDPPolicyName = activePoliciesInPDP.get(i).replace(".xml", "");
1368 int activePDPPolicyVersion = Integer.parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf(".")+1));
1369 activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf(".")).replace(".", File.separator);
1370 PolicyVersion insertactivePDPVersion = new PolicyVersion();
1371 insertactivePDPVersion.setPolicyName(activePDPPolicyName);
1372 insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion);
1373 insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion);
1374 insertactivePDPVersion.setCreatedBy(userId);
1375 insertactivePDPVersion.setModifiedBy(userId);
1376 controller.saveData(insertactivePDPVersion);
1379 return error("All the Policies has been deleted in Scope. Except the following list of Policies:"+activePoliciesInPDP);
1381 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1382 controller.executeQuery(policyScopeQuery);
1385 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1386 controller.executeQuery(policyScopeQuery);
1390 } catch (Exception e) {
1391 LOGGER.error("delete", e);
1392 return error(e.getMessage());
1397 private JSONObject editFile(JSONObject params) throws ServletException {
1400 PolicyController controller = getPolicyControllerInstance();
1401 String mode = params.getString("mode");
1402 String path = params.getString("path");
1403 LOGGER.debug("editFile path: {}"+ path);
1405 String domain = path.substring(1, path.lastIndexOf("/"));
1406 domain = domain.replace("/", ".");
1408 path = path.substring(1);
1409 path = path.replace("/", ".");
1410 String dbCheckName = path;
1411 if(dbCheckName.contains("Config_")){
1412 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
1413 }else if(dbCheckName.contains("Action_")){
1414 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
1415 }else if(dbCheckName.contains("Decision_")){
1416 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
1419 String[] split = dbCheckName.split(":");
1420 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
1421 SimpleBindings peParams = new SimpleBindings();
1422 peParams.put("split_1", split[1]);
1423 peParams.put("split_0", split[0]);
1424 List<Object> queryData = null;
1426 queryData = controller.getDataByQuery(query, null);
1428 queryData = controller.getDataByQuery(query, peParams);
1430 PolicyEntity entity = (PolicyEntity) queryData.get(0);
1431 InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
1434 Object policy = XACMLPolicyScanner.readPolicy(stream);
1435 PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
1436 policyAdapter.setData(policy);
1438 if("viewPolicy".equalsIgnoreCase(mode)){
1439 policyAdapter.setReadOnly(true);
1440 policyAdapter.setEditPolicy(false);
1442 policyAdapter.setReadOnly(false);
1443 policyAdapter.setEditPolicy(true);
1445 policyAdapter.setDomain(domain);
1446 policyAdapter.setDomainDir(domain);
1447 policyAdapter.setPolicyData(policy);
1448 String policyName = path.replace(".xml", "");
1449 policyName = policyName.substring(0, policyName.lastIndexOf("."));
1450 policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf(".")+1));
1452 PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance();
1453 setpolicyAdapter.configure(policyAdapter,entity);
1455 policyAdapter.setParentPath(null);
1456 ObjectMapper mapper = new ObjectMapper();
1457 String json = mapper.writeValueAsString(policyAdapter);
1458 JsonNode jsonNode = mapper.readTree(json);
1460 return new JSONObject().put(RESULT, jsonNode);
1461 } catch (Exception e) {
1462 LOGGER.error("editFile", e);
1463 return error(e.getMessage());
1468 private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
1469 PolicyController controller = getPolicyControllerInstance();
1472 String userId = UserUtils.getUserSession(request).getOrgUserId();
1473 String path = params.getString("path");
1475 if(params.has("subScopename")){
1476 if(!params.getString("subScopename").equals("")){
1477 name = params.getString("path").replace("/", File.separator) + File.separator +params.getString("subScopename");
1480 name = params.getString("name");
1482 }catch(Exception e){
1483 name = params.getString("name");
1484 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e);
1486 String validateName;
1487 if(name.contains(File.separator)){
1488 validateName = name.substring(name.lastIndexOf(File.separator)+1);
1490 validateName = name;
1492 if(!name.isEmpty()){
1493 String validate = PolicyUtils.policySpecialCharValidator(validateName);
1494 if(!validate.contains("success")){
1495 return error(validate);
1498 LOGGER.debug("addFolder path: {} name: {}" + path +name);
1499 if(!name.equals("")){
1500 if(name.startsWith(File.separator)){
1501 name = name.substring(1);
1503 PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, "scopeName", name);
1505 UserInfo userInfo = new UserInfo();
1506 userInfo.setUserLoginId(userId);
1507 PolicyEditorScopes newScope = new PolicyEditorScopes();
1508 newScope.setScopeName(name);
1509 newScope.setUserCreatedBy(userInfo);
1510 newScope.setUserModifiedBy(userInfo);
1511 controller.saveData(newScope);
1513 return error("Scope Already Exists");
1517 } catch (Exception e) {
1518 LOGGER.error("addFolder", e);
1519 return error(e.getMessage());
1523 //Return Error Object
1524 private JSONObject error(String msg) throws ServletException {
1526 JSONObject result = new JSONObject();
1527 result.put("success", false);
1528 result.put("error", msg);
1529 return new JSONObject().put(RESULT, result);
1530 } catch (JSONException e) {
1531 throw new ServletException(e);
1535 //Return Success Object
1536 private JSONObject success() throws ServletException {
1538 JSONObject result = new JSONObject();
1539 result.put("success", true);
1540 result.put("error", (Object) null);
1541 return new JSONObject().put(RESULT, result);
1542 } catch (JSONException e) {
1543 throw new ServletException(e);
1547 private PolicyController getPolicyControllerInstance(){
1548 return policyController != null ? getPolicyController() : new PolicyController();
1551 public String getTestUserId() {
1555 public static void setTestUserId(String testUserId) {
1556 PolicyManagerServlet.testUserId = testUserId;