diff options
Diffstat (limited to 'POLICY-SDK-APP/src/main/java/org/onap')
-rw-r--r-- | POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java | 451 | ||||
-rw-r--r-- | POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java | 929 |
2 files changed, 714 insertions, 666 deletions
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java index de83b045b..2492ab024 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java @@ -326,8 +326,6 @@ public class PolicyManagerServlet extends HttpServlet { } private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) { - Set<String> scopes; - List<String> roles; List<Object> policyData = new ArrayList<>(); JSONArray policyList = null; if(params.has("policyList")){ @@ -336,55 +334,66 @@ public class PolicyManagerServlet extends HttpServlet { PolicyController controller = getPolicyControllerInstance(); List<JSONObject> resultList = new ArrayList<>(); try { - //Get the Login Id of the User from Request - String userId = UserUtils.getUserSession(request).getOrgUserId(); - List<Object> userRoles = controller.getRoles(userId); - Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles); - roles = pair.u; - scopes = pair.t; - if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) { - if(scopes.isEmpty()){ - return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin"); - } - Set<String> tempScopes = scopes; - for(String scope : tempScopes){ - addScope(scopes, scope); - } + if (!lookupPolicyData(request, policyData, policyList, controller, resultList)) + return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin"); + + }catch(Exception e){ + LOGGER.error("Exception occured while reading policy Data from Policy Version table for Policy Search Data"+e); + } + + return new JSONObject().put(RESULT, resultList); + } + + private boolean lookupPolicyData(HttpServletRequest request, List<Object> policyData, JSONArray policyList, PolicyController controller, List<JSONObject> resultList) throws ServletException { + List<String> roles; + Set<String> scopes;//Get the Login Id of the User from Request + String userId = UserUtils.getUserSession(request).getOrgUserId(); + List<Object> userRoles = controller.getRoles(userId); + Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles); + roles = pair.u; + scopes = pair.t; + if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) { + if(scopes.isEmpty()){ + return false; } - if(policyList!= null){ - for(int i = 0; i < policyList.length(); i++){ - String policyName = policyList.get(i).toString().replace(".xml", ""); - String version = policyName.substring(policyName.lastIndexOf('.')+1); - policyName = policyName.substring(0, policyName.lastIndexOf('.')).replace(".", File.separator); - parsePolicyList(resultList, controller, policyName, version); - } + Set<String> tempScopes = scopes; + for(String scope : tempScopes){ + addScope(scopes, scope); + } + } + if(policyList!= null){ + for(int i = 0; i < policyList.length(); i++){ + String policyName = policyList.get(i).toString().replace(".xml", ""); + String version = policyName.substring(policyName.lastIndexOf('.')+1); + policyName = policyName.substring(0, policyName.lastIndexOf('.')).replace(".", File.separator); + parsePolicyList(resultList, controller, policyName, version); + } + }else{ + if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ){ + policyData = controller.getData(PolicyVersion.class); }else{ - if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ){ - policyData = controller.getData(PolicyVersion.class); - }else{ - List<Object> filterdatas = controller.getData(PolicyVersion.class); - for(Object filter : filterdatas){ - PolicyVersion filterdata = (PolicyVersion) filter; - try{ - String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator)); - if(scopes.contains(scopeName)){ - policyData.add(filterdata); - } - }catch(Exception e){ - LOGGER.error("Exception occured while filtering policyversion data"+e); - } - } + List<Object> filterdatas = controller.getData(PolicyVersion.class); + for(Object filter : filterdatas) { + addFilterData(policyData, scopes, (PolicyVersion) filter); } + } - if(!policyData.isEmpty()){ - updateResultList(policyData, resultList); - } + if(!policyData.isEmpty()){ + updateResultList(policyData, resultList); } - }catch(Exception e){ - LOGGER.error("Exception occured while reading policy Data from Policy Version table for Policy Search Data"+e); } + return true; + } - return new JSONObject().put(RESULT, resultList); + private void addFilterData(List<Object> policyData, Set<String> scopes, PolicyVersion filter) { + try{ + String scopeName = filter.getPolicyName().substring(0, filter.getPolicyName().lastIndexOf(File.separator)); + if(scopes.contains(scopeName)){ + policyData.add(filter); + } + }catch(Exception e){ + LOGGER.error("Exception occured while filtering policyversion data"+e); + } } private void updateResultList(List<Object> policyData, List<JSONObject> resultList) { @@ -570,82 +579,90 @@ public class PolicyManagerServlet extends HttpServlet { //Get the List of Policies and Scopes for Showing in Editor tab private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException { - Set<String> scopes = null; - List<String> roles = null; try { - PolicyController controller = getPolicyControllerInstance(); - //Get the Login Id of the User from Request - String testUserID = getTestUserId(); - String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId(); - List<Object> userRoles = controller.getRoles(userId); - Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles); - roles = pair.u; - scopes = pair.t; - - List<JSONObject> resultList = new ArrayList<>(); - boolean onlyFolders = params.getBoolean("onlyFolders"); - String path = params.getString("path"); - if(path.contains("..xml")){ - path = path.replaceAll("..xml", "").trim(); - } + return processPolicyList(params, request); + } catch (Exception e) { + LOGGER.error("list", e); + return error(e.getMessage()); + } + } - if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) { - if(scopes.isEmpty()){ - return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin"); - }else{ - if(!"/".equals(path)){ - String tempScope = path.substring(1, path.length()); - tempScope = tempScope.replace("/", File.separator); - scopes.add(tempScope); - } - } - } + private JSONObject processPolicyList(JSONObject params, HttpServletRequest request) throws ServletException { + List<String> roles; + Set<String> scopes;PolicyController controller = getPolicyControllerInstance(); + //Get the Login Id of the User from Request + String testUserID = getTestUserId(); + String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId(); + List<Object> userRoles = controller.getRoles(userId); + Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles); + roles = pair.u; + scopes = pair.t; - if("/".equals(path)){ - if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){ - List<Object> scopesList = queryPolicyEditorScopes(null); - for(Object list : scopesList){ - PolicyEditorScopes scope = (PolicyEditorScopes) list; - if(!(scope.getScopeName().contains(File.separator))){ - JSONObject el = new JSONObject(); - el.put(NAME, scope.getScopeName()); - el.put(DATE, scope.getModifiedDate()); - el.put(SIZE, ""); - el.put(TYPE, "dir"); - el.put(CREATED_BY, scope.getUserCreatedBy().getUserName()); - el.put(MODIFIED_BY, scope.getUserModifiedBy().getUserName()); - resultList.add(el); - } - } - }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){ - for(Object scope : scopes){ - JSONObject el = new JSONObject(); - List<Object> scopesList = queryPolicyEditorScopes(scope.toString()); - if(!scopesList.isEmpty()){ - PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0); - el.put(NAME, scopeById.getScopeName()); - el.put(DATE, scopeById.getModifiedDate()); - el.put(SIZE, ""); - el.put(TYPE, "dir"); - el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName()); - el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName()); - resultList.add(el); - } - } - } + List<JSONObject> resultList = new ArrayList<>(); + boolean onlyFolders = params.getBoolean("onlyFolders"); + String path = params.getString("path"); + if(path.contains("..xml")){ + path = path.replaceAll("..xml", "").trim(); + } + + if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) { + if(scopes.isEmpty()){ + return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin"); }else{ - try{ - String scopeName = path.substring(path.indexOf('/') +1); - activePolicyList(scopeName, resultList, roles, scopes, onlyFolders); - } catch (Exception ex) { - LOGGER.error("Error Occured While reading Policy Files List"+ex ); + if(!"/".equals(path)){ + String tempScope = path.substring(1, path.length()); + tempScope = tempScope.replace("/", File.separator); + scopes.add(tempScope); } } + } + if (!"/".equals(path)) { + try{ + String scopeName = path.substring(path.indexOf('/') +1); + activePolicyList(scopeName, resultList, roles, scopes, onlyFolders); + } catch (Exception ex) { + LOGGER.error("Error Occured While reading Policy Files List"+ex ); + } return new JSONObject().put(RESULT, resultList); - } catch (Exception e) { - LOGGER.error("list", e); - return error(e.getMessage()); + } + + processRoles(scopes, roles, resultList); + + return new JSONObject().put(RESULT, resultList); + } + + private void processRoles(Set<String> scopes, List<String> roles, List<JSONObject> resultList) { + if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){ + List<Object> scopesList = queryPolicyEditorScopes(null); + for(Object list : scopesList){ + PolicyEditorScopes scope = (PolicyEditorScopes) list; + if(!(scope.getScopeName().contains(File.separator))){ + JSONObject el = new JSONObject(); + el.put(NAME, scope.getScopeName()); + el.put(DATE, scope.getModifiedDate()); + el.put(SIZE, ""); + el.put(TYPE, "dir"); + el.put(CREATED_BY, scope.getUserCreatedBy().getUserName()); + el.put(MODIFIED_BY, scope.getUserModifiedBy().getUserName()); + resultList.add(el); + } + } + }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){ + for(Object scope : scopes){ + JSONObject el = new JSONObject(); + List<Object> scopesList = queryPolicyEditorScopes(scope.toString()); + if(!scopesList.isEmpty()){ + PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0); + el.put(NAME, scopeById.getScopeName()); + el.put(DATE, scopeById.getModifiedDate()); + el.put(SIZE, ""); + el.put(TYPE, "dir"); + el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName()); + el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName()); + resultList.add(el); + } + } } } @@ -693,31 +710,8 @@ public class PolicyManagerServlet extends HttpServlet { activePolicies = controller.getDataByQuery(query, params); scopesList = controller.getDataByQuery(scopeNamequery, params); } - for(Object list : scopesList){ - PolicyEditorScopes scopeById = (PolicyEditorScopes) list; - String scope = scopeById.getScopeName(); - if(scope.contains(File.separator)){ - String checkScope = scope.substring(0, scope.lastIndexOf(File.separator)); - if(scopeName.contains("\\\\")){ - scopeName = scopeName.replace("\\\\", File.separator); - } - if(scope.contains(File.separator)){ - scope = scope.substring(checkScope.length()+1); - if(scope.contains(File.separator)){ - scope = scope.substring(0, scope.indexOf(File.separator)); - } - } - if(scopeName.equalsIgnoreCase(checkScope)){ - JSONObject el = new JSONObject(); - el.put(NAME, scope); - el.put(DATE, scopeById.getModifiedDate()); - el.put(SIZE, ""); - el.put(TYPE, "dir"); - el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName()); - el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName()); - resultList.add(el); - } - } + for(Object list : scopesList) { + scopeName = checkScope(resultList, scopeName, (PolicyEditorScopes) list); } String scopeNameCheck; for (Object list : activePolicies) { @@ -754,6 +748,33 @@ public class PolicyManagerServlet extends HttpServlet { } } + private String checkScope(List<JSONObject> resultList, String scopeName, PolicyEditorScopes scopeById) { + String scope = scopeById.getScopeName(); + if(scope.contains(File.separator)){ + String targetScope = scope.substring(0, scope.lastIndexOf(File.separator)); + if(scopeName.contains("\\\\")){ + scopeName = scopeName.replace("\\\\", File.separator); + } + if(scope.contains(File.separator)){ + scope = scope.substring(targetScope.length()+1); + if(scope.contains(File.separator)){ + scope = scope.substring(0, scope.indexOf(File.separator)); + } + } + if(scopeName.equalsIgnoreCase(targetScope)){ + JSONObject el = new JSONObject(); + el.put(NAME, scope); + el.put(DATE, scopeById.getModifiedDate()); + el.put(SIZE, ""); + el.put(TYPE, "dir"); + el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName()); + el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName()); + resultList.add(el); + } + } + return scopeName; + } + private String getUserName(String loginId){ PolicyController controller = getPolicyControllerInstance(); UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId); @@ -766,88 +787,92 @@ public class PolicyManagerServlet extends HttpServlet { //Rename Policy private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException { try { - boolean isActive = false; - List<String> policyActiveInPDP = new ArrayList<>(); - Set<String> scopeOfPolicyActiveInPDP = new HashSet<>(); - String userId = UserUtils.getUserSession(request).getOrgUserId(); - String oldPath = params.getString("path"); - String newPath = params.getString("newPath"); - oldPath = oldPath.substring(oldPath.indexOf('/')+1); - newPath = newPath.substring(newPath.indexOf('/')+1); - String checkValidation = null; - if(oldPath.endsWith(".xml")){ - checkValidation = newPath.replace(".xml", ""); - checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf(".")); - checkValidation = checkValidation.substring(checkValidation.lastIndexOf("/")+1); - if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains("success")){ - return error("Policy Rename Failed. The Name contains special characters."); - } - JSONObject result = policyRename(oldPath, newPath, userId); + return handlePolicyRename(params, request); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e); + return error(e.getMessage()); + } + } + + private JSONObject handlePolicyRename(JSONObject params, HttpServletRequest request) throws ServletException { + boolean isActive = false; + List<String> policyActiveInPDP = new ArrayList<>(); + Set<String> scopeOfPolicyActiveInPDP = new HashSet<>(); + String userId = UserUtils.getUserSession(request).getOrgUserId(); + String oldPath = params.getString("path"); + String newPath = params.getString("newPath"); + oldPath = oldPath.substring(oldPath.indexOf('/')+1); + newPath = newPath.substring(newPath.indexOf('/')+1); + String checkValidation = null; + if(oldPath.endsWith(".xml")){ + checkValidation = newPath.replace(".xml", ""); + checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf(".")); + checkValidation = checkValidation.substring(checkValidation.lastIndexOf("/")+1); + if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains("success")){ + return error("Policy Rename Failed. The Name contains special characters."); + } + JSONObject result = policyRename(oldPath, newPath, userId); + if(!(Boolean)(result.getJSONObject("result").get("success"))){ + return result; + } + }else{ + String scopeName = oldPath; + String newScopeName = newPath; + if(scopeName.contains("/")){ + scopeName = scopeName.replace("/", File.separator); + newScopeName = newScopeName.replace("/", File.separator); + } + checkValidation = newScopeName.substring(newScopeName.lastIndexOf(File.separator)+1); + if(scopeName.contains("\\")){ + scopeName = scopeName.replace("\\", "\\\\\\\\"); + newScopeName = newScopeName.replace("\\", "\\\\\\\\"); + } + if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains("success")){ + return error("Scope Rename Failed. The Name contains special characters."); + } + PolicyController controller = getPolicyControllerInstance(); + String query = "from PolicyVersion where POLICY_NAME like :scopeName"; + String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName"; + SimpleBindings pvParams = new SimpleBindings(); + pvParams.put("scopeName", scopeName + "%"); + List<Object> activePolicies = controller.getDataByQuery(query, pvParams); + List<Object> scopesList = controller.getDataByQuery(scopeNamequery, pvParams); + for(Object object : activePolicies){ + PolicyVersion activeVersion = (PolicyVersion) object; + String policyOldPath = activeVersion.getPolicyName().replace(File.separator, "/") + "." + activeVersion.getActiveVersion() + ".xml"; + String policyNewPath = policyOldPath.replace(oldPath, newPath); + JSONObject result = policyRename(policyOldPath, policyNewPath, userId); if(!(Boolean)(result.getJSONObject("result").get("success"))){ - return result; - } - }else{ - String scopeName = oldPath; - String newScopeName = newPath; - if(scopeName.contains("/")){ - scopeName = scopeName.replace("/", File.separator); - newScopeName = newScopeName.replace("/", File.separator); - } - checkValidation = newScopeName.substring(newScopeName.lastIndexOf(File.separator)+1); - if(scopeName.contains("\\")){ - scopeName = scopeName.replace("\\", "\\\\\\\\"); - newScopeName = newScopeName.replace("\\", "\\\\\\\\"); - } - if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains("success")){ - return error("Scope Rename Failed. The Name contains special characters."); - } - PolicyController controller = getPolicyControllerInstance(); - String query = "from PolicyVersion where POLICY_NAME like :scopeName"; - String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like :scopeName"; - SimpleBindings pvParams = new SimpleBindings(); - pvParams.put("scopeName", scopeName + "%"); - List<Object> activePolicies = controller.getDataByQuery(query, pvParams); - List<Object> scopesList = controller.getDataByQuery(scopeNamequery, pvParams); - for(Object object : activePolicies){ - PolicyVersion activeVersion = (PolicyVersion) object; - String policyOldPath = activeVersion.getPolicyName().replace(File.separator, "/") + "." + activeVersion.getActiveVersion() + ".xml"; - String policyNewPath = policyOldPath.replace(oldPath, newPath); - JSONObject result = policyRename(policyOldPath, policyNewPath, userId); - if(!(Boolean)(result.getJSONObject("result").get("success"))){ - isActive = true; - policyActiveInPDP.add(policyOldPath); - String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf('/')); - scopeOfPolicyActiveInPDP.add(scope.replace("/", File.separator)); - } - } - boolean rename = false; - if(activePolicies.size() != policyActiveInPDP.size()){ - rename = true; + isActive = true; + policyActiveInPDP.add(policyOldPath); + String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf('/')); + scopeOfPolicyActiveInPDP.add(scope.replace("/", File.separator)); } + } + boolean rename = false; + if(activePolicies.size() != policyActiveInPDP.size()){ + rename = true; + } - UserInfo userInfo = new UserInfo(); - userInfo.setUserLoginId(userId); - if(policyActiveInPDP.isEmpty()){ - renameScope(scopesList, scopeName, newScopeName, controller); - }else if(rename){ - renameScope(scopesList, scopeName, newScopeName, controller); - for(String scope : scopeOfPolicyActiveInPDP){ - PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes(); - editorScopeEntity.setScopeName(scope.replace("\\", "\\\\\\\\")); - editorScopeEntity.setUserCreatedBy(userInfo); - editorScopeEntity.setUserModifiedBy(userInfo); - controller.saveData(editorScopeEntity); - } - } - if(isActive){ - return error("The Following policies rename failed. Since they are active in PDP Groups" +policyActiveInPDP); + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId(userId); + if(policyActiveInPDP.isEmpty()){ + renameScope(scopesList, scopeName, newScopeName, controller); + }else if(rename){ + renameScope(scopesList, scopeName, newScopeName, controller); + for(String scope : scopeOfPolicyActiveInPDP){ + PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes(); + editorScopeEntity.setScopeName(scope.replace("\\", "\\\\\\\\")); + editorScopeEntity.setUserCreatedBy(userInfo); + editorScopeEntity.setUserModifiedBy(userInfo); + controller.saveData(editorScopeEntity); } } - return success(); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e); - return error(e.getMessage()); + if(isActive){ + return error("The Following policies rename failed. Since they are active in PDP Groups" +policyActiveInPDP); + } } + return success(); } private void renameScope(List<Object> scopesList, String inScopeName, String newScopeName, PolicyController controller){ diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java index 40cceead5..b49f1fc35 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java @@ -3,6 +3,7 @@ * ONAP Policy Engine * ================================================================================ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,457 +70,479 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; @Controller @RequestMapping("/") public class CreateBRMSParamController extends RestrictedBaseController { - private static final Logger policyLogger = FlexLogger.getLogger(CreateBRMSParamController.class); - - private static CommonClassDao commonClassDao; - - public static CommonClassDao getCommonClassDao() { - return commonClassDao; - } - - public static void setCommonClassDao(CommonClassDao commonClassDao) { - CreateBRMSParamController.commonClassDao = commonClassDao; - } - - @Autowired - private CreateBRMSParamController(CommonClassDao commonClassDao){ - CreateBRMSParamController.commonClassDao = commonClassDao; - } - - public CreateBRMSParamController(){ - // Empty constructor - } - protected PolicyRestAdapter policyAdapter = null; - - private HashMap<String, String> dynamicLayoutMap; - - private static String brmsTemplateVlaue = "<$%BRMSParamTemplate="; - private static String string = "String"; - - - @RequestMapping(value={"/policyController/getBRMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public void getBRMSParamPolicyRuleData(HttpServletRequest request, HttpServletResponse response){ - try{ - dynamicLayoutMap = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - String rule = findRule(root.get(PolicyController.getPolicydata()).toString().replaceAll("^\"|\"$", "")); - generateUI(rule); - response.setCharacterEncoding(PolicyController.getCharacterencoding()); - response.setContentType(PolicyController.getContenttype()); - request.setCharacterEncoding(PolicyController.getCharacterencoding()); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(dynamicLayoutMap); - JSONObject j = new JSONObject("{policyData: " + responseString + "}"); - out.write(j.toString()); - }catch(Exception e){ - policyLogger.error("Exception Occured while getting BRMS Rule data" , e); - } - } - - protected String findRule(String ruleTemplate) { - List<Object> datas = commonClassDao.getDataById(BRMSParamTemplate.class, "ruleName", ruleTemplate); - if(datas != null && !datas.isEmpty()){ - BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate) datas.get(0); - return bRMSParamTemplate.getRule(); - } - return null; - } - - protected void generateUI(String rule) { - if(rule!=null){ - try { - StringBuilder params = new StringBuilder(""); - Boolean flag = false; - Boolean comment = false; - String[] lines = rule.split("\n"); - for(String line : lines){ - if (line.isEmpty() || line.startsWith("//")) { - continue; - } - if (line.startsWith("/*")) { - comment = true; - continue; - } - if (line.contains("//")) { - line = line.split("\\/\\/")[0]; - } - if (line.contains("/*")) { - comment = true; - if (line.contains("*/")) { - try { - comment = false; - line = line.split("\\/\\*")[0] - + line.split("\\*\\/")[1].replace("*/", ""); - } catch (Exception e) { - policyLogger.info("Just for Logging"+e); - line = line.split("\\/\\*")[0]; - } - } else { - line = line.split("\\/\\*")[0]; - } - } - if (line.contains("*/")) { - comment = false; - try { - line = line.split("\\*\\/")[1].replace("*/", ""); - } catch (Exception e) { - policyLogger.info("Just for Logging"+e); - line = ""; - } - } - if (comment) { - continue; - } - if (flag) { - params.append(line); - } - if (line.contains("declare Params")) { - params.append(line); - flag = true; - } - if (line.contains("end") && flag) { - break; - } - } - params = new StringBuilder(params.toString().replace("declare Params", "").replace("end", "").replaceAll("\\s+", "")); - String[] components = params.toString().split(":"); - String caption = ""; - for (int i = 0; i < components.length; i++) { - String type; - if (i == 0) { - caption = components[i]; - } - if("".equals(caption)){ - break; - } - String nextComponent = ""; - try { - nextComponent = components[i + 1]; - } catch (Exception e) { - policyLogger.info("Just for Logging"+e); - nextComponent = components[i]; - } - if (nextComponent.startsWith(string)) { - type = "String"; - createField(caption, type); - caption = nextComponent.replace(string, ""); - } else if (nextComponent.startsWith("int")) { - type = "int"; - createField(caption, type); - caption = nextComponent.replace("int", ""); - } - } - } catch (Exception e) { - policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); - } - } - } - - private void createField(String caption, String type) { - dynamicLayoutMap.put(caption, type); - } - - /* - * When the User Click Edit or View Policy the following method will get invoked for setting the data to PolicyRestAdapter. - * Which is used to bind the data in GUI - */ - public void prePopulateBRMSParamPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - dynamicLayoutMap = new HashMap<>(); - if (policyAdapter.getPolicyData() instanceof PolicyType) { - PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - // policy name value is the policy name without any prefix and - // Extensions. - String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Param_") + 11); - if (policyLogger.isDebugEnabled()) { - policyLogger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName()); - } - policyAdapter.setPolicyName(policyNameValue); - String description = ""; - try{ - description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); - }catch(Exception e){ - policyLogger.info("Just for Logging"+e); - description = policy.getDescription(); - } - policyAdapter.setPolicyDescription(description); - setDataAdapterFromAdviceExpressions(policy, policyAdapter); - paramUIGenerate(policyAdapter, entity); - // Get the target data under policy. - policyAdapter.setDynamicLayoutMap(dynamicLayoutMap); - if(policyAdapter.getDynamicLayoutMap().size() > 0){ - LinkedHashMap<String,String> drlRule = new LinkedHashMap<>(); - for(Object keyValue: policyAdapter.getDynamicLayoutMap().keySet()){ - drlRule.put(keyValue.toString(), policyAdapter.getDynamicLayoutMap().get(keyValue)); - } - policyAdapter.setRuleData(drlRule); - } - TargetType target = policy.getTarget(); - if (target != null) { - setDataToAdapterFromTarget(target, policyAdapter); - } - } - } - - private void setDataAdapterFromAdviceExpressions(PolicyType policy, PolicyRestAdapter policyAdapter){ - ArrayList<Object> attributeList = new ArrayList<>(); - // Set Attributes. - AdviceExpressionsType expressionTypes = ((RuleType)policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions(); - for( AdviceExpressionType adviceExpression: expressionTypes.getAdviceExpression()){ - for(AttributeAssignmentExpressionType attributeAssignment: adviceExpression.getAttributeAssignmentExpression()){ - if(attributeAssignment.getAttributeId().startsWith("key:")){ - Map<String, String> attribute = new HashMap<>(); - String key = attributeAssignment.getAttributeId().replace("key:", ""); - attribute.put("key", key); - @SuppressWarnings("unchecked") - JAXBElement<AttributeValueType> attributevalue = (JAXBElement<AttributeValueType>) attributeAssignment.getExpression(); - String value = (String) attributevalue.getValue().getContent().get(0); - attribute.put("value", value); - attributeList.add(attribute); - }else if(attributeAssignment.getAttributeId().startsWith("dependencies:")){ - ArrayList<String> dependencies = new ArrayList<>(Arrays.asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(","))); - if(dependencies.contains("")){ - dependencies.remove(""); - } - policyAdapter.setBrmsDependency(dependencies); - }else if(attributeAssignment.getAttributeId().startsWith("controller:")){ - policyAdapter.setBrmsController(attributeAssignment.getAttributeId().replace("controller:", "")); - } - } - policyAdapter.setAttributes(attributeList); - } - } - - private void setDataToAdapterFromTarget(TargetType target, PolicyRestAdapter policyAdapter){ - // Under target we have AnyOFType - List<AnyOfType> anyOfList = target.getAnyOf(); - if (anyOfList != null) { - Iterator<AnyOfType> iterAnyOf = anyOfList.iterator(); - while (iterAnyOf.hasNext()) { - AnyOfType anyOf = iterAnyOf.next(); - // Under AnyOFType we have AllOFType - List<AllOfType> allOfList = anyOf.getAllOf(); - if (allOfList != null) { - Iterator<AllOfType> iterAllOf = allOfList.iterator(); - while (iterAllOf.hasNext()) { - AllOfType allOf = iterAllOf.next(); - // Under AllOFType we have Match - List<MatchType> matchList = allOf.getMatch(); - if (matchList != null) { - setDataToAdapterFromMatchList(matchList, policyAdapter); - } - } - } - } - } - } - - private void setDataToAdapterFromMatchList(List<MatchType> matchList, PolicyRestAdapter policyAdapter){ - Iterator<MatchType> iterMatch = matchList.iterator(); - while (iterMatch.hasNext()) { - MatchType match = iterMatch.next(); - // - // Under the match we have attribute value and - // attributeDesignator. So,finally down to the actual attribute. - // - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - - if ("RiskType".equals(attributeId)){ - policyAdapter.setRiskType(value); - } - if ("RiskLevel".equals(attributeId)){ - policyAdapter.setRiskLevel(value); - } - if ("guard".equals(attributeId)){ - policyAdapter.setGuard(value); - } - if ("TTLDate".equals(attributeId) && !value.contains("NA")){ - PolicyController controller = new PolicyController(); - String newDate = controller.convertDate(value); - policyAdapter.setTtlDate(newDate); - } - } - } - - // This method generates the UI from rule configuration - public void paramUIGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - String data = entity.getConfigurationData().getConfigBody(); - if(data != null){ - try { - StringBuilder params = new StringBuilder(""); - Boolean flag = false; - Boolean comment = false; - for (String line : data.split("\n")) { - if (line.isEmpty() || line.startsWith("//")) { - continue; - } - if(line.contains(brmsTemplateVlaue)){ - String value = line.substring(line.indexOf("<$%"),line.indexOf("%$>")); - value = value.replace(brmsTemplateVlaue, ""); - policyAdapter.setRuleName(value); - } - if(line.contains("<%$Values=")) { - String value = line.substring(line.indexOf("<%$"), line.indexOf("$%>")); - value = value.replaceAll("<%\\$Values=", ""); - for( String keyValue : value.split(":\\|:")) { - String[] pair = keyValue.split(":-:"); - if (pair != null && pair.length > 0) { - dynamicLayoutMap.put(pair[0], (pair.length > 1) ? pair[1] : ""); - } - } - return; - } - if (line.startsWith("/*")) { - comment = true; - continue; - } - if ((line.contains("//"))&&(!(line.contains("http://") || line.contains("https://")))){ - line = line.split("\\/\\/")[0]; - } - if (line.contains("/*")) { - comment = true; - if (line.contains("*/")) { - try { - comment = false; - line = line.split("\\/\\*")[0] - + line.split("\\*\\/")[1].replace( - "*/", ""); - } catch (Exception e) { - policyLogger.info("Just for Logging"+e); - line = line.split("\\/\\*")[0]; - } - } else { - line = line.split("\\/\\*")[0]; - } - } - if (line.contains("*/")) { - comment = false; - try { - line = line.split("\\*\\/")[1] - .replace("*/", ""); - } catch (Exception e) { - policyLogger.info("Just for Logging"+e); - line = ""; - } - } - if (comment) { - continue; - } - if (flag) { - params.append(line); - } - if (line.contains("rule") && line.contains(".Params\"")) { - params.append(line); - flag = true; - } - if (line.contains("end") && flag) { - break; - } - } - params = new StringBuilder(params.substring(params.indexOf(".Params\"")+ 11)); - params = new StringBuilder(params.toString().replaceAll("\\s+", "").replace("salience1000whenthenParamsparams=newParams();","") - .replace("insert(params);end", "") - .replace("params.set", "")); - String[] components = params.toString().split("\\);"); - if(components!= null && components.length > 0){ - for (int i = 0; i < components.length; i++) { - String value; - components[i] = components[i]+")"; - String caption = components[i].substring(0, - components[i].indexOf('(')); - caption = caption.substring(0, 1).toLowerCase() + caption.substring(1); - if (components[i].contains("(\"")) { - value = components[i] - .substring(components[i].indexOf("(\""), - components[i].indexOf("\")")) - .replace("(\"", "").replace("\")", ""); - } else { - value = components[i] - .substring(components[i].indexOf('('), - components[i].indexOf(')')) - .replace("(", "").replace(")", ""); - } - dynamicLayoutMap.put(caption, value); - - } - } - } catch (Exception e) { - policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e); - } - } - - } - - // set View Rule - @SuppressWarnings("unchecked") - @RequestMapping(value={"/policyController/ViewBRMSParamPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public void setViewRule(HttpServletRequest request, HttpServletResponse response){ - try { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class); - policyData.setDomainDir(root.get(PolicyController.getPolicydata()).get("model").get("name").toString().replace("\"", "")); - if(root.get(PolicyController.getPolicydata()).get("model").get("type").toString().replace("\"", "").equals(PolicyController.getFile())){ - policyData.setEditPolicy(true); - } - - String body; - body = findRule((String) policyData.getRuleName()) + "\n"; - StringBuilder generatedMetadata = new StringBuilder(); - generatedMetadata.append("/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " + - brmsTemplateVlaue + policyData.getRuleName() + "%$> \n */ \n"); - - if(policyData.getDynamicLayoutMap().size() > 0){ - generatedMetadata.append("/* <%$Values="); - for (Entry<?, ?> entry : policyData.getRuleData().entrySet()) { - String uiKey = (String) entry.getKey(); - if(!"templateName".equals(uiKey)) { - generatedMetadata.append(uiKey+":-:"+entry.getValue()+":|:"); - } - } - generatedMetadata.append("$%> \n*/ \n"); - } - policyLogger.info("Metadata generated with :" + generatedMetadata.toString()); - body = generatedMetadata.toString() + body; - // Expand the body. - Map<String,String> copyMap=new HashMap<>(); - copyMap.putAll((Map<? extends String, ? extends String>) policyData.getRuleData()); - copyMap.put("policyName", policyData.getDomainDir().replace("\\", ".") +".Config_BRMS_Param_" + policyData.getPolicyName()); - copyMap.put("policyScope", policyData.getDomainDir().replace("\\", ".")); - copyMap.put("policyVersion", "1"); - //Finding all the keys in the Map data-structure. - Set<String> keySet= copyMap.keySet(); - Iterator<String> iterator = keySet.iterator(); - Pattern p; - Matcher m; - while(iterator.hasNext()) { - //Converting the first character of the key into a lower case. - String input= iterator.next(); - String output = Character.toLowerCase(input.charAt(0)) + - (input.length() > 1 ? input.substring(1) : ""); - //Searching for a pattern in the String using the key. - p=Pattern.compile("\\$\\{"+output+"\\}"); - m=p.matcher(body); - //Replacing the value with the inputs provided by the user in the editor. - body=m.replaceAll(copyMap.get(input)); - } - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(body); - JSONObject j = new JSONObject("{policyData: " + responseString + "}"); - out.write(j.toString()); - } catch (Exception e) { - policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } + private static final Logger policyLogger = FlexLogger.getLogger(CreateBRMSParamController.class); + + private static CommonClassDao commonClassDao; + + public static CommonClassDao getCommonClassDao() { + return commonClassDao; + } + + public static void setCommonClassDao(CommonClassDao commonClassDao) { + CreateBRMSParamController.commonClassDao = commonClassDao; + } + + @Autowired + private CreateBRMSParamController(CommonClassDao commonClassDao){ + CreateBRMSParamController.commonClassDao = commonClassDao; + } + + public CreateBRMSParamController(){ + // Empty constructor + } + protected PolicyRestAdapter policyAdapter = null; + + private HashMap<String, String> dynamicLayoutMap; + + private static String brmsTemplateVlaue = "<$%BRMSParamTemplate="; + private static String string = "String"; + + + @RequestMapping(value={"/policyController/getBRMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public void getBRMSParamPolicyRuleData(HttpServletRequest request, HttpServletResponse response){ + try{ + dynamicLayoutMap = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + String rule = findRule(root.get(PolicyController.getPolicydata()).toString().replaceAll("^\"|\"$", "")); + generateUI(rule); + response.setCharacterEncoding(PolicyController.getCharacterencoding()); + response.setContentType(PolicyController.getContenttype()); + request.setCharacterEncoding(PolicyController.getCharacterencoding()); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(dynamicLayoutMap); + JSONObject j = new JSONObject("{policyData: " + responseString + "}"); + out.write(j.toString()); + }catch(Exception e){ + policyLogger.error("Exception Occured while getting BRMS Rule data" , e); + } + } + + protected String findRule(String ruleTemplate) { + List<Object> datas = commonClassDao.getDataById(BRMSParamTemplate.class, "ruleName", ruleTemplate); + if(datas != null && !datas.isEmpty()){ + BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate) datas.get(0); + return bRMSParamTemplate.getRule(); + } + return null; + } + + protected void generateUI(String rule) { + if (rule==null){ + return; + } + try { + processRule(rule); + } catch (Exception e) { + policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + } + + } + + private void processRule(String rule) { + StringBuilder params = new StringBuilder(""); + Boolean flag = false; + Boolean comment = false; + String[] lines = rule.split("\n"); + for(String line : lines){ + if (line.isEmpty() || line.startsWith("//")) { + continue; + } + if (line.startsWith("/*")) { + comment = true; + continue; + } + if (line.contains("//")) { + line = splitSingleLineComment(line); + } + if (line.contains("/*")) { + comment = true; + if (line.contains("*/")) { + comment = false; + line = processMultiLineFullComment(line); + } else { + line = splitMultiLineStartComment(line); + } + } + if (line.contains("*/")) { + comment = false; + line = processEndComment(line); + } + if (comment) { + continue; + } + if (flag) { + params.append(line); + } + if (line.contains("declare Params")) { + params.append(line); + flag = true; + } + if (line.contains("end") && flag) { + break; + } + } + params = new StringBuilder(params.toString().replace("declare Params", "").replace("end", "").replaceAll("\\s+", "")); + String[] components = params.toString().split(":"); + String caption = ""; + for (int i = 0; i < components.length; i++) { + String type; + if (i == 0) { + caption = components[i]; + } + if("".equals(caption)){ + break; + } + String nextComponent = ""; + try { + nextComponent = components[i + 1]; + } catch (Exception e) { + policyLogger.info("Just for Logging"+e); + nextComponent = components[i]; + } + if (nextComponent.startsWith(string)) { + type = "String"; + createField(caption, type); + caption = nextComponent.replace(string, ""); + } else if (nextComponent.startsWith("int")) { + type = "int"; + createField(caption, type); + caption = nextComponent.replace("int", ""); + } + } + } + + private String splitMultiLineStartComment(String line) { + return line.split("\\/\\*")[0]; + } + + private String splitMultiLineEndComment(String line) { + return line.split("\\*\\/")[1].replace("*/", ""); + } + + private String splitSingleLineComment(String line) { + return line.split("\\/\\/")[0]; + } + + private void createField(String caption, String type) { + dynamicLayoutMap.put(caption, type); + } + + /* + * When the User Click Edit or View Policy the following method will get invoked for setting the data to PolicyRestAdapter. + * Which is used to bind the data in GUI + */ + public void prePopulateBRMSParamPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + dynamicLayoutMap = new HashMap<>(); + if (policyAdapter.getPolicyData() instanceof PolicyType) { + PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + // policy name value is the policy name without any prefix and + // Extensions. + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Param_") + 11); + if (policyLogger.isDebugEnabled()) { + policyLogger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName()); + } + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + policyLogger.info("Just for Logging"+e); + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + setDataAdapterFromAdviceExpressions(policy, policyAdapter); + paramUIGenerate(policyAdapter, entity); + // Get the target data under policy. + policyAdapter.setDynamicLayoutMap(dynamicLayoutMap); + if(policyAdapter.getDynamicLayoutMap().size() > 0){ + LinkedHashMap<String,String> drlRule = new LinkedHashMap<>(); + for(Object keyValue: policyAdapter.getDynamicLayoutMap().keySet()){ + drlRule.put(keyValue.toString(), policyAdapter.getDynamicLayoutMap().get(keyValue)); + } + policyAdapter.setRuleData(drlRule); + } + TargetType target = policy.getTarget(); + if (target != null) { + setDataToAdapterFromTarget(target, policyAdapter); + } + } + } + + private void setDataAdapterFromAdviceExpressions(PolicyType policy, PolicyRestAdapter policyAdapter){ + ArrayList<Object> attributeList = new ArrayList<>(); + // Set Attributes. + AdviceExpressionsType expressionTypes = ((RuleType)policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions(); + for( AdviceExpressionType adviceExpression: expressionTypes.getAdviceExpression()){ + for(AttributeAssignmentExpressionType attributeAssignment: adviceExpression.getAttributeAssignmentExpression()){ + if(attributeAssignment.getAttributeId().startsWith("key:")){ + Map<String, String> attribute = new HashMap<>(); + String key = attributeAssignment.getAttributeId().replace("key:", ""); + attribute.put("key", key); + @SuppressWarnings("unchecked") + JAXBElement<AttributeValueType> attributevalue = (JAXBElement<AttributeValueType>) attributeAssignment.getExpression(); + String value = (String) attributevalue.getValue().getContent().get(0); + attribute.put("value", value); + attributeList.add(attribute); + }else if(attributeAssignment.getAttributeId().startsWith("dependencies:")){ + ArrayList<String> dependencies = new ArrayList<>(Arrays.asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(","))); + if(dependencies.contains("")){ + dependencies.remove(""); + } + policyAdapter.setBrmsDependency(dependencies); + }else if(attributeAssignment.getAttributeId().startsWith("controller:")){ + policyAdapter.setBrmsController(attributeAssignment.getAttributeId().replace("controller:", "")); + } + } + policyAdapter.setAttributes(attributeList); + } + } + + private void setDataToAdapterFromTarget(TargetType target, PolicyRestAdapter policyAdapter){ + // Under target we have AnyOFType + List<AnyOfType> anyOfList = target.getAnyOf(); + + if (anyOfList == null) { + return; + } + + Iterator<AnyOfType> iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AnyOFType we have AllOFType + List<AllOfType> allOfList = anyOf.getAllOf(); + if (allOfList == null) { + continue; + } + Iterator<AllOfType> iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOFType we have Match + List<MatchType> matchList = allOf.getMatch(); + if (matchList != null) { + setDataToAdapterFromMatchList(matchList, policyAdapter); + } + } + } + } + + private void setDataToAdapterFromMatchList(List<MatchType> matchList, PolicyRestAdapter policyAdapter){ + Iterator<MatchType> iterMatch = matchList.iterator(); + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attribute value and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + + if ("RiskType".equals(attributeId)){ + policyAdapter.setRiskType(value); + } + if ("RiskLevel".equals(attributeId)){ + policyAdapter.setRiskLevel(value); + } + if ("guard".equals(attributeId)){ + policyAdapter.setGuard(value); + } + if ("TTLDate".equals(attributeId) && !value.contains("NA")){ + PolicyController controller = new PolicyController(); + String newDate = controller.convertDate(value); + policyAdapter.setTtlDate(newDate); + } + } + } + + // This method generates the UI from rule configuration + public void paramUIGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + String data = entity.getConfigurationData().getConfigBody(); + if(data == null){ + return; + } + + try { + StringBuilder params = new StringBuilder(""); + Boolean flag = false; + Boolean comment = false; + for (String line : data.split("\n")) { + if (line.isEmpty() || line.startsWith("//")) { + continue; + } + if(line.contains(brmsTemplateVlaue)){ + String value = line.substring(line.indexOf("<$%"),line.indexOf("%$>")); + value = value.replace(brmsTemplateVlaue, ""); + policyAdapter.setRuleName(value); + } + if(line.contains("<%$Values=")) { + String value = line.substring(line.indexOf("<%$"), line.indexOf("$%>")); + value = value.replaceAll("<%\\$Values=", ""); + for( String keyValue : value.split(":\\|:")) { + String[] pair = keyValue.split(":-:"); + if (pair != null && pair.length > 0) { + dynamicLayoutMap.put(pair[0], (pair.length > 1) ? pair[1] : ""); + } + } + return; + } + if (line.startsWith("/*")) { + comment = true; + continue; + } + if ((line.contains("//"))&&(!(line.contains("http://") || line.contains("https://")))){ + line = splitSingleLineComment(line); + } + if (line.contains("/*")) { + comment = true; + if (line.contains("*/")) { + comment = false; + line = processMultiLineFullComment(line); + } else { + line = splitMultiLineStartComment(line); + } + } + if (line.contains("*/")) { + comment = false; + line = processEndComment(line); + } + if (comment) { + continue; + } + if (flag) { + params.append(line); + } + if (line.contains("rule") && line.contains(".Params\"")) { + params.append(line); + flag = true; + } + if (line.contains("end") && flag) { + break; + } + } + params = new StringBuilder(params.substring(params.indexOf(".Params\"")+ 11)); + params = new StringBuilder(params.toString().replaceAll("\\s+", "").replace("salience1000whenthenParamsparams=newParams();","") + .replace("insert(params);end", "") + .replace("params.set", "")); + String[] components = params.toString().split("\\);"); + if(components!= null && components.length > 0){ + for (int i = 0; i < components.length; i++) { + String value; + components[i] = components[i]+")"; + String caption = components[i].substring(0, + components[i].indexOf('(')); + caption = caption.substring(0, 1).toLowerCase() + caption.substring(1); + if (components[i].contains("(\"")) { + value = components[i] + .substring(components[i].indexOf("(\""), + components[i].indexOf("\")")) + .replace("(\"", "").replace("\")", ""); + } else { + value = components[i] + .substring(components[i].indexOf('('), + components[i].indexOf(')')) + .replace("(", "").replace(")", ""); + } + dynamicLayoutMap.put(caption, value); + + } + } + } catch (Exception e) { + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e); + } + + + } + + private String processEndComment(String line) { + try { + line = splitMultiLineEndComment(line); + } catch (Exception e) { + policyLogger.info("Just for Logging"+e); + line = ""; + } + return line; + } + + private String processMultiLineFullComment(String line) { + try { + line = splitMultiLineStartComment(line) + + splitMultiLineEndComment(line); + } catch (Exception e) { + policyLogger.info("Just for Logging"+e); + line = splitMultiLineStartComment(line); + } + return line; + } + + // set View Rule + @SuppressWarnings("unchecked") + @RequestMapping(value={"/policyController/ViewBRMSParamPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public void setViewRule(HttpServletRequest request, HttpServletResponse response){ + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class); + policyData.setDomainDir(root.get(PolicyController.getPolicydata()).get("model").get("name").toString().replace("\"", "")); + if(root.get(PolicyController.getPolicydata()).get("model").get("type").toString().replace("\"", "").equals(PolicyController.getFile())){ + policyData.setEditPolicy(true); + } + + String body; + body = findRule((String) policyData.getRuleName()) + "\n"; + StringBuilder generatedMetadata = new StringBuilder(); + generatedMetadata.append("/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " + + brmsTemplateVlaue + policyData.getRuleName() + "%$> \n */ \n"); + + if(policyData.getDynamicLayoutMap().size() > 0){ + generatedMetadata.append("/* <%$Values="); + for (Entry<?, ?> entry : policyData.getRuleData().entrySet()) { + String uiKey = (String) entry.getKey(); + if(!"templateName".equals(uiKey)) { + generatedMetadata.append(uiKey+":-:"+entry.getValue()+":|:"); + } + } + generatedMetadata.append("$%> \n*/ \n"); + } + policyLogger.info("Metadata generated with :" + generatedMetadata.toString()); + body = generatedMetadata.toString() + body; + // Expand the body. + Map<String,String> copyMap=new HashMap<>(); + copyMap.putAll((Map<? extends String, ? extends String>) policyData.getRuleData()); + copyMap.put("policyName", policyData.getDomainDir().replace("\\", ".") +".Config_BRMS_Param_" + policyData.getPolicyName()); + copyMap.put("policyScope", policyData.getDomainDir().replace("\\", ".")); + copyMap.put("policyVersion", "1"); + //Finding all the keys in the Map data-structure. + Set<String> keySet= copyMap.keySet(); + Iterator<String> iterator = keySet.iterator(); + Pattern p; + Matcher m; + while(iterator.hasNext()) { + //Converting the first character of the key into a lower case. + String input= iterator.next(); + String output = Character.toLowerCase(input.charAt(0)) + + (input.length() > 1 ? input.substring(1) : ""); + //Searching for a pattern in the String using the key. + p=Pattern.compile("\\$\\{"+output+"\\}"); + m=p.matcher(body); + //Replacing the value with the inputs provided by the user in the editor. + body=m.replaceAll(copyMap.get(input)); + } + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(body); + JSONObject j = new JSONObject("{policyData: " + responseString + "}"); + out.write(j.toString()); + } catch (Exception e) { + policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } } |