X-Git-Url: https://gerrit.onap.org/r/gitweb?p=policy%2Fengine.git;a=blobdiff_plain;f=POLICY-SDK-APP%2Fsrc%2Fmain%2Fjava%2Forg%2Fonap%2Fpolicy%2Fcontroller%2FPolicyController.java;h=40f6be8d7a452904f646fcf14209abf3b305921c;hp=2200eae9914d680b488d3e470a241b7c4621558a;hb=f36e53a3637e1204a42491ec0eeed7b3c763f681;hpb=2cdbafa5550465315a2328ea302b333446e1465d diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java index 2200eae99..40f6be8d7 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java @@ -2,8 +2,9 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. + * Modifications Copyright (C) 2019 Bell Canada * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,27 +22,36 @@ package org.onap.policy.controller; +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; +import java.util.Set; import javax.annotation.PostConstruct; -import javax.mail.MessagingException; import javax.script.SimpleBindings; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; + import org.json.JSONObject; import org.onap.policy.admin.PolicyNotificationMail; import org.onap.policy.admin.RESTfulPAPEngine; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.model.PDPGroupContainer; @@ -53,9 +63,13 @@ import org.onap.policy.rest.jpa.FunctionDefinition; import org.onap.policy.rest.jpa.PolicyEntity; import org.onap.policy.rest.jpa.PolicyVersion; import org.onap.policy.rest.jpa.UserInfo; +import org.onap.policy.utils.PeCryptoUtils; +import org.onap.policy.utils.UserUtils.Pair; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.onap.policy.xacml.api.pap.PAPPolicyEngine; +import org.onap.policy.xacml.util.XACMLPolicyScanner; import org.onap.portalsdk.core.controller.RestrictedBaseController; +import org.onap.portalsdk.core.domain.UserApp; import org.onap.portalsdk.core.web.support.JsonMessage; import org.onap.portalsdk.core.web.support.UserUtils; import org.springframework.beans.factory.annotation.Autowired; @@ -65,14 +79,10 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; -import com.att.research.xacml.util.XACMLProperties; -import com.fasterxml.jackson.databind.ObjectMapper; - - @Controller @RequestMapping("/") public class PolicyController extends RestrictedBaseController { - private static final Logger policyLogger = FlexLogger.getLogger(PolicyController.class); + private static final Logger policyLogger = FlexLogger.getLogger(PolicyController.class); private static CommonClassDao commonClassDao; // @@ -83,6 +93,7 @@ public class PolicyController extends RestrictedBaseController { private static String logTableLimit; private static String systemAlertTableLimit; protected static Map dropDownMap = new HashMap<>(); + public static Map getDropDownMap() { return dropDownMap; } @@ -99,64 +110,66 @@ public class PolicyController extends RestrictedBaseController { private static Map> mapDatatype2Function = null; private static Map mapID2Function = null; - //Constant variables used across Policy-sdk + // Constant variables used across Policy-sdk private static final String policyData = "policyData"; private static final String characterEncoding = "UTF-8"; private static final String contentType = "application/json"; private static final String file = "file"; + private static final String SUPERADMIN = "super-admin"; + private static final String POLICYGUEST = "Policy Guest"; + private static final String LOGINID = "loginId"; - //Smtp Java Mail Properties + // Smtp Java Mail Properties private static String smtpHost = null; private static String smtpPort = null; private static String smtpUsername = null; private static String smtpPassword = null; private static String smtpApplicationName = null; private static String smtpEmailExtension = null; - //log db Properties + // log db Properties private static String logdbDriver = null; private static String logdbUrl = null; private static String logdbUserName = null; private static String logdbPassword = null; private static String logdbDialect = null; - //Xacml db properties + // Xacml db properties private static String xacmldbUrl = null; private static String xacmldbUserName = null; private static String xacmldbPassword = null; - //AutoPush feature. + // AutoPush feature. private static String autoPushAvailable; private static String autoPushDSClosedLoop; private static String autoPushDSFirewall; private static String autoPushDSMicroservice; private static String autoPushPDPGroup; - //papURL + // papURL private static String papUrl; - //MicroService Model Properties + // MicroService Model Properties private static String msOnapName; private static String msPolicyName; - //WebApp directories + // WebApp directories private static String configHome; private static String actionHome; - //File upload size + // File upload size private static long fileSizeLimit; private static boolean jUnit = false; - public static boolean isjUnit() { return jUnit; } - public static void setjUnit(boolean jUnit) { - PolicyController.jUnit = jUnit; + public static void setjUnit(boolean isJunit) { + PolicyController.jUnit = isJunit; } @Autowired - private PolicyController(CommonClassDao commonClassDao){ + private PolicyController(CommonClassDao commonClassDao) { PolicyController.commonClassDao = commonClassDao; } @@ -164,26 +177,30 @@ public class PolicyController extends RestrictedBaseController { // Empty constructor } + /** + * init method to load the properties. + */ @PostConstruct - public void init(){ + public void init() { Properties prop = new Properties(); try { String fileName; - if(jUnit){ - fileName = new File(".").getCanonicalPath() + File.separator + "src"+ File.separator + "test" + File.separator + "resources" + File.separator + "JSONConfig.json"; + if (jUnit) { + fileName = new File(".").getCanonicalPath() + File.separator + "src" + File.separator + "test" + + File.separator + "resources" + File.separator + "JSONConfig.json"; } else { fileName = "xacml.admin.properties"; } - try(InputStream input = new FileInputStream(fileName)) { + try (InputStream input = new FileInputStream(fileName)) { // load a properties file prop.load(input); } - //file upload size limit property + // file upload size limit property setFileSizeLimit(prop.getProperty("file.size.limit")); - //pap url + // pap url setPapUrl(prop.getProperty("xacml.rest.pap.url")); // get the property values setSmtpHost(prop.getProperty("onap.smtp.host")); @@ -192,60 +209,67 @@ public class PolicyController extends RestrictedBaseController { setSmtpPassword(prop.getProperty("onap.smtp.password")); setSmtpApplicationName(prop.getProperty("onap.application.name")); setSmtpEmailExtension(prop.getProperty("onap.smtp.emailExtension")); - //Log Database Properties + // Log Database Properties setLogdbDriver(prop.getProperty("xacml.log.db.driver")); setLogdbUrl(prop.getProperty("xacml.log.db.url")); setLogdbUserName(prop.getProperty("xacml.log.db.user")); - setLogdbPassword(prop.getProperty("xacml.log.db.password")); + setLogdbPassword(PeCryptoUtils.decrypt(prop.getProperty("xacml.log.db.password"))); setLogdbDialect(prop.getProperty("onap.dialect")); - //Xacml Database Properties + // Xacml Database Properties setXacmldbUrl(prop.getProperty("javax.persistence.jdbc.url")); setXacmldbUserName(prop.getProperty("javax.persistence.jdbc.user")); - setXacmldbPassword(prop.getProperty("javax.persistence.jdbc.password")); - //AutoPuh + setXacmldbPassword(PeCryptoUtils.decrypt(prop.getProperty("javax.persistence.jdbc.password"))); + // AutoPuh setAutoPushAvailable(prop.getProperty("xacml.automatic.push")); setAutoPushDSClosedLoop(prop.getProperty("xacml.autopush.closedloop")); setAutoPushDSFirewall(prop.getProperty("xacml.autopush.firewall")); setAutoPushDSMicroservice(prop.getProperty("xacml.autopush.microservice")); setAutoPushPDPGroup(prop.getProperty("xacml.autopush.pdpGroup")); - //Micro Service Properties + // Micro Service Properties setMsOnapName(prop.getProperty("xacml.policy.msOnapName")); - if(getMsOnapName() == null){ + if (getMsOnapName() == null) { setMsOnapName(prop.getProperty("xacml.policy.msEcompName")); } policyLogger.info("getMsOnapName => " + getMsOnapName()); setMsPolicyName(prop.getProperty("xacml.policy.msPolicyName")); policyLogger.info("setMsPolicyName => " + getMsPolicyName()); - //WebApp directories + // WebApp directories setConfigHome(prop.getProperty("xacml.rest.config.webapps") + "Config"); setActionHome(prop.getProperty("xacml.rest.config.webapps") + "Action"); - //Get the Property Values for Dashboard tab Limit - try{ + // Get the Property Values for Dashboard tab Limit + try { setLogTableLimit(prop.getProperty("xacml.onap.dashboard.logTableLimit")); setSystemAlertTableLimit(prop.getProperty("xacml.onap.dashboard.systemAlertTableLimit")); - }catch(Exception e){ - policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Dashboard tab Property fields are missing" +e); + } catch (Exception e) { + policyLogger + .error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Dashboard tab Property fields are missing" + e); setLogTableLimit("5000"); setSystemAlertTableLimit("2000"); } System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "xacml.admin.properties"); } catch (IOException ex) { - policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured while reading the Smtp properties from xacml.admin.properties file" +ex); + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + + "Exception Occured while reading the Smtp properties from xacml.admin.properties file" + ex); } - //Initialize the FunctionDefinition table at Server Start up + // Initialize the FunctionDefinition table at Server Start up Map> functionMap = getFunctionDatatypeMap(); - for ( Entry> entry : functionMap.entrySet()) { + for (Entry> entry : functionMap.entrySet()) { List functionDefinations = entry.getValue(); for (FunctionDefinition functionDef : functionDefinations) { - dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid()); + dropDownMap.put(functionDef.getShortname(), functionDef.getXacmlid()); } } } - public static Map> getFunctionDatatypeMap() { - synchronized(mapAccess) { + /** + * Get FunctionData Type from DB. + * + * @return list of FunctionData. + */ + public static Map> getFunctionDatatypeMap() { + synchronized (mapAccess) { if (mapDatatype2Function == null) { buildFunctionMaps(); } @@ -253,8 +277,13 @@ public class PolicyController extends RestrictedBaseController { return mapDatatype2Function; } - public static Map getFunctionIDMap() { - synchronized(mapAccess) { + /** + * Get Function ID. + * + * @return Function ID. + */ + public static Map getFunctionIdMap() { + synchronized (mapAccess) { if (mapID2Function == null) { buildFunctionMaps(); } @@ -262,11 +291,11 @@ public class PolicyController extends RestrictedBaseController { return mapID2Function; } - private static void buildFunctionMaps() { + private static void buildFunctionMaps() { mapDatatype2Function = new HashMap<>(); - mapID2Function = new HashMap<>(); + mapID2Function = new HashMap<>(); List functiondefinitions = commonClassDao.getData(FunctionDefinition.class); - for (int i = 0; i < functiondefinitions.size(); i ++) { + for (int i = 0; i < functiondefinitions.size(); i++) { FunctionDefinition value = (FunctionDefinition) functiondefinitions.get(i); mapID2Function.put(value.getXacmlid(), value); if (!mapDatatype2Function.containsKey(value.getDatatypeBean())) { @@ -276,83 +305,218 @@ public class PolicyController extends RestrictedBaseController { } } - @RequestMapping(value={"/get_FunctionDefinitionDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getFunctionDefinitionData(HttpServletRequest request, HttpServletResponse response){ - try{ + /** + * Get Functional Definition data. + * + * @param request HttpServletRequest. + * @param response HttpServletResponse. + */ + @RequestMapping( + value = {"/get_FunctionDefinitionDataByName"}, + method = {org.springframework.web.bind.annotation.RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getFunctionDefinitionData(HttpServletRequest request, HttpServletResponse response) { + try { Map model = new HashMap<>(); ObjectMapper mapper = new ObjectMapper(); - model.put("functionDefinitionDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(FunctionDefinition.class, "shortname"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE +"Error while retriving the Function Definition data"+e); + model.put("functionDefinitionDatas", + mapper.writeValueAsString(commonClassDao.getDataByColumn(FunctionDefinition.class, "shortname"))); + response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString()); + } catch (Exception e) { + policyLogger.error( + XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while retriving the Function Definition data" + e); } } - public PolicyEntity getPolicyEntityData(String scope, String policyName){ + /** + * Get PolicyEntity Data from db. + * + * @param scope scopeName. + * @param policyName policyName. + * @return policyEntity data. + */ + public PolicyEntity getPolicyEntityData(String scope, String policyName) { String key = scope + ":" + policyName; List data = commonClassDao.getDataById(PolicyEntity.class, "scope:policyName", key); return (PolicyEntity) data.get(0); } - public static Map getUserRoles(String userId) { - Map scopes = new HashMap<>(); - List roles = commonClassDao.getDataById(Roles.class, "loginId", userId); - if (roles != null && !roles.isEmpty()) { - for (Object role : roles) { - scopes.put(((Roles) role).getScope(), (Roles) role); - } - } - return scopes; - } - + /** + * Get Policy User Roles from db. + * + * @param userId LoginID. + * @return list of Roles. + */ public List getRolesOfUser(String userId) { List rolesList = new ArrayList<>(); - List roles = commonClassDao.getDataById(Roles.class, "loginId", userId); - for (Object role: roles) { + List roles = commonClassDao.getDataById(Roles.class, LOGINID, userId); + for (Object role : roles) { rolesList.add(((Roles) role).getRole()); } return rolesList; } public List getRoles(String userId) { - return commonClassDao.getDataById(Roles.class, "loginId", userId); - } - - //Get List of User Roles - @RequestMapping(value={"/get_UserRolesData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getUserRolesEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ + return commonClassDao.getDataById(Roles.class, LOGINID, userId); + } + + /** + * Get List of User Roles. + * + * @param request HttpServletRequest. + * @param response HttpServletResponse. + */ + @RequestMapping( + value = {"/get_UserRolesData"}, + method = {org.springframework.web.bind.annotation.RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getUserRolesEntityData(HttpServletRequest request, HttpServletResponse response) { + try { String userId = UserUtils.getUserSession(request).getOrgUserId(); Map model = new HashMap<>(); ObjectMapper mapper = new ObjectMapper(); model.put("userRolesDatas", mapper.writeValueAsString(getRolesOfUser(userId))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - policyLogger.error("Exception Occured"+e); + response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString()); + } catch (Exception e) { + policyLogger.error("Exception Occured" + e); } } - //Policy tabs Model and View - @RequestMapping(value= {"/policy", "/policy/Editor" } , method = RequestMethod.GET) - public ModelAndView view(HttpServletRequest request){ - String myRequestURL = request.getRequestURL().toString(); + /** + * Policy tabs Model and View. + * + * @param request Request input. + * @return view model. + */ + @RequestMapping(value = {"/policy", "/policy/Editor"}, method = RequestMethod.GET) + public ModelAndView view(HttpServletRequest request) { + getUserRoleFromSession(request); + String myRequestUrl = request.getRequestURL().toString(); try { // // Set the URL for the RESTful PAP Engine // - setPapEngine((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL)); - new PDPGroupContainer((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL)); + setPapEngine(new RESTfulPAPEngine(myRequestUrl)); + new PDPGroupContainer(new RESTfulPAPEngine(myRequestUrl)); } catch (Exception e) { - policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while loading PAP"+e); + policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception Occured while loading PAP" + e); } Map model = new HashMap<>(); - return new ModelAndView("policy_Editor","model", model); + return new ModelAndView("policy_Editor", "model", model); + } + + /** + * Read the role from session for inserting into the database. + * + * @param request Request input for Role. + */ + public void getUserRoleFromSession(HttpServletRequest request) { + // While user landing on Policy page, fetch the userId and Role from + // session. + // And, Query the Roles table and if user not exists or else modified + // update the Roles table. + List roles; + List newRoles = new ArrayList<>(); + String userId = UserUtils.getUserSession(request).getOrgUserId(); + String name = UserUtils.getUserSession(request).getFullName(); + @SuppressWarnings("unchecked") + Set userApps = UserUtils.getUserSession(request).getUserApps(); + for (UserApp userApp : userApps) { + newRoles.add(userApp.getRole().getName()); + } + List userRoles = getRoles(userId); + List filteredRoles = filterRole(newRoles); + if (!filteredRoles.isEmpty()) { + cleanUpRoles(filteredRoles, userId); + } + for (String filteredRole : filteredRoles) { + if (userRoles == null || userRoles.isEmpty()) { + savePolicyRoles(name, filteredRole, userId); + } else { + userRoles = getRoles(userId); + Pair, List> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles); + roles = pair.u; + if (!roles.contains(filteredRole)) { + savePolicyRoles(name, filteredRole, userId); + } + } + } + } + + /** + * Build a delete query for cleaning up roles and execute it. + * + * @param filteredRoles Filtered roles list. + * @param userId UserID. + */ + private void cleanUpRoles(List filteredRoles, String userId) { + StringBuilder query = new StringBuilder(); + query.append("delete from Roles where loginid = '" + userId + "'"); + if (filteredRoles.contains(SUPERADMIN)) { + query.append("and not role = '" + SUPERADMIN + "'"); + } else { + for (String filteredRole : filteredRoles) { + query.append("and not role = '" + filteredRole + "'"); + } + } + query.append("and id > 0"); + commonClassDao.updateQuery(query.toString()); + } + + /** + * Save the Role to DB. + * + * @param name User Name. + * @param filteredRole Role Name. + * @param userId User LoginID. + */ + private void savePolicyRoles(String name, String filteredRole, String userId) { + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId(userId); + userInfo.setUserName(name); + commonClassDao.save(userInfo); + Roles role = new Roles(); + role.setName(name); + role.setRole(filteredRole); + role.setLoginId(userId); + commonClassDao.save(role); + } + + /** + * Filter the list of roles hierarchy wise. + * + * @param newRoles list of roles from request. + * @return + */ + private List filterRole(List newRoles) { + List roles = new ArrayList<>(); + boolean superCheck = false; + for (String role : newRoles) { + if ("Policy Super Guest".equalsIgnoreCase(role.trim())) { + superCheck = true; + roles.add("super-guest"); + } else if ("Policy Super Editor".equalsIgnoreCase(role.trim())) { + superCheck = true; + roles.clear(); + roles.add("super-editor"); + } else if ("Policy Super Admin".equalsIgnoreCase(role.trim()) + || "System Administrator".equalsIgnoreCase(role.trim()) + || "Standard User".equalsIgnoreCase(role.trim())) { + superCheck = true; + roles.clear(); + roles.add(SUPERADMIN); + } + if (!roles.contains(SUPERADMIN) || (POLICYGUEST.equalsIgnoreCase(role) && !superCheck)) { + if ("Policy Admin".equalsIgnoreCase(role.trim())) { + roles.add("admin"); + } else if ("Policy Editor".equalsIgnoreCase(role.trim())) { + roles.add("editor"); + } else if (POLICYGUEST.equalsIgnoreCase(role.trim())) { + roles.add("guest"); + } + } + } + return roles; } public PAPPolicyEngine getPapEngine() { @@ -363,18 +527,26 @@ public class PolicyController extends RestrictedBaseController { PolicyController.papEngine = papEngine; } + /** + * Get UserName based on LoginID. + * + * @param createdBy loginID. + * @return name. + */ public String getUserName(String createdBy) { String loginId = createdBy; - List data = commonClassDao.getDataById(UserInfo.class, "loginId", loginId); + List data = commonClassDao.getDataById(UserInfo.class, LOGINID, loginId); return data.get(0).toString(); } + /** + * Check if the Policy is Active or not. + * + * @param query sql query. + * @return boolean. + */ public static boolean getActivePolicy(String query) { - if(!commonClassDao.getDataByQuery(query, new SimpleBindings()).isEmpty()){ - return true; - }else{ - return false; - } + return !commonClassDao.getDataByQuery(query, new SimpleBindings()).isEmpty(); } public void executeQuery(String query) { @@ -393,61 +565,71 @@ public class PolicyController extends RestrictedBaseController { commonClassDao.delete(entity); } - public List getData(@SuppressWarnings("rawtypes") Class className){ + public List getData(@SuppressWarnings("rawtypes") Class className) { return commonClassDao.getData(className); } - public PolicyVersion getPolicyEntityFromPolicyVersion(String query){ + public PolicyVersion getPolicyEntityFromPolicyVersion(String query) { return (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", query); } - public List getDataByQuery(String query, SimpleBindings params){ + public List getDataByQuery(String query, SimpleBindings params) { return commonClassDao.getDataByQuery(query, params); } - @SuppressWarnings("rawtypes") - public Object getEntityItem(Class className, String columname, String key){ + public Object getEntityItem(Class className, String columname, String key) { return commonClassDao.getEntityItem(className, columname, key); } - - public void watchPolicyFunction(PolicyVersion entity, String policyName, String mode){ + /** + * Watch Policy Function. + * + * @param entity PolicyVersion entity. + * @param policyName updated policy name. + * @param mode type of action rename/delete/import. + */ + public void watchPolicyFunction(PolicyVersion entity, String policyName, String mode) { PolicyNotificationMail email = new PolicyNotificationMail(); - try { - email.sendMail(entity, policyName, mode, commonClassDao); - } catch (MessagingException e) { - policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Excepton Occured while Renaming/Deleting a Policy or Scope" + e); - } + email.sendMail(entity, policyName, mode, commonClassDao); } - //Switch Version - public JSONObject switchVersionPolicyContent(String policyName) { + /** + * Switch Version Policy Content. + * + * @param thePolicyName which is used to find associated versions. + * @return list of available versions based on policy name. + */ + public JSONObject switchVersionPolicyContent(String thePolicyName) { + String policyName = thePolicyName; String dbCheckName = policyName.replace("/", "."); - if(dbCheckName.contains("Config_")){ + if (dbCheckName.contains("Config_")) { dbCheckName = dbCheckName.replace(".Config_", ":Config_"); - }else if(dbCheckName.contains("Action_")){ + } else if (dbCheckName.contains("Action_")) { dbCheckName = dbCheckName.replace(".Action_", ":Action_"); - }else if(dbCheckName.contains("Decision_")){ + } else if (dbCheckName.contains("Decision_MS_")) { + dbCheckName = dbCheckName.replace(".Decision_MS_", ":Decision_MS_"); + } else if (dbCheckName.contains("Decision_")) { dbCheckName = dbCheckName.replace(".Decision_", ":Decision_"); } - String[] splitDBCheckName = dbCheckName.split(":"); - String query = "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0"; + String[] splitDbCheckName = dbCheckName.split(":"); + String query = "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0"; SimpleBindings params = new SimpleBindings(); - params.put("splitDBCheckName1", splitDBCheckName[1] + "%"); - params.put("splitDBCheckName0", splitDBCheckName[0]); - List policyEntity = commonClassDao.getDataByQuery(query, params); + params.put("splitDBCheckName1", splitDbCheckName[1] + "%"); + params.put("splitDBCheckName0", splitDbCheckName[0]); List av = new ArrayList<>(); - for(Object entity : policyEntity){ - PolicyEntity pEntity = (PolicyEntity) entity; - String removeExtension = pEntity.getPolicyName().replace(".xml", ""); - String version = removeExtension.substring(removeExtension.lastIndexOf('.')+1); - av.add(version); + for (Object entity : commonClassDao.getDataByQuery(query, params)) { + PolicyEntity policyEntity = (PolicyEntity) entity; + String removeExtension = policyEntity.getPolicyName().replace(".xml", ""); + String version = removeExtension.substring(removeExtension.lastIndexOf('.') + 1); + String userName = getUserId(policyEntity, "@ModifiedBy:"); + av.add(version + " | " + policyEntity.getModifiedDate() + " | " + userName); } - if(policyName.contains("/")){ + if (policyName.contains("/")) { policyName = policyName.replace("/", File.separator); } - PolicyVersion entity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", policyName); + PolicyVersion entity = + (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", policyName); JSONObject el = new JSONObject(); el.put("activeVersion", entity.getActiveVersion()); el.put("availableVersions", av); @@ -455,6 +637,73 @@ public class PolicyController extends RestrictedBaseController { return el; } + /** + * getUserId. + * + * @param data PolicyEntity + * @param value String + * @return String + */ + public String getUserId(PolicyEntity data, String value) { + String userId = ""; + String userValue = value; // Why? + String description = getDescription(data); + if (description.contains(userValue)) { + userId = description.substring(description.indexOf(userValue) + userValue.length(), + description.lastIndexOf(userValue)); + } + UserInfo userInfo = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", userId); + if (userInfo == null) { + return SUPERADMIN; + } + return userInfo.getUserName(); + } + + /** + * getDescription. + * + * @param data PolicyEntity + * @return String + */ + public String getDescription(PolicyEntity data) { + InputStream stream = new ByteArrayInputStream(data.getPolicyData().getBytes(StandardCharsets.UTF_8)); + Object policy = XACMLPolicyScanner.readPolicy(stream); + if (policy instanceof PolicySetType) { + return ((PolicySetType) policy).getDescription(); + } else if (policy instanceof PolicyType) { + return ((PolicyType) policy).getDescription(); + } + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Expecting a PolicySet/Policy/Rule object. Got: " + + policy.getClass().getCanonicalName()); + return null; + } + + /** + * getUserInfo. + * + * @param data PolicyEntity + * @param activePolicies list of active policies + * @return array of String + */ + public String[] getUserInfo(PolicyEntity data, List activePolicies) { + String policyName = data.getScope().replace(".", File.separator) + File.separator + + data.getPolicyName().substring(0, data.getPolicyName().indexOf('.')); + PolicyVersion polVersion = + activePolicies.stream().filter(a -> policyName.equals(a.getPolicyName())).findAny().orElse(null); + String[] result = new String[2]; + UserInfo userCreate = null; + UserInfo userModify = null; + if (polVersion != null) { + userCreate = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", polVersion.getCreatedBy()); + userModify = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", polVersion.getModifiedBy()); + } + + result[0] = userCreate != null ? userCreate.getUserName() : SUPERADMIN; + result[1] = userModify != null ? userModify.getUserName() : SUPERADMIN; + + return result; + } + public static String getLogTableLimit() { return logTableLimit; } @@ -707,12 +956,16 @@ public class PolicyController extends RestrictedBaseController { return file; } + /** + * Set File Size limit. + * + * @param uploadSize value. + */ public static void setFileSizeLimit(String uploadSize) { - //Default size limit is 30MB + // Default size limit is 30MB if (uploadSize == null || uploadSize.isEmpty()) { fileSizeLimit = 30000000; - } - else { + } else { fileSizeLimit = Long.parseLong(uploadSize); } } @@ -720,10 +973,17 @@ public class PolicyController extends RestrictedBaseController { public static long getFileSizeLimit() { return fileSizeLimit; } - public String convertDate(String dateTTL) { + + /** + * Function to convert date. + * + * @param dateTimeToLive input date value. + * @return + */ + public String convertDate(String dateTimeToLive) { String formateDate = null; - if(dateTTL.contains("-")){ - formateDate = dateTTL.replace("-", "/"); + if (dateTimeToLive.contains("-")) { + formateDate = dateTimeToLive.replace("-", "/"); } return formateDate; }