X-Git-Url: https://gerrit.onap.org/r/gitweb?a=blobdiff_plain;f=POLICY-SDK-APP%2Fsrc%2Fmain%2Fjava%2Forg%2Fonap%2Fpolicy%2Fcontroller%2FPolicyController.java;h=700aa3a578ed16fb5256a0e9fe221d0079b1388c;hb=c1b69dfb1297365d35f2ada8690f13f787d38b4f;hp=3b4d03de8a4108189977cc1e400ed3159ad44742;hpb=75d9db3e29232580871c106560016be6492255d6;p=policy%2Fengine.git 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 3b4d03de8..700aa3a57 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. @@ -23,10 +24,12 @@ 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; @@ -34,15 +37,17 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; -import java.util.TreeMap; 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; @@ -54,9 +59,11 @@ 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; @@ -68,7 +75,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; - @Controller @RequestMapping("/") public class PolicyController extends RestrictedBaseController { @@ -105,6 +111,9 @@ public class PolicyController extends RestrictedBaseController { 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 private static String smtpHost = null; @@ -147,7 +156,6 @@ public class PolicyController extends RestrictedBaseController { private static boolean jUnit = false; - public static boolean isjUnit() { return jUnit; } @@ -175,8 +183,9 @@ public class PolicyController extends RestrictedBaseController { try { String fileName; if (jUnit) { - fileName = new File(".").getCanonicalPath() + File.separator + "src" + File.separator + "test" - + File.separator + "resources" + File.separator + "JSONConfig.json"; + fileName = new File(".").getCanonicalPath() + File.separator + "src" + + File.separator + "test" + File.separator + "resources" + File.separator + + "JSONConfig.json"; } else { fileName = "xacml.admin.properties"; } @@ -201,12 +210,12 @@ public class PolicyController extends RestrictedBaseController { 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 setXacmldbUrl(prop.getProperty("javax.persistence.jdbc.url")); setXacmldbUserName(prop.getProperty("javax.persistence.jdbc.user")); - setXacmldbPassword(prop.getProperty("javax.persistence.jdbc.password")); + setXacmldbPassword(PeCryptoUtils.decrypt(prop.getProperty("javax.persistence.jdbc.password"))); // AutoPuh setAutoPushAvailable(prop.getProperty("xacml.automatic.push")); setAutoPushDSClosedLoop(prop.getProperty("xacml.autopush.closedloop")); @@ -227,17 +236,19 @@ public class PolicyController extends RestrictedBaseController { // Get the Property Values for Dashboard tab Limit try { setLogTableLimit(prop.getProperty("xacml.onap.dashboard.logTableLimit")); - setSystemAlertTableLimit(prop.getProperty("xacml.onap.dashboard.systemAlertTableLimit")); + setSystemAlertTableLimit( + prop.getProperty("xacml.onap.dashboard.systemAlertTableLimit")); } catch (Exception e) { - policyLogger - .error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Dashboard tab Property fields are missing" + 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); + + "Exception Occured while reading the Smtp properties from xacml.admin.properties file" + + ex); } // Initialize the FunctionDefinition table at Server Start up @@ -253,7 +264,7 @@ public class PolicyController extends RestrictedBaseController { /** * Get FunctionData Type from DB. - * + * * @return list of FunctionData. */ public static Map> getFunctionDatatypeMap() { @@ -267,7 +278,7 @@ public class PolicyController extends RestrictedBaseController { /** * Get Function ID. - * + * * @return Function ID. */ public static Map getFunctionIdMap() { @@ -287,7 +298,8 @@ public class PolicyController extends RestrictedBaseController { FunctionDefinition value = (FunctionDefinition) functiondefinitions.get(i); mapID2Function.put(value.getXacmlid(), value); if (!mapDatatype2Function.containsKey(value.getDatatypeBean())) { - mapDatatype2Function.put(value.getDatatypeBean(), new ArrayList()); + mapDatatype2Function.put(value.getDatatypeBean(), + new ArrayList()); } mapDatatype2Function.get(value.getDatatypeBean()).add(value); } @@ -295,31 +307,32 @@ public class PolicyController extends RestrictedBaseController { /** * 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) { + 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"))); + 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); + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + + "Error while retriving the Function Definition data" + e); } } /** * Get PolicyEntity Data from db. - * + * * @param scope scopeName. * @param policyName policyName. * @return policyEntity data. @@ -332,13 +345,13 @@ public class PolicyController extends RestrictedBaseController { /** * 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); + List roles = commonClassDao.getDataById(Roles.class, LOGINID, userId); for (Object role : roles) { rolesList.add(((Roles) role).getRole()); } @@ -346,12 +359,12 @@ public class PolicyController extends RestrictedBaseController { } public List getRoles(String userId) { - return commonClassDao.getDataById(Roles.class, "loginId", userId); + return commonClassDao.getDataById(Roles.class, LOGINID, userId); } /** * Get List of User Roles. - * + * * @param request HttpServletRequest. * @param response HttpServletResponse. */ @@ -374,7 +387,7 @@ public class PolicyController extends RestrictedBaseController { /** * Policy tabs Model and View. - * + * * @param request Request input. * @return view model. */ @@ -386,19 +399,20 @@ public class PolicyController extends RestrictedBaseController { // // 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); } /** - * Read the role from session. - * - * @param request Request input. + * 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 @@ -415,23 +429,48 @@ public class PolicyController extends RestrictedBaseController { newRoles.add(userApp.getRole().getName()); } List userRoles = getRoles(userId); - String filteredRole = filterRole(newRoles); - if (userRoles == null || userRoles.isEmpty()) { - savePolicyRoles(name, filteredRole, userId); - } else { - Pair, List> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles); - roles = pair.u; - if (!roles.contains(filteredRole)) { - String query = "delete from Roles where loginid='" + userId + "'"; - commonClassDao.updateQuery(query); + 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. @@ -450,29 +489,40 @@ public class PolicyController extends RestrictedBaseController { /** * Filter the list of roles hierarchy wise. - * + * * @param newRoles list of roles from request. * @return */ - private String filterRole(List newRoles) { - Map roleMap = new TreeMap<>(); - roleMap.put(6, "guest"); + private List filterRole(List newRoles) { + List roles = new ArrayList<>(); + boolean superCheck = false; for (String role : newRoles) { - if ("Policy Super Admin".equalsIgnoreCase(role.trim()) + 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())) { - roleMap.put(1, "super-admin"); - } else if ("Policy Super Editor".equalsIgnoreCase(role.trim())) { - roleMap.put(2, "super-editor"); - } else if ("Policy Super Guest".equalsIgnoreCase(role.trim())) { - roleMap.put(3, "super-guest"); - } else if ("Policy Admin".equalsIgnoreCase(role.trim())) { - roleMap.put(4, "admin"); - } else if ("Policy Editor".equalsIgnoreCase(role.trim())) { - roleMap.put(5, "editor"); + 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 roleMap.entrySet().iterator().next().getValue(); + return roles; } public PAPPolicyEngine getPapEngine() { @@ -485,18 +535,19 @@ public class PolicyController extends RestrictedBaseController { /** * 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. */ @@ -525,40 +576,34 @@ public class PolicyController extends RestrictedBaseController { } public PolicyVersion getPolicyEntityFromPolicyVersion(String query) { - return (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", query); + return (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", + query); } public List getDataByQuery(String query, SimpleBindings params) { return commonClassDao.getDataByQuery(query, params); } - @SuppressWarnings("rawtypes") public Object getEntityItem(Class className, String columname, String key) { return commonClassDao.getEntityItem(className, columname, key); } - /** * 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 Policy Content. - * + * * @param pName which is used to find associated versions. * @return list of available versions based on policy name. */ @@ -569,11 +614,14 @@ public class PolicyController extends RestrictedBaseController { dbCheckName = dbCheckName.replace(".Config_", ":Config_"); } else if (dbCheckName.contains("Action_")) { dbCheckName = dbCheckName.replace(".Action_", ":Action_"); + } 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 query = + "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0"; SimpleBindings params = new SimpleBindings(); params.put("splitDBCheckName1", splitDbCheckName[1] + "%"); params.put("splitDBCheckName0", splitDbCheckName[0]); @@ -583,13 +631,14 @@ public class PolicyController extends RestrictedBaseController { PolicyEntity pEntity = (PolicyEntity) entity; String removeExtension = pEntity.getPolicyName().replace(".xml", ""); String version = removeExtension.substring(removeExtension.lastIndexOf('.') + 1); - av.add(version); + String userName = getUserId(pEntity, "@ModifiedBy:"); + av.add(version + " | " + pEntity.getModifiedDate() + " | " + userName); } 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); @@ -597,6 +646,58 @@ public class PolicyController extends RestrictedBaseController { return el; } + public String getUserId(PolicyEntity data, String value) { + String userId = ""; + String uValue = value; + String description = getDescription(data); + if (description.contains(uValue)) { + userId = description.substring(description.indexOf(uValue) + uValue.length(), + description.lastIndexOf(uValue)); + } + UserInfo userInfo = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", userId); + if (userInfo == null) { + return SUPERADMIN; + } + return userInfo.getUserName(); + } + + 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(); + } else { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + + "Expecting a PolicySet/Policy/Rule object. Got: " + + policy.getClass().getCanonicalName()); + return null; + } + } + + 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; } @@ -625,7 +726,8 @@ public class PolicyController extends RestrictedBaseController { return mapDatatype2Function; } - public static void setMapDatatype2Function(Map> mapDatatype2Function) { + public static void setMapDatatype2Function( + Map> mapDatatype2Function) { PolicyController.mapDatatype2Function = mapDatatype2Function; } @@ -851,7 +953,7 @@ public class PolicyController extends RestrictedBaseController { /** * Set File Size limit. - * + * * @param uploadSize value. */ public static void setFileSizeLimit(String uploadSize) { @@ -869,7 +971,7 @@ public class PolicyController extends RestrictedBaseController { /** * Function to convert date. - * + * * @param dateTTL input date value. * @return */