2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 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.FileOutputStream;
29 import java.io.FileWriter;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.io.OutputStream;
33 import java.io.PrintWriter;
34 import java.nio.charset.StandardCharsets;
35 import java.nio.file.Files;
36 import java.nio.file.Path;
37 import java.nio.file.Paths;
38 import java.util.ArrayList;
39 import java.util.Date;
40 import java.util.HashMap;
41 import java.util.HashSet;
42 import java.util.List;
46 import javax.json.Json;
47 import javax.json.JsonArray;
48 import javax.json.JsonReader;
49 import javax.script.SimpleBindings;
50 import javax.servlet.ServletConfig;
51 import javax.servlet.ServletException;
52 import javax.servlet.annotation.WebInitParam;
53 import javax.servlet.annotation.WebServlet;
54 import javax.servlet.http.HttpServlet;
55 import javax.servlet.http.HttpServletRequest;
56 import javax.servlet.http.HttpServletResponse;
58 import org.apache.commons.compress.utils.IOUtils;
59 import org.apache.commons.fileupload.FileItem;
60 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
61 import org.apache.commons.fileupload.servlet.ServletFileUpload;
62 import org.apache.http.HttpStatus;
63 import org.json.JSONArray;
64 import org.json.JSONException;
65 import org.json.JSONObject;
66 import org.onap.policy.common.logging.flexlogger.FlexLogger;
67 import org.onap.policy.common.logging.flexlogger.Logger;
68 import org.onap.policy.components.HumanPolicyComponent;
69 import org.onap.policy.controller.PolicyController;
70 import org.onap.policy.controller.PolicyExportAndImportController;
71 import org.onap.policy.rest.XACMLRest;
72 import org.onap.policy.rest.XACMLRestProperties;
73 import org.onap.policy.rest.adapter.PolicyRestAdapter;
74 import org.onap.policy.rest.jpa.ActionBodyEntity;
75 import org.onap.policy.rest.jpa.ConfigurationDataEntity;
76 import org.onap.policy.rest.jpa.PolicyEditorScopes;
77 import org.onap.policy.rest.jpa.PolicyEntity;
78 import org.onap.policy.rest.jpa.PolicyVersion;
79 import org.onap.policy.rest.jpa.UserInfo;
80 import org.onap.policy.utils.PolicyUtils;
81 import org.onap.policy.utils.UserUtils.Pair;
82 import org.onap.policy.xacml.api.XACMLErrorConstants;
83 import org.onap.policy.xacml.util.XACMLPolicyScanner;
84 import org.onap.portalsdk.core.web.support.UserUtils;
86 import com.att.research.xacml.util.XACMLProperties;
87 import com.fasterxml.jackson.databind.JsonNode;
88 import com.fasterxml.jackson.databind.ObjectMapper;
91 @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.") })
92 public class PolicyManagerServlet extends HttpServlet {
93 private static final Logger LOGGER = FlexLogger.getLogger(PolicyManagerServlet.class);
94 private static final long serialVersionUID = -8453502699403909016L;
97 LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT, SEARCHLIST
100 private static PolicyController policyController;
101 public synchronized PolicyController getPolicyController() {
102 return policyController;
105 public static synchronized void setPolicyController(PolicyController policyController) {
106 PolicyManagerServlet.policyController = policyController;
109 private static String CONTENTTYPE = "application/json";
110 private static String SUPERADMIN = "super-admin";
111 private static String SUPEREDITOR = "super-editor";
112 private static String SUPERGUEST = "super-guest";
113 private static String ADMIN = "admin";
114 private static String EDITOR = "editor";
115 private static String GUEST = "guest";
116 private static String RESULT = "result";
118 private static Path closedLoopJsonLocation;
119 private static JsonArray policyNames;
120 private static String testUserId = null;
122 public static JsonArray getPolicyNames() {
126 public static void setPolicyNames(JsonArray policyNames) {
127 PolicyManagerServlet.policyNames = policyNames;
130 private static List<String> serviceTypeNamesList = new ArrayList<>();
132 public static List<String> getServiceTypeNamesList() {
133 return serviceTypeNamesList;
137 public void init(ServletConfig servletConfig) throws ServletException {
138 super.init(servletConfig);
140 // Common initialization
142 XACMLRest.xacmlInit(servletConfig);
144 //Initialize ClosedLoop JSON
146 PolicyManagerServlet.initializeJSONLoad();
149 protected static void initializeJSONLoad() {
150 closedLoopJsonLocation = Paths.get(XACMLProperties
151 .getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP));
152 String location = closedLoopJsonLocation.toString();
153 if (! location.endsWith("json")) {
154 LOGGER.warn("JSONConfig file does not end with extension .json");
157 try (FileInputStream inputStream = new FileInputStream(location);
158 JsonReader jsonReader = Json.createReader(inputStream)) {
159 policyNames = jsonReader.readArray();
160 serviceTypeNamesList = new ArrayList<>();
161 for (int i = 0; i < policyNames.size(); i++) {
162 javax.json.JsonObject policyName = policyNames.getJsonObject(i);
163 String name = policyName.getJsonString("serviceTypePolicyName").getString();
164 serviceTypeNamesList.add(name);
166 } catch (IOException e) {
167 LOGGER.error("Exception Occured while initializing the JSONConfig file"+e);
172 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
173 LOGGER.debug("doPost");
175 // if request contains multipart-form-data
176 if (ServletFileUpload.isMultipartContent(request)) {
177 uploadFile(request, response);
179 // all other post request has json params in body
181 fileOperation(request, response);
183 } catch (Exception e) {
185 setError(e, response);
186 }catch(Exception e1){
187 LOGGER.error("Exception Occured"+e1);
192 //Set Error Message for Exception
193 private void setError(Exception t, HttpServletResponse response) throws IOException {
195 JSONObject responseJsonObject = error(t.getMessage());
196 response.setContentType(CONTENTTYPE);
197 PrintWriter out = response.getWriter();
198 out.print(responseJsonObject);
200 } catch (Exception x) {
201 LOGGER.error("Exception Occured"+x);
202 response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage());
206 //Policy Import Functionality
207 private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException {
210 Map<String, InputStream> files = new HashMap<>();
212 List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
213 for (FileItem item : items) {
214 if (!item.isFormField()) {
215 // Process form file field (input type="file").
216 files.put(item.getName(), item.getInputStream());
217 if(item.getName().endsWith(".xls") && item.getSize() <= PolicyController.getFileSizeLimit()){
218 File file = new File(item.getName());
219 try (OutputStream outputStream = new FileOutputStream(file);)
221 IOUtils.copy(item.getInputStream(), outputStream);
222 newFile = file.toString();
223 PolicyExportAndImportController importController = new PolicyExportAndImportController();
224 importController.importRepositoryFile(newFile, request);
226 LOGGER.error("Upload error : " + e);
229 else if (!item.getName().endsWith(".xls")) {
230 LOGGER.error("Non .xls filetype uploaded: " + item.getName());
232 else { //uploaded file size is greater than allowed
233 LOGGER.error("Upload file size limit exceeded! File size (Bytes) is: " + item.getSize());
238 JSONObject responseJsonObject;
239 responseJsonObject = this.success();
240 response.setContentType(CONTENTTYPE);
241 PrintWriter out = response.getWriter();
242 out.print(responseJsonObject);
244 } catch (Exception e) {
245 LOGGER.debug("Cannot write file");
246 throw new ServletException("Cannot write file", e);
250 //File Operation Functionality
251 private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
252 JSONObject responseJsonObject = null;
254 StringBuilder sb = new StringBuilder();
255 BufferedReader br = request.getReader();
257 while ((str = br.readLine()) != null) {
261 JSONObject jObj = new JSONObject(sb.toString());
262 JSONObject params = jObj.getJSONObject("params");
263 Mode mode = Mode.valueOf(params.getString("mode"));
265 String userId = UserUtils.getUserSession(request).getOrgUserId();
266 LOGGER.info("****************************************Logging UserID while doing actions on Editor tab*******************************************");
267 LOGGER.info("UserId: " + userId + "Action Mode: "+ mode.toString() + "Action Params: "+params.toString());
268 LOGGER.info("***********************************************************************************************************************************");
273 responseJsonObject = addFolder(params, request);
276 responseJsonObject = copy(params, request);
279 responseJsonObject = delete(params, request);
283 responseJsonObject = editFile(params);
286 responseJsonObject = list(params, request);
289 responseJsonObject = rename(params, request);
291 case DESCRIBEPOLICYFILE:
292 responseJsonObject = describePolicy(params);
295 responseJsonObject = switchVersion(params, request);
298 responseJsonObject = searchPolicyList(params, request);
301 throw new ServletException("not implemented");
303 if (responseJsonObject == null) {
304 responseJsonObject = error("generic error : responseJsonObject is null");
306 } catch (Exception e) {
307 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While doing File Operation" + e);
308 responseJsonObject = error(e.getMessage());
310 response.setContentType(CONTENTTYPE);
311 PrintWriter out = response.getWriter();
312 out.print(responseJsonObject);
316 private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) {
319 List<Object> policyData = new ArrayList<>();
320 JSONArray policyList = null;
321 if(params.has("policyList")){
322 policyList = (JSONArray) params.get("policyList");
324 PolicyController controller = getPolicyControllerInstance();
325 List<JSONObject> resultList = new ArrayList<>();
327 //Get the Login Id of the User from Request
328 String userId = UserUtils.getUserSession(request).getOrgUserId();
329 List<Object> userRoles = controller.getRoles(userId);
330 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
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");
337 Set<String> tempScopes = scopes;
338 for(String scope : tempScopes){
339 List<Object> scopesList = queryPolicyEditorScopes(scope);
340 if(!scopesList.isEmpty()){
341 for(int i = 0; i < scopesList.size(); i++){
342 PolicyEditorScopes tempScope = (PolicyEditorScopes) scopesList.get(i);
343 scopes.add(tempScope.getScopeName());
348 if(policyList!= null){
349 for(int i = 0; i < policyList.length(); i++){
350 String policyName = policyList.get(i).toString().replace(".xml", "");
351 String version = policyName.substring(policyName.lastIndexOf('.')+1);
352 policyName = policyName.substring(0, policyName.lastIndexOf('.')).replace(".", File.separator);
353 if(policyName.contains("\\")){
354 policyName = policyName.replace("\\", "\\\\");
356 String policyVersionQuery = "From PolicyVersion where policy_name = :policyName and active_version = :version and id >0";
357 SimpleBindings pvParams = new SimpleBindings();
358 pvParams.put("policyName", policyName);
359 pvParams.put("version", version);
360 List<Object> activeData = controller.getDataByQuery(policyVersionQuery, pvParams);
361 if(!activeData.isEmpty()){
362 PolicyVersion policy = (PolicyVersion) activeData.get(0);
363 JSONObject el = new JSONObject();
364 el.put("name", policy.getPolicyName().replace(File.separator, "/"));
365 el.put("date", policy.getModifiedDate());
366 el.put("version", policy.getActiveVersion());
368 el.put("type", "file");
369 el.put("createdBy", getUserName(policy.getCreatedBy()));
370 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
375 if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ){
376 policyData = controller.getData(PolicyVersion.class);
378 List<Object> filterdatas = controller.getData(PolicyVersion.class);
379 for(Object filter : filterdatas){
380 PolicyVersion filterdata = (PolicyVersion) filter;
382 String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator));
383 if(scopes.contains(scopeName)){
384 policyData.add(filterdata);
387 LOGGER.error("Exception occured while filtering policyversion data"+e);
392 if(!policyData.isEmpty()){
393 for(int i =0; i < policyData.size(); i++){
394 PolicyVersion policy = (PolicyVersion) policyData.get(i);
395 JSONObject el = new JSONObject();
396 el.put("name", policy.getPolicyName().replace(File.separator, "/"));
397 el.put("date", policy.getModifiedDate());
398 el.put("version", policy.getActiveVersion());
400 el.put("type", "file");
401 el.put("createdBy", getUserName(policy.getCreatedBy()));
402 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
408 LOGGER.error("Exception occured while reading policy Data from Policy Version table for Policy Search Data"+e);
411 return new JSONObject().put(RESULT, resultList);
414 //Switch Version Functionality
415 private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{
416 String path = params.getString("path");
417 String userId = null;
419 userId = UserUtils.getUserSession(request).getOrgUserId();
420 } catch (Exception e) {
421 LOGGER.error("Exception Occured while reading userid from cookie" +e);
424 String removeExtension = path.replace(".xml", "");
425 if(path.startsWith("/")){
426 policyName = removeExtension.substring(1, removeExtension.lastIndexOf('.'));
428 policyName = removeExtension.substring(0, removeExtension.lastIndexOf('.'));
432 PolicyController controller = getPolicyControllerInstance();
433 if(! params.toString().contains("activeVersion")){
434 return controller.switchVersionPolicyContent(policyName);
436 String activeVersion = params.getString("activeVersion");
437 String highestVersion = params.get("highestVersion").toString();
438 if(Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)){
439 return error("The Version shouldn't be greater than Highest Value");
441 activePolicy = policyName + "." + activeVersion + ".xml";
442 String dbCheckName = activePolicy.replace("/", ".");
443 if(dbCheckName.contains("Config_")){
444 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
445 }else if(dbCheckName.contains("Action_")){
446 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
447 }else if(dbCheckName.contains("Decision_")){
448 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
450 String[] splitDBCheckName = dbCheckName.split(":");
451 String peQuery = "FROM PolicyEntity where policyName = :splitDBCheckName_1 and scope = :splitDBCheckName_0";
452 SimpleBindings policyParams = new SimpleBindings();
453 policyParams.put("splitDBCheckName_1", splitDBCheckName[1]);
454 policyParams.put("splitDBCheckName_0", splitDBCheckName[0]);
455 List<Object> policyEntity = controller.getDataByQuery(peQuery, policyParams);
456 PolicyEntity pentity = (PolicyEntity) policyEntity.get(0);
457 if(pentity.isDeleted()){
458 return error("The Policy is Not Existing in Workspace");
460 if(policyName.contains("/")){
461 policyName = policyName.replace("/", File.separator);
463 policyName = policyName.substring(policyName.indexOf(File.separator)+1);
464 if(policyName.contains("\\")){
465 policyName = policyName.replace(File.separator, "\\");
467 policyName = splitDBCheckName[0].replace(".", File.separator)+File.separator+policyName;
468 String watchPolicyName = policyName;
469 if(policyName.contains("/")){
470 policyName = policyName.replace("/", File.separator);
472 if(policyName.contains("\\")){
473 policyName = policyName.replace("\\", "\\\\");
475 String query = "update PolicyVersion set active_version='"+activeVersion+"' where policy_name ='"+policyName+"' and id >0";
477 controller.executeQuery(query);
478 //Policy Notification
479 PolicyVersion entity = new PolicyVersion();
480 entity.setPolicyName(watchPolicyName);
481 entity.setActiveVersion(Integer.parseInt(activeVersion));
482 entity.setModifiedBy(userId);
483 controller.watchPolicyFunction(entity, activePolicy, "SwitchVersion");
488 private JSONObject describePolicy(JSONObject params) throws ServletException{
489 JSONObject object = null;
490 String path = params.getString("path");
491 String policyName = null;
492 if(path.startsWith("/")){
493 path = path.substring(1);
494 policyName = path.substring(path.lastIndexOf('/') +1);
495 path = path.replace("/", ".");
497 path = path.replace("/", ".");
500 if(path.contains("Config_")){
501 path = path.replace(".Config_", ":Config_");
502 }else if(path.contains("Action_")){
503 path = path.replace(".Action_", ":Action_");
504 }else if(path.contains("Decision_")){
505 path = path.replace(".Decision_", ":Decision_");
507 PolicyController controller = getPolicyControllerInstance();
508 String[] split = path.split(":");
509 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
510 SimpleBindings peParams = new SimpleBindings();
511 peParams.put("split_1", split[1]);
512 peParams.put("split_0", split[0]);
513 List<Object> queryData = null;
514 if(PolicyController.isjUnit()){
515 queryData = controller.getDataByQuery(query, null);
517 queryData = controller.getDataByQuery(query, peParams);
519 if(queryData.isEmpty()){
520 return error("Error Occured while Describing the Policy - query is empty");
522 PolicyEntity entity = (PolicyEntity) queryData.get(0);
525 temp = File.createTempFile(policyName, ".tmp");
526 } catch (IOException e) {
527 String message = "Failed to create temp file " + policyName + ".tmp";
528 LOGGER.error(message + e);
529 return error(message);
531 try (BufferedWriter bw = new BufferedWriter(new FileWriter(temp))) {
532 bw.write(entity.getPolicyData());
533 object = HumanPolicyComponent.DescribePolicy(temp);
534 } catch (IOException e) {
535 LOGGER.error("Exception Occured while Describing the Policy"+e);
539 Files.delete(temp.toPath());
540 } catch (IOException e) {
541 LOGGER.warn("Failed to delete " + temp.getName() + e);
548 //Get the List of Policies and Scopes for Showing in Editor tab
549 private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException {
550 Set<String> scopes = null;
551 List<String> roles = null;
553 PolicyController controller = getPolicyControllerInstance();
554 //Get the Login Id of the User from Request
555 String testUserID = getTestUserId();
556 String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId();
557 List<Object> userRoles = controller.getRoles(userId);
558 Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
562 List<JSONObject> resultList = new ArrayList<>();
563 boolean onlyFolders = params.getBoolean("onlyFolders");
564 String path = params.getString("path");
565 if(path.contains("..xml")){
566 path = path.replaceAll("..xml", "").trim();
569 if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
570 if(scopes.isEmpty()){
571 return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
573 if(!"/".equals(path)){
574 String tempScope = path.substring(1, path.length());
575 tempScope = tempScope.replace("/", File.separator);
576 scopes.add(tempScope);
581 if("/".equals(path)){
582 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
583 List<Object> scopesList = queryPolicyEditorScopes(null);
584 for(Object list : scopesList){
585 PolicyEditorScopes scope = (PolicyEditorScopes) list;
586 if(!(scope.getScopeName().contains(File.separator))){
587 JSONObject el = new JSONObject();
588 el.put("name", scope.getScopeName());
589 el.put("date", scope.getModifiedDate());
591 el.put("type", "dir");
592 el.put("createdBy", scope.getUserCreatedBy().getUserName());
593 el.put("modifiedBy", scope.getUserModifiedBy().getUserName());
597 }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){
598 for(Object scope : scopes){
599 JSONObject el = new JSONObject();
600 List<Object> scopesList = queryPolicyEditorScopes(scope.toString());
601 if(!scopesList.isEmpty()){
602 PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
603 el.put("name", scopeById.getScopeName());
604 el.put("date", scopeById.getModifiedDate());
606 el.put("type", "dir");
607 el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
608 el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
615 String scopeName = path.substring(path.indexOf('/') +1);
616 activePolicyList(scopeName, resultList, roles, scopes, onlyFolders);
617 } catch (Exception ex) {
618 LOGGER.error("Error Occured While reading Policy Files List"+ex );
622 return new JSONObject().put(RESULT, resultList);
623 } catch (Exception e) {
624 LOGGER.error("list", e);
625 return error(e.getMessage());
629 private List<Object> queryPolicyEditorScopes(String scopeName){
630 String scopeNamequery;
631 SimpleBindings params = new SimpleBindings();
632 if(scopeName == null){
633 scopeNamequery = "from PolicyEditorScopes";
635 scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
636 params.put("scopeName", scopeName + "%");
638 PolicyController controller = getPolicyControllerInstance();
639 List<Object> scopesList;
640 if(PolicyController.isjUnit()){
641 scopesList = controller.getDataByQuery(scopeNamequery, null);
643 scopesList = controller.getDataByQuery(scopeNamequery, params);
648 //Get Active Policy List based on Scope Selection form Policy Version table
649 private void activePolicyList(String inScopeName, List<JSONObject> resultList, List<String> roles, Set<String> scopes, boolean onlyFolders){
650 PolicyController controller = getPolicyControllerInstance();
651 String scopeName = inScopeName;
652 if(scopeName.contains("/")){
653 scopeName = scopeName.replace("/", File.separator);
655 if(scopeName.contains("\\")){
656 scopeName = scopeName.replace("\\", "\\\\");
658 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
659 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
661 SimpleBindings params = new SimpleBindings();
662 params.put("scopeName", scopeName + "%");
664 List<Object> activePolicies;
665 List<Object> scopesList;
666 if(PolicyController.isjUnit()){
667 activePolicies = controller.getDataByQuery(query, null);
668 scopesList = controller.getDataByQuery(scopeNamequery, null);
670 activePolicies = controller.getDataByQuery(query, params);
671 scopesList = controller.getDataByQuery(scopeNamequery, params);
673 for(Object list : scopesList){
674 PolicyEditorScopes scopeById = (PolicyEditorScopes) list;
675 String scope = scopeById.getScopeName();
676 if(scope.contains(File.separator)){
677 String checkScope = scope.substring(0, scope.lastIndexOf(File.separator));
678 if(scopeName.contains("\\\\")){
679 scopeName = scopeName.replace("\\\\", File.separator);
681 if(scope.contains(File.separator)){
682 scope = scope.substring(checkScope.length()+1);
683 if(scope.contains(File.separator)){
684 scope = scope.substring(0, scope.indexOf(File.separator));
687 if(scopeName.equalsIgnoreCase(checkScope)){
688 JSONObject el = new JSONObject();
689 el.put("name", scope);
690 el.put("date", scopeById.getModifiedDate());
692 el.put("type", "dir");
693 el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
694 el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
699 String scopeNameCheck;
700 for (Object list : activePolicies) {
701 PolicyVersion policy = (PolicyVersion) list;
702 String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator));
703 if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
704 if(scopeName.contains("\\\\")){
705 scopeNameCheck = scopeName.replace("\\\\", File.separator);
707 scopeNameCheck = scopeName;
709 if(scopeNameValue.equals(scopeNameCheck)){
710 JSONObject el = new JSONObject();
711 el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
712 el.put("date", policy.getModifiedDate());
713 el.put("version", policy.getActiveVersion());
715 el.put("type", "file");
716 el.put("createdBy", getUserName(policy.getCreatedBy()));
717 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
720 }else if(!scopes.isEmpty() && scopes.contains(scopeNameValue)){
721 JSONObject el = new JSONObject();
722 el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
723 el.put("date", policy.getModifiedDate());
724 el.put("version", policy.getActiveVersion());
726 el.put("type", "file");
727 el.put("createdBy", getUserName(policy.getCreatedBy()));
728 el.put("modifiedBy", getUserName(policy.getModifiedBy()));
734 private String getUserName(String loginId){
735 PolicyController controller = getPolicyControllerInstance();
736 UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
737 if(userInfo == null){
740 return userInfo.getUserName();
744 private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
746 boolean isActive = false;
747 List<String> policyActiveInPDP = new ArrayList<>();
748 Set<String> scopeOfPolicyActiveInPDP = new HashSet<>();
749 String userId = UserUtils.getUserSession(request).getOrgUserId();
750 String oldPath = params.getString("path");
751 String newPath = params.getString("newPath");
752 oldPath = oldPath.substring(oldPath.indexOf('/')+1);
753 newPath = newPath.substring(newPath.indexOf('/')+1);
754 String checkValidation = null;
755 if(oldPath.endsWith(".xml")){
756 checkValidation = newPath.replace(".xml", "");
757 checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf("."));
758 checkValidation = checkValidation.substring(checkValidation.lastIndexOf("/")+1);
759 if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains("success")){
760 return error("Policy Rename Failed. The Name contains special characters.");
762 JSONObject result = policyRename(oldPath, newPath, userId);
763 if(!(Boolean)(result.getJSONObject("result").get("success"))){
767 String scopeName = oldPath;
768 String newScopeName = newPath;
769 if(scopeName.contains("/")){
770 scopeName = scopeName.replace("/", File.separator);
771 newScopeName = newScopeName.replace("/", File.separator);
773 checkValidation = newScopeName.substring(newScopeName.lastIndexOf(File.separator)+1);
774 if(scopeName.contains("\\")){
775 scopeName = scopeName.replace("\\", "\\\\\\\\");
776 newScopeName = newScopeName.replace("\\", "\\\\\\\\");
778 if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains("success")){
779 return error("Scope Rename Failed. The Name contains special characters.");
781 PolicyController controller = getPolicyControllerInstance();
782 String query = "from PolicyVersion where POLICY_NAME like :scopeName";
783 String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName";
784 SimpleBindings pvParams = new SimpleBindings();
785 pvParams.put("scopeName", scopeName + "%");
786 List<Object> activePolicies = controller.getDataByQuery(query, pvParams);
787 List<Object> scopesList = controller.getDataByQuery(scopeNamequery, pvParams);
788 for(Object object : activePolicies){
789 PolicyVersion activeVersion = (PolicyVersion) object;
790 String policyOldPath = activeVersion.getPolicyName().replace(File.separator, "/") + "." + activeVersion.getActiveVersion() + ".xml";
791 String policyNewPath = policyOldPath.replace(oldPath, newPath);
792 JSONObject result = policyRename(policyOldPath, policyNewPath, userId);
793 if(!(Boolean)(result.getJSONObject("result").get("success"))){
795 policyActiveInPDP.add(policyOldPath);
796 String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf('/'));
797 scopeOfPolicyActiveInPDP.add(scope.replace("/", File.separator));
800 boolean rename = false;
801 if(activePolicies.size() != policyActiveInPDP.size()){
805 UserInfo userInfo = new UserInfo();
806 userInfo.setUserLoginId(userId);
807 if(policyActiveInPDP.isEmpty()){
808 renameScope(scopesList, scopeName, newScopeName, controller);
810 renameScope(scopesList, scopeName, newScopeName, controller);
811 for(String scope : scopeOfPolicyActiveInPDP){
812 PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes();
813 editorScopeEntity.setScopeName(scope.replace("\\", "\\\\\\\\"));
814 editorScopeEntity.setUserCreatedBy(userInfo);
815 editorScopeEntity.setUserModifiedBy(userInfo);
816 controller.saveData(editorScopeEntity);
820 return error("The Following policies rename failed. Since they are active in PDP Groups" +policyActiveInPDP);
824 } catch (Exception e) {
825 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
826 return error(e.getMessage());
830 private void renameScope(List<Object> scopesList, String inScopeName, String newScopeName, PolicyController controller){
831 for(Object object : scopesList){
832 PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object;
833 String scopeName = inScopeName;
834 if(scopeName.contains("\\\\\\\\")){
835 scopeName = scopeName.replace("\\\\\\\\", File.separator);
836 newScopeName = newScopeName.replace("\\\\\\\\", File.separator);
838 String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName);
839 editorScopeEntity.setScopeName(scope);
840 controller.updateData(editorScopeEntity);
844 private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
847 PolicyController controller = getPolicyControllerInstance();
849 String policyVersionName = newPath.replace(".xml", "");
850 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')).replace("/", File.separator);
852 String oldpolicyVersionName = oldPath.replace(".xml", "");
853 String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf('.')).replace("/", File.separator);
855 String newpolicyName = newPath.replace("/", ".");
856 String newPolicyCheck = newpolicyName;
857 if(newPolicyCheck.contains("Config_")){
858 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
859 }else if(newPolicyCheck.contains("Action_")){
860 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
861 }else if(newPolicyCheck.contains("Decision_")){
862 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
864 String[] newPolicySplit = newPolicyCheck.split(":");
866 String orignalPolicyName = oldPath.replace("/", ".");
867 String oldPolicyCheck = orignalPolicyName;
868 if(oldPolicyCheck.contains("Config_")){
869 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
870 }else if(oldPolicyCheck.contains("Action_")){
871 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
872 }else if(oldPolicyCheck.contains("Decision_")){
873 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
875 String[] oldPolicySplit = oldPolicyCheck.split(":");
877 //Check PolicyEntity table with newPolicy Name
878 String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
879 SimpleBindings policyParams = new SimpleBindings();
880 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
881 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
882 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
883 if(!queryData.isEmpty()){
884 return error("Policy rename failed. Since, the policy with same name already exists.");
887 //Query the Policy Entity with oldPolicy Name
888 String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf('.'));
889 String oldpolicyEntityquery = "FROM PolicyEntity where policyName like :policyEntityCheck and scope = :oldPolicySplit_0";
890 SimpleBindings params = new SimpleBindings();
891 params.put("policyEntityCheck", policyEntityCheck + "%");
892 params.put("oldPolicySplit_0", oldPolicySplit[0]);
893 List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery, params);
894 if(!oldEntityData.isEmpty()){
895 StringBuilder groupQuery = new StringBuilder();
896 groupQuery.append("FROM PolicyGroupEntity where (");
897 SimpleBindings geParams = new SimpleBindings();
898 for(int i=0; i<oldEntityData.size(); i++){
899 entity = (PolicyEntity) oldEntityData.get(i);
901 groupQuery.append("policyid = :policyId");
902 geParams.put("policyId", entity.getPolicyId());
904 groupQuery.append(" or policyid = :policyId" + i);
905 geParams.put("policyId" + i, entity.getPolicyId());
908 groupQuery.append(")");
909 List<Object> groupEntityData = controller.getDataByQuery(groupQuery.toString(), geParams);
910 if(! groupEntityData.isEmpty()){
911 return error("Policy rename failed. Since the policy or its version is active in PDP Groups.");
913 for(int i=0; i<oldEntityData.size(); i++){
914 entity = (PolicyEntity) oldEntityData.get(i);
915 String checkEntityName = entity.getPolicyName().replace(".xml", "");
916 checkEntityName = checkEntityName.substring(0, checkEntityName.lastIndexOf('.'));
917 String originalPolicyName = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
918 if(checkEntityName.equals(originalPolicyName)){
919 checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0] , newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
923 return error("Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin.");
927 } catch (Exception e) {
928 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
929 return error(e.getMessage());
933 private JSONObject checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, String oldScope, String removeoldPolicyExtension,
934 String policyName, String newpolicyName, String oldpolicyName, String userId) throws ServletException{
936 ConfigurationDataEntity configEntity = entity.getConfigurationData();
937 ActionBodyEntity actionEntity = entity.getActionBodyEntity();
938 PolicyController controller = getPolicyControllerInstance();
940 String oldPolicyNameWithoutExtension = removeoldPolicyExtension;
941 String newPolicyNameWithoutExtension = removenewPolicyExtension;
942 if(removeoldPolicyExtension.endsWith(".xml")){
943 oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf('.'));
944 newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf('.'));
946 entity.setPolicyName(entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
947 entity.setPolicyData(entity.getPolicyData().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
948 entity.setScope(newScope);
949 entity.setModifiedBy(userId);
951 String oldConfigurationName = null;
952 String newConfigurationName = null;
953 if(newpolicyName.contains("Config_")){
954 oldConfigurationName = configEntity.getConfigurationName();
955 configEntity.setConfigurationName(configEntity.getConfigurationName().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
956 controller.updateData(configEntity);
957 newConfigurationName = configEntity.getConfigurationName();
958 File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName);
960 File renamefile = new File(PolicyController.getConfigHome() + File.separator + newConfigurationName);
961 file.renameTo(renamefile);
963 }else if(newpolicyName.contains("Action_")){
964 oldConfigurationName = actionEntity.getActionBodyName();
965 actionEntity.setActionBody(actionEntity.getActionBody().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
966 controller.updateData(actionEntity);
967 newConfigurationName = actionEntity.getActionBodyName();
968 File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName);
970 File renamefile = new File(PolicyController.getActionHome() + File.separator + newConfigurationName);
971 file.renameTo(renamefile);
974 controller.updateData(entity);
976 PolicyRestController restController = new PolicyRestController();
977 restController.notifyOtherPAPSToUpdateConfigurations("rename", newConfigurationName, oldConfigurationName);
978 PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldpolicyName);
979 versionEntity.setPolicyName(policyName);
980 versionEntity.setModifiedBy(userId);
981 controller.updateData(versionEntity);
982 String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator)+1);
983 String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
984 if(movePolicyCheck.equals(moveOldPolicyCheck)){
985 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move");
987 controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename");
990 } catch (Exception e) {
991 LOGGER.error("Exception Occured"+e);
992 return error(e.getMessage());
996 private JSONObject cloneRecord(String newpolicyName, String oldScope, String inRemoveoldPolicyExtension, String newScope, String inRemovenewPolicyExtension, PolicyEntity entity, String userId) throws ServletException{
997 String queryEntityName;
998 PolicyController controller = getPolicyControllerInstance();
999 PolicyEntity cloneEntity = new PolicyEntity();
1000 cloneEntity.setPolicyName(newpolicyName);
1001 String removeoldPolicyExtension = inRemoveoldPolicyExtension;
1002 String removenewPolicyExtension = inRemovenewPolicyExtension;
1003 removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
1004 removenewPolicyExtension = removenewPolicyExtension.replace(".xml", "");
1005 cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope+"."+removeoldPolicyExtension, newScope+"."+removenewPolicyExtension));
1006 cloneEntity.setScope(entity.getScope());
1007 String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
1008 String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
1009 String newConfigurationName = null;
1010 if(newpolicyName.contains("Config_")){
1011 ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
1012 configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1013 queryEntityName = configurationDataEntity.getConfigurationName();
1014 configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody());
1015 configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType());
1016 configurationDataEntity.setDeleted(false);
1017 configurationDataEntity.setCreatedBy(userId);
1018 configurationDataEntity.setModifiedBy(userId);
1019 controller.saveData(configurationDataEntity);
1020 ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
1021 cloneEntity.setConfigurationData(configEntiy);
1022 newConfigurationName = configEntiy.getConfigurationName();
1023 try (FileWriter fw = new FileWriter(PolicyController.getConfigHome() + File.separator + newConfigurationName);
1024 BufferedWriter bw = new BufferedWriter(fw)){
1025 bw.write(configEntiy.getConfigBody());
1026 } catch (IOException e) {
1027 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1029 }else if(newpolicyName.contains("Action_")){
1030 ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
1031 actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
1032 queryEntityName = actionBodyEntity.getActionBodyName();
1033 actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody());
1034 actionBodyEntity.setDeleted(false);
1035 actionBodyEntity.setCreatedBy(userId);
1036 actionBodyEntity.setModifiedBy(userId);
1037 controller.saveData(actionBodyEntity);
1038 ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class, "actionBodyName", queryEntityName);
1039 cloneEntity.setActionBodyEntity(actionEntiy);
1040 newConfigurationName = actionEntiy.getActionBodyName();
1041 try (FileWriter fw = new FileWriter(PolicyController.getActionHome() + File.separator + newConfigurationName);
1042 BufferedWriter bw = new BufferedWriter(fw)){
1043 bw.write(actionEntiy.getActionBody());
1044 } catch (IOException e) {
1045 LOGGER.error("Exception Occured While cloning the configuration file"+e);
1049 cloneEntity.setDeleted(entity.isDeleted());
1050 cloneEntity.setCreatedBy(userId);
1051 cloneEntity.setModifiedBy(userId);
1052 controller.saveData(cloneEntity);
1054 //Notify others paps regarding clone policy.
1055 PolicyRestController restController = new PolicyRestController();
1056 restController.notifyOtherPAPSToUpdateConfigurations("clonePolicy", newConfigurationName, null);
1061 private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
1063 String userId = UserUtils.getUserSession(request).getOrgUserId();
1064 String oldPath = params.getString("path");
1065 String newPath = params.getString("newPath");
1066 oldPath = oldPath.substring(oldPath.indexOf('/')+1);
1067 newPath = newPath.substring(newPath.indexOf('/')+1);
1069 String policyVersionName = newPath.replace(".xml", "");
1070 String version = policyVersionName.substring(policyVersionName.indexOf('.')+1);
1071 String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')).replace("/", File.separator);
1073 String newpolicyName = newPath.replace("/", ".");
1075 String orignalPolicyName = oldPath.replace("/", ".");
1077 String newPolicyCheck = newpolicyName;
1078 if(newPolicyCheck.contains("Config_")){
1079 newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_");
1080 }else if(newPolicyCheck.contains("Action_")){
1081 newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_");
1082 }else if(newPolicyCheck.contains("Decision_")){
1083 newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_");
1085 if(!newPolicyCheck.contains(":")){
1086 return error("Policy Clone Failed. The Name contains special characters.");
1088 String[] newPolicySplit = newPolicyCheck.split(":");
1090 String checkValidation = newPolicySplit[1].replace(".xml", "");
1091 checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf("."));
1092 if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains("success")){
1093 return error("Policy Clone Failed. The Name contains special characters.");
1096 String oldPolicyCheck = orignalPolicyName;
1097 if(oldPolicyCheck.contains("Config_")){
1098 oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_");
1099 }else if(oldPolicyCheck.contains("Action_")){
1100 oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_");
1101 }else if(oldPolicyCheck.contains("Decision_")){
1102 oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_");
1104 String[] oldPolicySplit = oldPolicyCheck.split(":");
1106 PolicyController controller = getPolicyControllerInstance();
1108 PolicyEntity entity = null;
1109 boolean success = false;
1111 //Check PolicyEntity table with newPolicy Name
1112 String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
1113 SimpleBindings policyParams = new SimpleBindings();
1114 policyParams.put("newPolicySplit_1", newPolicySplit[1]);
1115 policyParams.put("newPolicySplit_0", newPolicySplit[0]);
1116 List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
1117 if(!queryData.isEmpty()){
1118 return error("Policy already exists with same name");
1121 //Query the Policy Entity with oldPolicy Name
1122 policyEntityquery = "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0";
1123 SimpleBindings peParams = new SimpleBindings();
1124 peParams.put("oldPolicySplit_1", oldPolicySplit[1]);
1125 peParams.put("oldPolicySplit_0", oldPolicySplit[0]);
1126 queryData = controller.getDataByQuery(policyEntityquery, peParams);
1127 if(!queryData.isEmpty()){
1128 entity = (PolicyEntity) queryData.get(0);
1131 cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId);
1136 PolicyVersion entityItem = new PolicyVersion();
1137 entityItem.setActiveVersion(Integer.parseInt(version));
1138 entityItem.setHigherVersion(Integer.parseInt(version));
1139 entityItem.setPolicyName(policyName);
1140 entityItem.setCreatedBy(userId);
1141 entityItem.setModifiedBy(userId);
1142 entityItem.setModifiedDate(new Date());
1143 controller.saveData(entityItem);
1146 LOGGER.debug("copy from: {} to: {}" + oldPath +newPath);
1149 } catch (Exception e) {
1150 LOGGER.error("copy", e);
1151 return error(e.getMessage());
1155 //Delete Policy or Scope Functionality
1156 private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
1157 PolicyController controller = getPolicyControllerInstance();
1158 PolicyRestController restController = new PolicyRestController();
1159 PolicyEntity policyEntity = null;
1160 String policyNamewithoutExtension;
1162 String userId = UserUtils.getUserSession(request).getOrgUserId();
1163 String deleteVersion = "";
1164 String path = params.getString("path");
1165 LOGGER.debug("delete {}" +path);
1166 if(params.has("deleteVersion")){
1167 deleteVersion = params.getString("deleteVersion");
1169 path = path.substring(path.indexOf('/')+1);
1170 String policyNamewithExtension = path.replace("/", File.separator);
1171 String policyVersionName = policyNamewithExtension.replace(".xml", "");
1173 SimpleBindings policyParams = new SimpleBindings();
1174 if(path.endsWith(".xml")){
1175 policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf('.'));
1176 policyNamewithoutExtension = policyNamewithoutExtension.replace(File.separator, ".");
1177 String splitPolicyName = null;
1178 if(policyNamewithoutExtension.contains("Config_")){
1179 splitPolicyName = policyNamewithoutExtension.replace(".Config_", ":Config_");
1180 }else if(policyNamewithoutExtension.contains("Action_")){
1181 splitPolicyName = policyNamewithoutExtension.replace(".Action_", ":Action_");
1182 }else if(policyNamewithoutExtension.contains("Decision_")){
1183 splitPolicyName = policyNamewithoutExtension.replace(".Decision_", ":Decision_");
1185 String[] split = splitPolicyName.split(":");
1187 query = "FROM PolicyEntity where policyName like :split_1 and scope = :split_0";
1188 policyParams.put("split_1", split[1] + "%");
1189 policyParams.put("split_0", split[0]);
1191 policyNamewithoutExtension = path.replace(File.separator, ".");
1192 query = "FROM PolicyEntity where scope like :policyNamewithoutExtension";
1193 policyParams.put("policyNamewithoutExtension", policyNamewithoutExtension + "%");
1196 List<Object> policyEntityobjects = controller.getDataByQuery(query, policyParams);
1197 String activePolicyName = null;
1198 boolean pdpCheck = false;
1199 if(path.endsWith(".xml")){
1200 policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator);
1201 int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf('.')+1));
1202 if("ALL".equals(deleteVersion)){
1203 if(!policyEntityobjects.isEmpty()){
1204 for(Object object : policyEntityobjects){
1205 policyEntity = (PolicyEntity) object;
1206 String groupEntityquery = "from PolicyGroupEntity where policyid ='"+policyEntity.getPolicyId()+"'";
1207 SimpleBindings pgeParams = new SimpleBindings();
1208 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, pgeParams);
1209 if(!groupobject.isEmpty()){
1211 activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName();
1213 //Delete the entity from Elastic Search Database
1214 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1215 restController.deleteElasticData(searchFileName);
1216 //Delete the entity from Policy Entity table
1217 controller.deleteData(policyEntity);
1218 if(policyNamewithoutExtension.contains("Config_")){
1219 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1220 controller.deleteData(policyEntity.getConfigurationData());
1221 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getConfigurationData().getConfigurationName());
1222 }else if(policyNamewithoutExtension.contains("Action_")){
1223 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1224 controller.deleteData(policyEntity.getActionBodyEntity());
1225 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getActionBodyEntity().getActionBodyName());
1230 //Policy Notification
1231 PolicyVersion versionEntity = new PolicyVersion();
1232 versionEntity.setPolicyName(policyNamewithoutExtension);
1233 versionEntity.setModifiedBy(userId);
1234 controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll");
1236 //Delete from policyVersion table
1237 String getActivePDPPolicyVersion = activePolicyName.replace(".xml", "");
1238 getActivePDPPolicyVersion = getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf('.')+1);
1239 String policyVersionQuery = "update PolicyVersion set active_version='"+getActivePDPPolicyVersion+"' , highest_version='"+getActivePDPPolicyVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1240 if(policyVersionQuery != null){
1241 controller.executeQuery(policyVersionQuery);
1243 return error("Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "+activePolicyName);
1245 //No Active Policy in PDP. So, deleting all entries from policyVersion table
1246 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1247 if(policyVersionQuery != null){
1248 controller.executeQuery(policyVersionQuery);
1251 }else if("CURRENT".equals(deleteVersion)){
1252 String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1);
1253 String currentVersionScope = policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator)).replace(File.separator, ".");
1254 query = "FROM PolicyEntity where policyName = :currentVersionPolicyName and scope = :currentVersionScope";
1256 SimpleBindings peParams = new SimpleBindings();
1257 peParams.put("currentVersionPolicyName", currentVersionPolicyName);
1258 peParams.put("currentVersionScope", currentVersionScope);
1260 List<Object> policyEntitys = controller.getDataByQuery(query, peParams);
1261 if(!policyEntitys.isEmpty()){
1262 policyEntity = (PolicyEntity) policyEntitys.get(0);
1264 if(policyEntity != null){
1265 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId and policyid > 0";
1266 SimpleBindings geParams = new SimpleBindings();
1267 geParams.put("policyEntityId", policyEntity.getPolicyId());
1268 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1269 if(groupobject.isEmpty()){
1270 //Delete the entity from Elastic Search Database
1271 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1272 restController.deleteElasticData(searchFileName);
1273 //Delete the entity from Policy Entity table
1274 controller.deleteData(policyEntity);
1275 if(policyNamewithoutExtension.contains("Config_")){
1276 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1277 controller.deleteData(policyEntity.getConfigurationData());
1278 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getConfigurationData().getConfigurationName());
1279 }else if(policyNamewithoutExtension.contains("Action_")){
1280 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1281 controller.deleteData(policyEntity.getActionBodyEntity());
1282 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getActionBodyEntity().getActionBodyName());
1286 int highestVersion = 0;
1287 if(!policyEntityobjects.isEmpty()){
1288 for(Object object : policyEntityobjects){
1289 policyEntity = (PolicyEntity) object;
1290 String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
1291 int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf('.')+1));
1292 if(policyEntityVersion > highestVersion && policyEntityVersion != version){
1293 highestVersion = policyEntityVersion;
1298 //Policy Notification
1299 PolicyVersion entity = new PolicyVersion();
1300 entity.setPolicyName(policyNamewithoutExtension);
1301 entity.setActiveVersion(highestVersion);
1302 entity.setModifiedBy(userId);
1303 controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne");
1305 String updatequery = "";
1306 if(highestVersion != 0){
1307 updatequery = "update PolicyVersion set active_version='"+highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"'";
1309 updatequery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1311 controller.executeQuery(updatequery);
1313 String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
1314 if(policyVersionQuery != null){
1315 controller.executeQuery(policyVersionQuery);
1319 return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'");
1324 List<String> activePoliciesInPDP = new ArrayList<>();
1325 if(!policyEntityobjects.isEmpty()){
1326 for(Object object : policyEntityobjects){
1327 policyEntity = (PolicyEntity) object;
1328 String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId";
1329 SimpleBindings geParams = new SimpleBindings();
1330 geParams.put("policyEntityId", policyEntity.getPolicyId());
1331 List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
1332 if(!groupobject.isEmpty()){
1334 activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName());
1336 //Delete the entity from Elastic Search Database
1337 String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
1338 restController.deleteElasticData(searchFileName);
1339 //Delete the entity from Policy Entity table
1340 controller.deleteData(policyEntity);
1341 policyNamewithoutExtension = policyEntity.getPolicyName();
1342 if(policyNamewithoutExtension.contains("Config_")){
1343 Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
1344 controller.deleteData(policyEntity.getConfigurationData());
1345 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getConfigurationData().getConfigurationName());
1346 }else if(policyNamewithoutExtension.contains("Action_")){
1347 Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
1348 controller.deleteData(policyEntity.getActionBodyEntity());
1349 restController.notifyOtherPAPSToUpdateConfigurations("delete", null, policyEntity.getActionBodyEntity().getActionBodyName());
1353 //Delete from policyVersion and policyEditor Scope table
1354 String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1355 controller.executeQuery(policyVersionQuery);
1357 //Policy Notification
1358 PolicyVersion entity = new PolicyVersion();
1359 entity.setPolicyName(path);
1360 entity.setModifiedBy(userId);
1361 controller.watchPolicyFunction(entity, path, "DeleteScope");
1363 //Add Active Policies List to PolicyVersionTable
1364 for(int i =0; i < activePoliciesInPDP.size(); i++){
1365 String activePDPPolicyName = activePoliciesInPDP.get(i).replace(".xml", "");
1366 int activePDPPolicyVersion = Integer.parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf('.')+1));
1367 activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf('.')).replace(".", File.separator);
1368 PolicyVersion insertactivePDPVersion = new PolicyVersion();
1369 insertactivePDPVersion.setPolicyName(activePDPPolicyName);
1370 insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion);
1371 insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion);
1372 insertactivePDPVersion.setCreatedBy(userId);
1373 insertactivePDPVersion.setModifiedBy(userId);
1374 controller.saveData(insertactivePDPVersion);
1377 return error("All the Policies has been deleted in Scope. Except the following list of Policies:"+activePoliciesInPDP);
1379 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1380 controller.executeQuery(policyScopeQuery);
1383 String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0";
1384 controller.executeQuery(policyScopeQuery);
1388 } catch (Exception e) {
1389 LOGGER.error("delete", e);
1390 return error(e.getMessage());
1395 private JSONObject editFile(JSONObject params) throws ServletException {
1398 PolicyController controller = getPolicyControllerInstance();
1399 String mode = params.getString("mode");
1400 String path = params.getString("path");
1401 LOGGER.debug("editFile path: {}"+ path);
1403 String domain = path.substring(1, path.lastIndexOf('/'));
1404 domain = domain.replace("/", ".");
1406 path = path.substring(1);
1407 path = path.replace("/", ".");
1408 String dbCheckName = path;
1409 if(dbCheckName.contains("Config_")){
1410 dbCheckName = dbCheckName.replace(".Config_", ":Config_");
1411 }else if(dbCheckName.contains("Action_")){
1412 dbCheckName = dbCheckName.replace(".Action_", ":Action_");
1413 }else if(dbCheckName.contains("Decision_")){
1414 dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
1417 String[] split = dbCheckName.split(":");
1418 String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
1419 SimpleBindings peParams = new SimpleBindings();
1420 peParams.put("split_1", split[1]);
1421 peParams.put("split_0", split[0]);
1422 List<Object> queryData;
1423 if(PolicyController.isjUnit()){
1424 queryData = controller.getDataByQuery(query, null);
1426 queryData = controller.getDataByQuery(query, peParams);
1428 PolicyEntity entity = (PolicyEntity) queryData.get(0);
1429 InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
1432 Object policy = XACMLPolicyScanner.readPolicy(stream);
1433 PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
1434 policyAdapter.setData(policy);
1436 if("viewPolicy".equalsIgnoreCase(mode)){
1437 policyAdapter.setReadOnly(true);
1438 policyAdapter.setEditPolicy(false);
1440 policyAdapter.setReadOnly(false);
1441 policyAdapter.setEditPolicy(true);
1444 policyAdapter.setDomainDir(domain);
1445 policyAdapter.setPolicyData(policy);
1446 String policyName = path.replace(".xml", "");
1447 policyName = policyName.substring(0, policyName.lastIndexOf('.'));
1448 policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf('.')+1));
1450 PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance();
1451 setpolicyAdapter.configure(policyAdapter,entity);
1453 policyAdapter.setParentPath(null);
1454 ObjectMapper mapper = new ObjectMapper();
1455 String json = mapper.writeValueAsString(policyAdapter);
1456 JsonNode jsonNode = mapper.readTree(json);
1458 return new JSONObject().put(RESULT, jsonNode);
1459 } catch (Exception e) {
1460 LOGGER.error("editFile", e);
1461 return error(e.getMessage());
1466 private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
1467 PolicyController controller = getPolicyControllerInstance();
1470 String userId = UserUtils.getUserSession(request).getOrgUserId();
1471 String path = params.getString("path");
1473 if(params.has("subScopename")){
1474 if(! "".equals(params.getString("subScopename"))) {
1475 name = params.getString("path").replace("/", File.separator) + File.separator +params.getString("subScopename");
1478 name = params.getString("name");
1480 }catch(Exception e){
1481 name = params.getString("name");
1482 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e);
1484 String validateName;
1485 if(name.contains(File.separator)){
1486 validateName = name.substring(name.lastIndexOf(File.separator)+1);
1488 validateName = name;
1490 if(!name.isEmpty()){
1491 String validate = PolicyUtils.policySpecialCharValidator(validateName);
1492 if(!validate.contains("success")){
1493 return error(validate);
1496 LOGGER.debug("addFolder path: {} name: {}" + path +name);
1497 if(! "".equals(name)){
1498 if(name.startsWith(File.separator)){
1499 name = name.substring(1);
1501 PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, "scopeName", name);
1503 UserInfo userInfo = new UserInfo();
1504 userInfo.setUserLoginId(userId);
1505 PolicyEditorScopes newScope = new PolicyEditorScopes();
1506 newScope.setScopeName(name);
1507 newScope.setUserCreatedBy(userInfo);
1508 newScope.setUserModifiedBy(userInfo);
1509 controller.saveData(newScope);
1511 return error("Scope Already Exists");
1515 } catch (Exception e) {
1516 LOGGER.error("addFolder", e);
1517 return error(e.getMessage());
1521 //Return Error Object
1522 private JSONObject error(String msg) throws ServletException {
1524 JSONObject result = new JSONObject();
1525 result.put("success", false);
1526 result.put("error", msg);
1527 return new JSONObject().put(RESULT, result);
1528 } catch (JSONException e) {
1529 throw new ServletException(e);
1533 //Return Success Object
1534 private JSONObject success() throws ServletException {
1536 JSONObject result = new JSONObject();
1537 result.put("success", true);
1538 result.put("error", (Object) null);
1539 return new JSONObject().put(RESULT, result);
1540 } catch (JSONException e) {
1541 throw new ServletException(e);
1545 private PolicyController getPolicyControllerInstance(){
1546 return policyController != null ? getPolicyController() : new PolicyController();
1549 public String getTestUserId() {
1553 public static void setTestUserId(String testUserId) {
1554 PolicyManagerServlet.testUserId = testUserId;