diff options
Diffstat (limited to 'POLICY-SDK-APP')
12 files changed, 716 insertions, 773 deletions
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java index 8349fab82..f91815992 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java @@ -4,13 +4,14 @@ * ================================================================================ * Copyright (C) 2017 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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -46,24 +47,23 @@ import org.onap.policy.xacml.api.XACMLErrorConstants; import com.att.research.xacml.util.XACMLProperties; /** - * What is not good about this class is that once a value has been set for pdpProperties path - * you cannot change it. That may be ok for a highly controlled production environment in which - * nothing changes, but not a very good implementation. - * - * The reset() method has been added to assist with the above problem in order to - * acquire >80% JUnit code coverage. - * - * This static class doesn't really check a PDP, it simply loads a properties file and tried - * to ensure that a valid URL exists for a PDP along with user/password. + * What is not good about this class is that once a value has been set for pdpProperties path you cannot change it. That + * may be ok for a highly controlled production environment in which nothing changes, but not a very good + * implementation. * + * The reset() method has been added to assist with the above problem in order to acquire >80% JUnit code coverage. + * + * This static class doesn't really check a PDP, it simply loads a properties file and tried to ensure that a valid URL + * exists for a PDP along with user/password. */ public class CheckPDP { + private static Path pdpPath = null; private static Long oldModified = null; private static HashMap<String, String> pdpMap = null; private static final Logger LOGGER = FlexLogger.getLogger(CheckPDP.class); - private CheckPDP(){ + private CheckPDP() { //default constructor } @@ -92,28 +92,27 @@ public class CheckPDP { return pdpMap.containsKey(id); } - private static void readFile(){ - String pdpFile = null; - try{ + private static void readFile() { + String pdpFile; + try { pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE); - }catch (Exception e){ + } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot read the PDP ID File" + e); return; } if (pdpFile == null) { LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PDP File name not Valid : " + pdpFile); - } - if (pdpPath == null) { + } else if (pdpPath == null) { pdpPath = Paths.get(pdpFile); if (!pdpPath.toString().endsWith(".properties") || !pdpPath.toFile().exists()) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path : " + pdpPath.toString()); + LOGGER.error( + XACMLErrorConstants.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path : " + pdpPath + .toString()); CheckPDP.reset(); return; } readProps(); - } - // Check if File is updated recently - else { + } else { // Check if File is updated recently Long newModified = pdpPath.toFile().lastModified(); if (!newModified.equals(oldModified)) { // File has been updated. @@ -122,11 +121,11 @@ public class CheckPDP { } } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) private static void readProps() { Properties pdpProp; pdpProp = new Properties(); - try(InputStream in = new FileInputStream(pdpPath.toFile())) { + try (InputStream in = new FileInputStream(pdpPath.toFile())) { oldModified = pdpPath.toFile().lastModified(); pdpProp.load(in); // Read the Properties and Load the PDPs and encoding. @@ -147,7 +146,7 @@ public class CheckPDP { } } - private static void loadPDPProperties(String propKey, Properties pdpProp){ + private static void loadPDPProperties(String propKey, Properties pdpProp) { if (propKey.startsWith("PDP_URL")) { String checkVal = pdpProp.getProperty(propKey); if (checkVal == null) { @@ -165,39 +164,40 @@ public class CheckPDP { } } - private static void readPDPParam(String pdpVal){ - if(pdpVal.contains(",")){ + private static void readPDPParam(String pdpVal) { + if (pdpVal.contains(",")) { List<String> pdpValues = new ArrayList<>(Arrays.asList(pdpVal.split("\\s*,\\s*"))); - if(pdpValues.size()==3){ + if (pdpValues.size() == 3) { // 1:2 will be UserID:Password String userID = pdpValues.get(1); String pass = pdpValues.get(2); Base64.Encoder encoder = Base64.getEncoder(); // 0 - PDPURL - pdpMap.put(pdpValues.get(0), encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8))); - }else{ + pdpMap.put(pdpValues.get(0), + encoder.encodeToString((userID + ":" + pass).getBytes(StandardCharsets.UTF_8))); + } else { LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpValues); } - }else{ + } else { LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpVal); } } - public static String getEncoding(String pdpID){ + public static String getEncoding(String pdpID) { try { readFile(); } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); } String encoding = null; - if(pdpMap!=null && (!pdpMap.isEmpty())){ - try{ + if (pdpMap != null && (!pdpMap.isEmpty())) { + try { encoding = pdpMap.get(pdpID); - } catch(Exception e){ + } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); } return encoding; - }else{ + } else { return null; } } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java index be660c803..6aa40dacf 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2017 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. @@ -40,7 +41,7 @@ import com.att.research.xacml.util.XACMLProperties; public class PolicyAdapter { - private static final Logger LOGGER = FlexLogger.getLogger(PolicyAdapter.class); + private static final Logger LOGGER = FlexLogger.getLogger(PolicyAdapter.class); public void configure(PolicyRestAdapter policyAdapter, PolicyEntity entity) { String policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf('_')); @@ -50,77 +51,70 @@ public class PolicyAdapter { if (configPolicyName != null) { policyAdapter.setConfigPolicyType(configPolicyName); } - - if("Action".equalsIgnoreCase(policyAdapter.getPolicyType())){ - new ActionPolicyController().prePopulateActionPolicyData(policyAdapter, entity); + if ("Action".equalsIgnoreCase(policyAdapter.getPolicyType())) { + new ActionPolicyController().prePopulateActionPolicyData(policyAdapter); } - if("Decision".equalsIgnoreCase(policyAdapter.getPolicyType())){ + if ("Decision".equalsIgnoreCase(policyAdapter.getPolicyType())) { new DecisionPolicyController().prePopulateDecisionPolicyData(policyAdapter, entity); } - if("Config".equalsIgnoreCase(policyAdapter.getPolicyType())){ + if ("Config".equalsIgnoreCase(policyAdapter.getPolicyType())) { prePopulatePolicyData(policyAdapter, entity); } } private String getConfigPolicyName(PolicyRestAdapter policyAdapter) { - String configPolicyName = null ; - if(policyAdapter.getPolicyName().startsWith("Config_PM")){ + String configPolicyName = null; + if (policyAdapter.getPolicyName().startsWith("Config_PM")) { configPolicyName = "ClosedLoop_PM"; - }else if(policyAdapter.getPolicyName().startsWith("Config_Fault")){ + } else if (policyAdapter.getPolicyName().startsWith("Config_Fault")) { configPolicyName = "ClosedLoop_Fault"; - }else if(policyAdapter.getPolicyName().startsWith("Config_FW")){ + } else if (policyAdapter.getPolicyName().startsWith("Config_FW")) { configPolicyName = "Firewall Config"; - }else if(policyAdapter.getPolicyName().startsWith("Config_BRMS_Raw")){ + } else if (policyAdapter.getPolicyName().startsWith("Config_BRMS_Raw")) { configPolicyName = "BRMS_Raw"; - }else if(policyAdapter.getPolicyName().startsWith("Config_BRMS_Param")){ + } else if (policyAdapter.getPolicyName().startsWith("Config_BRMS_Param")) { configPolicyName = "BRMS_Param"; - }else if(policyAdapter.getPolicyName().startsWith("Config_MS")){ + } else if (policyAdapter.getPolicyName().startsWith("Config_MS")) { configPolicyName = "Micro Service"; - }else if(policyAdapter.getPolicyName().startsWith("Config_OOF")){ + } else if (policyAdapter.getPolicyName().startsWith("Config_OOF")) { configPolicyName = "Optimization"; - }else if(policyAdapter.getPolicyName().startsWith("Action") || policyAdapter.getPolicyName().startsWith("Decision") ){ + } else if (policyAdapter.getPolicyName().startsWith("Action") || policyAdapter.getPolicyName() + .startsWith("Decision")) { // No configPolicyName is applicable - }else{ + } else { configPolicyName = "Base"; } return configPolicyName; } private void prePopulatePolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - if("Base".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + if ("Base".equalsIgnoreCase(policyAdapter.getConfigPolicyType())) { new CreatePolicyController().prePopulateBaseConfigPolicyData(policyAdapter, entity); - } - else if("BRMS_Raw".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + } else if ("BRMS_Raw".equalsIgnoreCase(policyAdapter.getConfigPolicyType())) { new CreateBRMSRawController().prePopulateBRMSRawPolicyData(policyAdapter, entity); - } - else if("BRMS_Param".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + } else if ("BRMS_Param".equalsIgnoreCase(policyAdapter.getConfigPolicyType())) { new CreateBRMSParamController().prePopulateBRMSParamPolicyData(policyAdapter, entity); - } - else if("ClosedLoop_Fault".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + } else if ("ClosedLoop_Fault".equalsIgnoreCase(policyAdapter.getConfigPolicyType())) { new CreateClosedLoopFaultController().prePopulateClosedLoopFaultPolicyData(policyAdapter, entity); - } - else if("ClosedLoop_PM".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + } else if ("ClosedLoop_PM".equalsIgnoreCase(policyAdapter.getConfigPolicyType())) { new CreateClosedLoopPMController().prePopulateClosedLoopPMPolicyData(policyAdapter, entity); - } - else if("Micro Service".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + } else if ("Micro Service".equalsIgnoreCase(policyAdapter.getConfigPolicyType())) { new CreateDcaeMicroServiceController().prePopulateDCAEMSPolicyData(policyAdapter, entity); - } - else if("Optimization".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + } else if ("Optimization".equalsIgnoreCase(policyAdapter.getConfigPolicyType())) { new CreateOptimizationController().prePopulatePolicyData(policyAdapter, entity); - } - else if("Firewall Config".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + } else if ("Firewall Config".equalsIgnoreCase(policyAdapter.getConfigPolicyType())) { new CreateFirewallController().prePopulateFWPolicyData(policyAdapter, entity); } } public static PolicyAdapter getInstance() { try { - Class<?> policyAdapter = Class.forName(XACMLProperties.getProperty("policyAdapter.impl.className", PolicyAdapter.class.getName())); + Class<?> policyAdapter = Class + .forName(XACMLProperties.getProperty("policyAdapter.impl.className", PolicyAdapter.class.getName())); return (PolicyAdapter) policyAdapter.newInstance(); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException e) { - LOGGER.error("Exception Occured"+e); + LOGGER.error("Exception Occurred" + e); } return null; } - -}
\ No newline at end of file +} 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 baf27b06f..d289feaaf 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 @@ -4,6 +4,7 @@ * ================================================================================ * 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. @@ -55,6 +56,7 @@ import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.http.HttpStatus; +import org.elasticsearch.common.Strings; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -393,8 +395,7 @@ public class PolicyManagerServlet extends HttpServlet { if (scopes.isEmpty()) { return false; } - Set<String> tempScopes = scopes; - for (String scope : tempScopes) { + for (String scope : scopes) { addScope(scopes, scope); } } @@ -416,8 +417,8 @@ public class PolicyManagerServlet extends HttpServlet { 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) { + List<Object> filterData = controller.getData(PolicyVersion.class); + for (Object filter : filterData) { addFilterData(policyData, scopes, (PolicyVersion) filter); } } @@ -579,12 +580,7 @@ public class PolicyManagerServlet extends HttpServlet { SimpleBindings peParams = new SimpleBindings(); peParams.put(SPLIT_1, split[1]); peParams.put(SPLIT_0, split[0]); - List<Object> queryData; - if (PolicyController.isjUnit()) { - queryData = controller.getDataByQuery(query, null); - } else { - queryData = controller.getDataByQuery(query, peParams); - } + List<Object> queryData = getDataByQueryFromController(controller, query, peParams); if (queryData.isEmpty()) { return error("Error Occured while Describing the Policy - query is empty"); } @@ -644,7 +640,7 @@ public class PolicyManagerServlet extends HttpServlet { return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin"); } else { if (!FORWARD_SLASH.equals(path)) { - String tempScope = path.substring(1, path.length()); + String tempScope = path.substring(1); tempScope = tempScope.replace(FORWARD_SLASH, File.separator); scopes.add(tempScope); } @@ -656,13 +652,11 @@ public class PolicyManagerServlet extends HttpServlet { String scopeName = path.substring(path.indexOf('/') + 1); activePolicyList(scopeName, resultList, roles, scopes, roleByScope); } catch (Exception ex) { - LOGGER.error("Error Occured While reading Policy Files List" + ex); + LOGGER.error("Error Occurred While reading Policy Files List" + ex); } return new JSONObject().put(RESULT, resultList); } - processRoles(scopes, roles, resultList, roleByScope); - return new JSONObject().put(RESULT, resultList); } @@ -670,9 +664,11 @@ public class PolicyManagerServlet extends HttpServlet { Map<String, String> roleByScope) { 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))) { + scopesList.stream() + .map(list -> (PolicyEditorScopes) list) + .filter(scope -> !(scope.getScopeName().contains(File.separator)) + && !scopes.contains(scope.getScopeName())) + .forEach(scope -> { JSONObject el = new JSONObject(); el.put(NAME, scope.getScopeName()); el.put(DATE, scope.getModifiedDate()); @@ -681,17 +677,14 @@ public class PolicyManagerServlet extends HttpServlet { el.put(CREATED_BY, scope.getUserCreatedBy().getUserName()); el.put(MODIFIED_BY, scope.getUserModifiedBy().getUserName()); el.put(ROLETYPE, roleByScope.get(ALLSCOPES)); - if (!scopes.contains(scope.getScopeName())) { - resultList.add(el); - } - } - } + resultList.add(el); + }); } 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()) { + scopes.stream().map(this::queryPolicyEditorScopes) + .filter(scopesList -> !scopesList.isEmpty()) + .forEach(scopesList -> { + JSONObject el = new JSONObject(); PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0); el.put(NAME, scopeById.getScopeName()); el.put(DATE, scopeById.getModifiedDate()); @@ -699,35 +692,28 @@ public class PolicyManagerServlet extends HttpServlet { el.put(TYPE, "dir"); el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName()); el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName()); - if (!(resultList).stream().anyMatch(item -> item.get("name").equals(scopeById.getScopeName()))) { + if ((resultList).stream().noneMatch(item -> item.get("name").equals(scopeById.getScopeName()))) { el.put(ROLETYPE, roleByScope.get(scopeById.getScopeName())); resultList.add(el); } - } - } + }); } } private List<Object> queryPolicyEditorScopes(String scopeName) { - String scopeNamequery; + String scopeNameQuery; SimpleBindings params = new SimpleBindings(); if (scopeName == null) { - scopeNamequery = "from PolicyEditorScopes"; + scopeNameQuery = "from PolicyEditorScopes"; } else { - scopeNamequery = FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME; + scopeNameQuery = FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME; params.put(SCOPE_NAME, scopeName + "%"); } PolicyController controller = getPolicyControllerInstance(); - List<Object> scopesList; - if (PolicyController.isjUnit()) { - scopesList = controller.getDataByQuery(scopeNamequery, null); - } else { - scopesList = controller.getDataByQuery(scopeNamequery, params); - } - return scopesList; + return getDataByQueryFromController(controller, scopeNameQuery, params); } - // Get Active Policy List based on Scope Selection form Policy Version table + // Get Active Policy List based on Scope Selection from Policy Version table private void activePolicyList(String inScopeName, List<JSONObject> resultList, List<String> roles, Set<String> scopes, Map<String, String> roleByScope) { PolicyController controller = getPolicyControllerInstance(); @@ -739,51 +725,39 @@ public class PolicyManagerServlet extends HttpServlet { scopeName = scopeName.replace(BACKSLASH, ESCAPE_BACKSLASH); } String query = "from PolicyVersion where POLICY_NAME like :scopeName"; - String scopeNamequery = FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME; SimpleBindings params = new SimpleBindings(); params.put(SCOPE_NAME, scopeName + "%"); - List<Object> activePolicies; - List<Object> scopesList; - if (PolicyController.isjUnit()) { - activePolicies = controller.getDataByQuery(query, null); - scopesList = controller.getDataByQuery(scopeNamequery, null); - } else { - activePolicies = controller.getDataByQuery(query, params); - scopesList = controller.getDataByQuery(scopeNamequery, params); - } + List<Object> activePolicies = getDataByQueryFromController(controller, query, params); + List<Object> scopesList = getDataByQueryFromController(controller, + FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME, params); for (Object list : scopesList) { scopeName = checkScope(resultList, scopeName, (PolicyEditorScopes) list, roleByScope); } - String scopeNameCheck; for (Object list : activePolicies) { PolicyVersion policy = (PolicyVersion) list; String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator)); if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) { - if (scopeName.contains(ESCAPE_BACKSLASH)) { - scopeNameCheck = scopeName.replace(ESCAPE_BACKSLASH, File.separator); - } else { - scopeNameCheck = scopeName; - } - if (scopeNameValue.equals(scopeNameCheck)) { - JSONObject el = new JSONObject(); - el.put(NAME, - policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator) + 1)); - el.put(DATE, policy.getModifiedDate()); - el.put(VERSION, policy.getActiveVersion()); - el.put(SIZE, ""); - el.put(TYPE, "file"); - el.put(CREATED_BY, getUserName(policy.getCreatedBy())); - el.put(MODIFIED_BY, getUserName(policy.getModifiedBy())); - String roleType = roleByScope.get(scopeNameValue); - if (roleType == null) { - roleType = roleByScope.get(ALLSCOPES); - } - el.put(ROLETYPE, roleType); - resultList.add(el); + String scopeNameCheck = + scopeName.contains(ESCAPE_BACKSLASH) ? scopeName.replace(ESCAPE_BACKSLASH, File.separator) : + scopeName; + if (!scopeNameValue.equals(scopeNameCheck)) { + continue; } + JSONObject el = new JSONObject(); + el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator) + 1)); + el.put(DATE, policy.getModifiedDate()); + el.put(VERSION, policy.getActiveVersion()); + el.put(SIZE, ""); + el.put(TYPE, "file"); + el.put(CREATED_BY, getUserName(policy.getCreatedBy())); + el.put(MODIFIED_BY, getUserName(policy.getModifiedBy())); + String roleType = Strings.isNullOrEmpty(roleByScope.get(scopeNameValue)) ? + roleByScope.get(ALLSCOPES) : roleByScope.get(scopeNameValue); + el.put(ROLETYPE, roleType); + resultList.add(el); } else if (!scopes.isEmpty() && scopes.contains(scopeNameValue)) { JSONObject el = new JSONObject(); el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator) + 1)); @@ -798,38 +772,49 @@ public class PolicyManagerServlet extends HttpServlet { } } + private List<Object> getDataByQueryFromController(final PolicyController controller, final String query, + final SimpleBindings params) { + final List<Object> activePolicies; + if (PolicyController.isjUnit()) { + activePolicies = controller.getDataByQuery(query, null); + } else { + activePolicies = controller.getDataByQuery(query, params); + } + return activePolicies; + } + private String checkScope(List<JSONObject> resultList, String scopeName, PolicyEditorScopes scopeById, Map<String, String> roleByScope) { String scope = scopeById.getScopeName(); + if (!scope.contains(File.separator)) { + return scopeName; + } + String targetScope = scope.substring(0, scope.lastIndexOf(File.separator)); + if (scopeName.contains(ESCAPE_BACKSLASH)) { + scopeName = scopeName.replace(ESCAPE_BACKSLASH, File.separator); + } if (scope.contains(File.separator)) { - String targetScope = scope.substring(0, scope.lastIndexOf(File.separator)); - if (scopeName.contains(ESCAPE_BACKSLASH)) { - scopeName = scopeName.replace(ESCAPE_BACKSLASH, File.separator); - } + scope = scope.substring(targetScope.length() + 1); if (scope.contains(File.separator)) { - scope = scope.substring(targetScope.length() + 1); - if (scope.contains(File.separator)) { - scope = scope.substring(0, scope.indexOf(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()); - String roleType = roleByScope.get(scopeName); - if (roleType == null) { - roleType = roleByScope.get(scopeName + File.separator + scope); - if (roleType == null) { - roleType = roleByScope.get(ALLSCOPES); - } - } - el.put(ROLETYPE, roleType); - resultList.add(el); + } + 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()); + String roleType = roleByScope.get(ALLSCOPES); // Set default role type to ALL_SCOPES + if (!Strings.isNullOrEmpty(roleByScope.get(scopeName))) { + roleType = roleByScope.get(scopeName); + } else if (!Strings.isNullOrEmpty(roleByScope.get(scopeName + File.separator + scope))) { + roleType = roleByScope.get(scopeName + File.separator + scope); } + el.put(ROLETYPE, roleType); + resultList.add(el); } return scopeName; } @@ -866,7 +851,7 @@ public class PolicyManagerServlet extends HttpServlet { if (oldPath.endsWith(".xml")) { checkValidation = newPath.replace(".xml", ""); checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, - checkValidation.lastIndexOf(".")); + checkValidation.lastIndexOf('.')); checkValidation = checkValidation.substring(checkValidation.lastIndexOf(FORWARD_SLASH) + 1); if (!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)) { return error("Policy Rename Failed. The Name contains special characters."); @@ -892,11 +877,10 @@ public class PolicyManagerServlet extends HttpServlet { } PolicyController controller = getPolicyControllerInstance(); String query = "from PolicyVersion where POLICY_NAME like :scopeName"; - String scopeNamequery = FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME; SimpleBindings pvParams = new SimpleBindings(); pvParams.put(SCOPE_NAME, scopeName + "%"); List<Object> activePolicies = controller.getDataByQuery(query, pvParams); - List<Object> scopesList = controller.getDataByQuery(scopeNamequery, pvParams); + List<Object> scopesList = controller.getDataByQuery(FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME, pvParams); for (Object object : activePolicies) { PolicyVersion activeVersion = (PolicyVersion) object; String policyOldPath = activeVersion.getPolicyName().replace(File.separator, FORWARD_SLASH) + "." @@ -910,24 +894,20 @@ public class PolicyManagerServlet extends HttpServlet { scopeOfPolicyActiveInPDP.add(scope.replace(FORWARD_SLASH, File.separator)); } } - boolean rename = false; - if (activePolicies.size() != policyActiveInPDP.size()) { - rename = true; - } - - UserInfo userInfo = new UserInfo(); - userInfo.setUserLoginId(userId); + boolean rename = activePolicies.size() != policyActiveInPDP.size(); if (policyActiveInPDP.isEmpty()) { renameScope(scopesList, scopeName, newScopeName, controller); } else if (rename) { renameScope(scopesList, scopeName, newScopeName, controller); - for (String scope : scopeOfPolicyActiveInPDP) { + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId(userId); + scopeOfPolicyActiveInPDP.forEach(scope -> { PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes(); editorScopeEntity.setScopeName(scope.replace(BACKSLASH, BACKSLASH_8TIMES)); 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" @@ -981,11 +961,12 @@ public class PolicyManagerServlet extends HttpServlet { // Query the Policy Entity with oldPolicy Name String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf('.')); - String oldpolicyEntityquery = "FROM PolicyEntity where policyName like :policyEntityCheck and scope = :oldPolicySplit_0"; + String oldPolicyEntityQuery = "FROM PolicyEntity where policyName like :policyEntityCheck and scope = " + + ":oldPolicySplit_0"; SimpleBindings params = new SimpleBindings(); params.put("policyEntityCheck", policyEntityCheck + "%"); params.put("oldPolicySplit_0", oldPolicySplit[0]); - List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery, params); + List<Object> oldEntityData = controller.getDataByQuery(oldPolicyEntityQuery, params); if (oldEntityData.isEmpty()) { return error( "Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin."); @@ -1019,7 +1000,6 @@ public class PolicyManagerServlet extends HttpServlet { oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId); } } - return success(); } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Renaming Policy" + e); @@ -1043,17 +1023,17 @@ public class PolicyManagerServlet extends HttpServlet { return policyName.split(":"); } - private void checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, - String oldScope, String removeoldPolicyExtension, String policyName, String newpolicyName, - String oldpolicyName, String userId) { + private void checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removeNewPolicyExtension, + String oldScope, String removeOldPolicyExtension, String policyName, String newPolicyName, + String oldPolicyName, String userId) { try { ConfigurationDataEntity configEntity = entity.getConfigurationData(); ActionBodyEntity actionEntity = entity.getActionBodyEntity(); PolicyController controller = getPolicyControllerInstance(); - String oldPolicyNameWithoutExtension = removeoldPolicyExtension; - String newPolicyNameWithoutExtension = removenewPolicyExtension; - if (removeoldPolicyExtension.endsWith(".xml")) { + String oldPolicyNameWithoutExtension = removeOldPolicyExtension; + String newPolicyNameWithoutExtension = removeNewPolicyExtension; + if (removeOldPolicyExtension.endsWith(".xml")) { oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf('.')); newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, @@ -1068,7 +1048,7 @@ public class PolicyManagerServlet extends HttpServlet { String oldConfigurationName = null; String newConfigurationName = null; - if (newpolicyName.contains(CONFIG2)) { + if (newPolicyName.contains(CONFIG2)) { oldConfigurationName = configEntity.getConfigurationName(); configEntity.setConfigurationName( configEntity.getConfigurationName().replace(oldScope + "." + oldPolicyNameWithoutExtension, @@ -1077,11 +1057,11 @@ public class PolicyManagerServlet extends HttpServlet { newConfigurationName = configEntity.getConfigurationName(); File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName); if (file.exists()) { - File renamefile = new File( + File renameFile = new File( PolicyController.getConfigHome() + File.separator + newConfigurationName); - file.renameTo(renamefile); + file.renameTo(renameFile); } - } else if (newpolicyName.contains(ACTION2)) { + } else if (newPolicyName.contains(ACTION2)) { oldConfigurationName = actionEntity.getActionBodyName(); actionEntity.setActionBody( actionEntity.getActionBody().replace(oldScope + "." + oldPolicyNameWithoutExtension, @@ -1090,9 +1070,9 @@ public class PolicyManagerServlet extends HttpServlet { newConfigurationName = actionEntity.getActionBodyName(); File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName); if (file.exists()) { - File renamefile = new File( + File renameFile = new File( PolicyController.getActionHome() + File.separator + newConfigurationName); - file.renameTo(renamefile); + file.renameTo(renameFile); } } controller.updateData(entity); @@ -1100,16 +1080,16 @@ public class PolicyManagerServlet extends HttpServlet { PolicyRestController restController = new PolicyRestController(); restController.notifyOtherPAPSToUpdateConfigurations("rename", newConfigurationName, oldConfigurationName); PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", - oldpolicyName); + oldPolicyName); versionEntity.setPolicyName(policyName); versionEntity.setModifiedBy(userId); controller.updateData(versionEntity); String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator) + 1); - String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator) + 1); + String moveOldPolicyCheck = oldPolicyName.substring(oldPolicyName.lastIndexOf(File.separator) + 1); if (movePolicyCheck.equals(moveOldPolicyCheck)) { - controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move"); + controller.watchPolicyFunction(versionEntity, oldPolicyName, "Move"); } else { - controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename"); + controller.watchPolicyFunction(versionEntity, oldPolicyName, "Rename"); } } catch (Exception e) { LOGGER.error(EXCEPTION_OCCURED + e); @@ -1204,11 +1184,11 @@ public class PolicyManagerServlet extends HttpServlet { String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')) .replace(FORWARD_SLASH, File.separator); - String newpolicyName = newPath.replace(FORWARD_SLASH, "."); + String newPolicyName = newPath.replace(FORWARD_SLASH, "."); - String orignalPolicyName = oldPath.replace(FORWARD_SLASH, "."); + String originalPolicyName = oldPath.replace(FORWARD_SLASH, "."); - String newPolicyCheck = newpolicyName; + String newPolicyCheck = newPolicyName; if (newPolicyCheck.contains(CONFIG2)) { newPolicyCheck = newPolicyCheck.replace(CONFIG, CONFIG1); } else if (newPolicyCheck.contains(ACTION2)) { @@ -1223,12 +1203,12 @@ public class PolicyManagerServlet extends HttpServlet { String checkValidation = newPolicySplit[1].replace(".xml", ""); checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, - checkValidation.lastIndexOf(".")); + checkValidation.lastIndexOf('.')); if (!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)) { return error("Policy Clone Failed. The Name contains special characters."); } - String[] oldPolicySplit = modifyPolicyName(orignalPolicyName); + String[] oldPolicySplit = modifyPolicyName(originalPolicyName); PolicyController controller = getPolicyControllerInstance(); @@ -1250,11 +1230,7 @@ public class PolicyManagerServlet extends HttpServlet { SimpleBindings peParams = new SimpleBindings(); peParams.put("oldPolicySplit_1", oldPolicySplit[1]); peParams.put("oldPolicySplit_0", oldPolicySplit[0]); - if (PolicyController.isjUnit()) { - queryData = controller.getDataByQuery(policyEntityquery, null); - } else { - queryData = controller.getDataByQuery(policyEntityquery, peParams); - } + queryData = getDataByQueryFromController(controller, policyEntityquery, peParams); if (!queryData.isEmpty()) { entity = (PolicyEntity) queryData.get(0); } @@ -1263,7 +1239,6 @@ public class PolicyManagerServlet extends HttpServlet { newPolicySplit[1], entity, userId); success = true; } - if (success) { PolicyVersion entityItem = new PolicyVersion(); entityItem.setActiveVersion(Integer.parseInt(version)); @@ -1274,9 +1249,7 @@ public class PolicyManagerServlet extends HttpServlet { entityItem.setModifiedDate(new Date()); controller.saveData(entityItem); } - LOGGER.debug("copy from: {} to: {}" + oldPath + newPath); - return success(); } catch (Exception e) { LOGGER.error("copy", e); @@ -1316,15 +1289,15 @@ public class PolicyManagerServlet extends HttpServlet { policyParams.put("exactScope", policyNamewithoutExtension); } - List<Object> policyEntityobjects = controller.getDataByQuery(query, policyParams); + List<Object> policyEntityObjects = controller.getDataByQuery(query, policyParams); String activePolicyName = null; boolean pdpCheck = false; if (path.endsWith(".xml")) { policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator); int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf('.') + 1)); if ("ALL".equals(deleteVersion)) { - if (!policyEntityobjects.isEmpty()) { - for (Object object : policyEntityobjects) { + if (!policyEntityObjects.isEmpty()) { + for (Object object : policyEntityObjects) { policyEntity = (PolicyEntity) object; String groupEntityquery = "from PolicyGroupEntity where policyid ='" + policyEntity.getPolicyId() + "'"; @@ -1334,24 +1307,8 @@ public class PolicyManagerServlet extends HttpServlet { pdpCheck = true; activePolicyName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); } else { - // Delete the entity from Elastic Search Database - String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); - restController.deleteElasticData(searchFileName); - // Delete the entity from Policy Entity table - controller.deleteData(policyEntity); - if (policyNamewithoutExtension.contains(CONFIG2)) { - Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator - + policyEntity.getConfigurationData().getConfigurationName())); - controller.deleteData(policyEntity.getConfigurationData()); - restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, - policyEntity.getConfigurationData().getConfigurationName()); - } else if (policyNamewithoutExtension.contains(ACTION2)) { - Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator - + policyEntity.getActionBodyEntity().getActionBodyName())); - controller.deleteData(policyEntity.getActionBodyEntity()); - restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, - policyEntity.getActionBodyEntity().getActionBodyName()); - } + deleteEntityFromEsAndPolicyEntityTable(controller, restController, policyEntity, + policyNamewithoutExtension); } } } @@ -1408,28 +1365,13 @@ public class PolicyManagerServlet extends HttpServlet { } // Delete the entity from Elastic Search Database - String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); - restController.deleteElasticData(searchFileName); - // Delete the entity from Policy Entity table - controller.deleteData(policyEntity); - if (policyNamewithoutExtension.contains(CONFIG2)) { - Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator - + policyEntity.getConfigurationData().getConfigurationName())); - controller.deleteData(policyEntity.getConfigurationData()); - restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, - policyEntity.getConfigurationData().getConfigurationName()); - } else if (policyNamewithoutExtension.contains(ACTION2)) { - Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator - + policyEntity.getActionBodyEntity().getActionBodyName())); - controller.deleteData(policyEntity.getActionBodyEntity()); - restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, - policyEntity.getActionBodyEntity().getActionBodyName()); - } + deleteEntityFromEsAndPolicyEntityTable(controller, restController, policyEntity, + policyNamewithoutExtension); if (version > 1) { int highestVersion = 0; - if (!policyEntityobjects.isEmpty()) { - for (Object object : policyEntityobjects) { + if (!policyEntityObjects.isEmpty()) { + for (Object object : policyEntityObjects) { policyEntity = (PolicyEntity) object; String policyEntityName = policyEntity.getPolicyName().replace(".xml", ""); int policyEntityVersion = Integer @@ -1465,18 +1407,18 @@ public class PolicyManagerServlet extends HttpServlet { } } else { List<String> activePoliciesInPDP = new ArrayList<>(); - if (policyEntityobjects.isEmpty()) { + if (policyEntityObjects.isEmpty()) { String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '" + path.replace(BACKSLASH, ESCAPE_BACKSLASH) + PERCENT_AND_ID_GT_0; controller.executeQuery(policyScopeQuery); return success(); } - for (Object object : policyEntityobjects) { + for (Object object : policyEntityObjects) { policyEntity = (PolicyEntity) object; - String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId"; + String groupEntityQuery = "from PolicyGroupEntity where policyid = :policyEntityId"; SimpleBindings geParams = new SimpleBindings(); geParams.put("policyEntityId", policyEntity.getPolicyId()); - List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams); + List<Object> groupobject = controller.getDataByQuery(groupEntityQuery, geParams); if (!groupobject.isEmpty()) { pdpCheck = true; activePoliciesInPDP.add(policyEntity.getScope() + "." + policyEntity.getPolicyName()); @@ -1520,15 +1462,14 @@ public class PolicyManagerServlet extends HttpServlet { .parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf('.') + 1)); activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf('.')) .replace(".", File.separator); - PolicyVersion insertactivePDPVersion = new PolicyVersion(); - insertactivePDPVersion.setPolicyName(activePDPPolicyName); - insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion); - insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion); - insertactivePDPVersion.setCreatedBy(userId); - insertactivePDPVersion.setModifiedBy(userId); - controller.saveData(insertactivePDPVersion); + PolicyVersion insertActivePDPVersion = new PolicyVersion(); + insertActivePDPVersion.setPolicyName(activePDPPolicyName); + insertActivePDPVersion.setHigherVersion(activePDPPolicyVersion); + insertActivePDPVersion.setActiveVersion(activePDPPolicyVersion); + insertActivePDPVersion.setCreatedBy(userId); + insertActivePDPVersion.setModifiedBy(userId); + controller.saveData(insertActivePDPVersion); } - return error("All the Policies has been deleted in Scope. Except the following list of Policies:" + activePoliciesInPDP); } else { @@ -1545,6 +1486,29 @@ public class PolicyManagerServlet extends HttpServlet { } } + private void deleteEntityFromEsAndPolicyEntityTable(final PolicyController controller, + final PolicyRestController restController, final PolicyEntity policyEntity, + final String policyNamewithoutExtension) throws IOException { + // Delete the entity from Elastic Search Database + String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); + restController.deleteElasticData(searchFileName); + // Delete the entity from Policy Entity table + controller.deleteData(policyEntity); + if (policyNamewithoutExtension.contains(CONFIG2)) { + Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + + policyEntity.getConfigurationData().getConfigurationName())); + controller.deleteData(policyEntity.getConfigurationData()); + restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, + policyEntity.getConfigurationData().getConfigurationName()); + } else if (policyNamewithoutExtension.contains(ACTION2)) { + Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + + policyEntity.getActionBodyEntity().getActionBodyName())); + controller.deleteData(policyEntity.getActionBodyEntity()); + restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, + policyEntity.getActionBodyEntity().getActionBodyName()); + } + } + // Edit the Policy private JSONObject editFile(JSONObject params) throws ServletException { // get content @@ -1566,12 +1530,7 @@ public class PolicyManagerServlet extends HttpServlet { SimpleBindings peParams = new SimpleBindings(); peParams.put(SPLIT_1, split[1]); peParams.put(SPLIT_0, split[0]); - List<Object> queryData; - if (PolicyController.isjUnit()) { - queryData = controller.getDataByQuery(query, null); - } else { - queryData = controller.getDataByQuery(query, peParams); - } + List<Object> queryData = getDataByQueryFromController(controller, query, peParams); PolicyEntity entity = (PolicyEntity) queryData.get(0); InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8)); @@ -1593,8 +1552,8 @@ public class PolicyManagerServlet extends HttpServlet { policyName = policyName.substring(0, policyName.lastIndexOf('.')); policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf('.') + 1)); - PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance(); - Objects.requireNonNull(setpolicyAdapter).configure(policyAdapter, entity); + PolicyAdapter setPolicyAdapter = PolicyAdapter.getInstance(); + Objects.requireNonNull(setPolicyAdapter).configure(policyAdapter, entity); policyAdapter.setParentPath(null); ObjectMapper mapper = new ObjectMapper(); @@ -1611,53 +1570,32 @@ public class PolicyManagerServlet extends HttpServlet { // Add Scopes private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException { PolicyController controller = getPolicyControllerInstance(); - String name = ""; try { - String userId = UserUtils.getUserSession(request).getOrgUserId(); - String path = params.getString("path"); - try { - if (params.has(SUB_SCOPENAME)) { - if (!"".equals(params.getString(SUB_SCOPENAME))) { - name = params.getString("path").replace(FORWARD_SLASH, File.separator) + File.separator - + params.getString(SUB_SCOPENAME); - } - } else { - name = params.getString(NAME); - } - } catch (Exception e) { - name = params.getString(NAME); - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope" + e); - } - String validateName; - if (name.contains(File.separator)) { - validateName = name.substring(name.lastIndexOf(File.separator) + 1); - } else { - validateName = name; - } + String name = getNameFromParams(params); + String validateName = + name.contains(File.separator) ? name.substring(name.lastIndexOf(File.separator) + 1) : name; if (!name.isEmpty()) { String validate = PolicyUtils.policySpecialCharValidator(validateName); if (!validate.contains(SUCCESS)) { return error(validate); } - } - LOGGER.debug("addFolder path: {} name: {}" + path + name); - if (!"".equals(name)) { + LOGGER.debug("addFolder path: {} name: {}" + params.getString("path") + name); if (name.startsWith(File.separator)) { name = name.substring(1); } PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, - SCOPE_NAME, name); - if (entity == null) { - UserInfo userInfo = new UserInfo(); - userInfo.setUserLoginId(userId); - PolicyEditorScopes newScope = new PolicyEditorScopes(); - newScope.setScopeName(name); - newScope.setUserCreatedBy(userInfo); - newScope.setUserModifiedBy(userInfo); - controller.saveData(newScope); - } else { + SCOPE_NAME, name); + if (entity != null) { return error("Scope Already Exists"); } + String userId = UserUtils.getUserSession(request).getOrgUserId(); + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId(userId); + PolicyEditorScopes newScope = new PolicyEditorScopes(); + newScope.setScopeName(name); + newScope.setUserCreatedBy(userInfo); + newScope.setUserModifiedBy(userInfo); + controller.saveData(newScope); } return success(); } catch (Exception e) { @@ -1666,6 +1604,24 @@ public class PolicyManagerServlet extends HttpServlet { } } + private String getNameFromParams(final JSONObject params) { + String name = ""; + try { + if (params.has(SUB_SCOPENAME)) { + if (!"".equals(params.getString(SUB_SCOPENAME))) { + name = params.getString("path").replace(FORWARD_SLASH, File.separator) + File.separator + + params.getString(SUB_SCOPENAME); + } + } else { + name = params.getString(NAME); + } + } catch (Exception e) { + name = params.getString(NAME); + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occurred While Adding Scope" + e); + } + return name; + } + // Return Error Object private JSONObject error(String msg) throws ServletException { try { @@ -1701,4 +1657,4 @@ public class PolicyManagerServlet extends HttpServlet { public static void setTestUserId(String testUserId) { PolicyManagerServlet.testUserId = testUserId; } -}
\ No newline at end of file +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java index a1bb73354..1fccfda78 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2017 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. @@ -24,11 +25,11 @@ package org.onap.policy.admin; import java.io.File; import java.text.DateFormat; import java.text.SimpleDateFormat; +import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Properties; -import javax.mail.MessagingException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.script.SimpleBindings; @@ -82,9 +83,8 @@ public class PolicyNotificationMail{ * @param policyName Name of the policy for which notification is to be sent * @param mode kind of operation done on the policy * @param policyNotificationDao database access object for policy - * @throws MessagingException */ - public void sendMail(PolicyVersion entityItem, String policyName, String mode, CommonClassDao policyNotificationDao) throws MessagingException { + public void sendMail(PolicyVersion entityItem, String policyName, String mode, CommonClassDao policyNotificationDao) { String subject = ""; String message = ""; @@ -130,26 +130,25 @@ public class PolicyNotificationMail{ String policyFileName = findPolicyFileName(entityItem); String query = "from WatchPolicyNotificationTable where policyName like:policyFileName"; List<Object> watchList = findWatchList(policyNotificationDao, policyFileName, query); - if (watchList == null) { - return; + if (!watchList.isEmpty()) { + composeAndSendMail(mode, policyNotificationDao, subject, message, checkPolicyName, watchList); } - - composeAndSendMail(mode, policyNotificationDao, subject, message, checkPolicyName, watchList); } private List<Object> findWatchList(CommonClassDao policyNotificationDao, String policyFileName, String query) { SimpleBindings params = new SimpleBindings(); params.put("policyFileName", policyFileName); List<Object> watchList; - if(PolicyController.isjUnit()){ + if (PolicyController.isjUnit()) { watchList = policyNotificationDao.getDataByQuery(query, null); - }else{ + } else { watchList = policyNotificationDao.getDataByQuery(query, params); } - if(watchList == null || watchList.isEmpty()) { - policyLogger.debug("List of policy being watched is either null or empty, hence return without sending mail"); - return null; + if (watchList == null || watchList.isEmpty()) { + policyLogger + .debug("List of policy being watched is either null or empty, hence return without sending mail"); + watchList = new ArrayList<>(); } return watchList; } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java index d77f52b0e..6935c7203 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2017-2018 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. @@ -33,7 +34,6 @@ import java.util.ArrayList; import java.util.Base64; import java.util.List; -import javax.mail.MessagingException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -136,25 +136,28 @@ public class PolicyRestController extends RestrictedBaseController{ } } - private void updateAndSendToPAP(HttpServletRequest request, HttpServletResponse response, String userId, ObjectMapper mapper) throws IOException, MessagingException { + private void updateAndSendToPAP(HttpServletRequest request, HttpServletResponse response, String userId, ObjectMapper mapper) throws IOException { JsonNode root = mapper.readTree(request.getReader()); - - policyLogger.info("****************************************Logging UserID while Create/Update Policy**************************************************"); - policyLogger.info(USER_ID + userId + "Policy Data Object: "+ root.get(PolicyController.getPolicydata()).get("policy").toString()); - policyLogger.info("***********************************************************************************************************************************"); - - PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class); - + policyLogger.info( + "****************************************Logging UserID while Create/Update Policy**************************************************"); + policyLogger.info( + USER_ID + userId + "Policy Data Object: " + root.get(PolicyController.getPolicydata()).get("policy") + .toString()); + policyLogger.info( + "***********************************************************************************************************************************"); + + PolicyRestAdapter policyData = mapper + .readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class); modifyPolicyData(root, policyData); - if(policyData.getConfigPolicyType() != null){ - if(CLOSED_LOOP_FAULT.equalsIgnoreCase(policyData.getConfigPolicyType())){ + if (policyData.getConfigPolicyType() != null) { + if (CLOSED_LOOP_FAULT.equalsIgnoreCase(policyData.getConfigPolicyType())) { policyData = new CreateClosedLoopFaultController().setDataToPolicyRestAdapter(policyData, root); - }else if(FIREWALL_CONFIG.equalsIgnoreCase(policyData.getConfigPolicyType())){ + } else if (FIREWALL_CONFIG.equalsIgnoreCase(policyData.getConfigPolicyType())) { policyData = new CreateFirewallController().setDataToPolicyRestAdapter(policyData); - }else if(MICRO_SERVICE.equalsIgnoreCase(policyData.getConfigPolicyType())){ + } else if (MICRO_SERVICE.equalsIgnoreCase(policyData.getConfigPolicyType())) { policyData = new CreateDcaeMicroServiceController().setDataToPolicyRestAdapter(policyData, root); - }else if(OPTIMIZATION.equalsIgnoreCase(policyData.getConfigPolicyType())){ + } else if (OPTIMIZATION.equalsIgnoreCase(policyData.getConfigPolicyType())) { policyData = new CreateOptimizationController().setDataToPolicyRestAdapter(policyData, root); } } @@ -165,17 +168,18 @@ public class PolicyRestController extends RestrictedBaseController{ String body = PolicyUtils.objectToJsonString(policyData); String uri = request.getRequestURI(); ResponseEntity<?> responseEntity = sendToPAP(body, uri, HttpMethod.POST); - if(responseEntity != null && responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)){ + if (responseEntity != null && responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)) { result = "PolicyExists"; - }else if(responseEntity != null){ - result = responseEntity.getBody().toString(); + } else if (responseEntity != null) { + result = responseEntity.getBody().toString(); String policyName = responseEntity.getHeaders().get(POLICY_NAME).get(0); - if(policyData.isEditPolicy() && SUCCESS.equalsIgnoreCase(result)){ + if (policyData.isEditPolicy() && SUCCESS.equalsIgnoreCase(result)) { PolicyNotificationMail email = new PolicyNotificationMail(); String mode = "EditPolicy"; String watchPolicyName = policyName.replace(XML, ""); - String version = watchPolicyName.substring(watchPolicyName.lastIndexOf('.')+1); - watchPolicyName = watchPolicyName.substring(0, watchPolicyName.lastIndexOf('.')).replace(".", File.separator); + String version = watchPolicyName.substring(watchPolicyName.lastIndexOf('.') + 1); + watchPolicyName = watchPolicyName.substring(0, watchPolicyName.lastIndexOf('.')) + .replace(".", File.separator); String policyVersionName = watchPolicyName.replace(".", File.separator); watchPolicyName = watchPolicyName + "." + version + XML; PolicyVersion entityItem = new PolicyVersion(); @@ -184,8 +188,8 @@ public class PolicyRestController extends RestrictedBaseController{ entityItem.setModifiedBy(userId); email.sendMail(entityItem, watchPolicyName, mode, commonClassDao); } - }else{ - result = "Response is null from PAP"; + } else { + result = "Response is null from PAP"; } response.setCharacterEncoding(PolicyController.getCharacterencoding()); @@ -343,10 +347,11 @@ public class PolicyRestController extends RestrictedBaseController{ return null; } - private void checkURI(HttpServletRequest request, String uri, HttpURLConnection connection, FileItem item) throws IOException { + private void checkURI(HttpServletRequest request, String uri, HttpURLConnection connection, FileItem item) + throws IOException { String boundary; - if(!(uri.endsWith("set_BRMSParamData") || uri.contains(IMPORT_DICTIONARY))){ - connection.setRequestProperty(CONTENT_TYPE,PolicyController.getContenttype()); + if (!(uri.endsWith("set_BRMSParamData") || uri.contains(IMPORT_DICTIONARY))) { + connection.setRequestProperty(CONTENT_TYPE, PolicyController.getContenttype()); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = getJsonNode(request, mapper); @@ -358,26 +363,24 @@ public class PolicyRestController extends RestrictedBaseController{ String json = mapper1.writeValueAsString(obj); // send current configuration - try(InputStream content = new ByteArrayInputStream(json.getBytes()); + try (InputStream content = new ByteArrayInputStream(json.getBytes()); OutputStream os = connection.getOutputStream()) { int count = IOUtils.copy(content, os); if (policyLogger.isDebugEnabled()) { policyLogger.debug("copied to output, bytes=" + count); } } - }else{ - if(uri.endsWith("set_BRMSParamData")){ - connection.setRequestProperty(CONTENT_TYPE,PolicyController.getContenttype()); - try (OutputStream os = connection.getOutputStream()) { - IOUtils.copy((InputStream) request.getInputStream(), os); - } - }else{ - boundary = "===" + System.currentTimeMillis() + "==="; - connection.setRequestProperty(CONTENT_TYPE,"multipart/form-data; boundary=" + boundary); - try (OutputStream os = connection.getOutputStream()) { - if(item != null){ - IOUtils.copy((InputStream) item.getInputStream(), os); - } + } else if (uri.endsWith("set_BRMSParamData")) { + connection.setRequestProperty(CONTENT_TYPE, PolicyController.getContenttype()); + try (OutputStream os = connection.getOutputStream()) { + IOUtils.copy(request.getInputStream(), os); + } + } else { + boundary = "===" + System.currentTimeMillis() + "==="; + connection.setRequestProperty(CONTENT_TYPE, "multipart/form-data; boundary=" + boundary); + try (OutputStream os = connection.getOutputStream()) { + if (item != null) { + IOUtils.copy(item.getInputStream(), os); } } } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java index 96205c5b1..7e0aef2e9 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java @@ -3,13 +3,14 @@ * ONAP Policy Engine * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * 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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -39,24 +40,23 @@ import com.fasterxml.jackson.databind.ObjectMapper; @Controller @RequestMapping("/") -public class PolicyUserInfoController extends RestrictedBaseController{ - - private static final Logger LOGGER = FlexLogger.getLogger(PolicyUserInfoController.class); - - @RequestMapping(value="/get_PolicyUserInfo", method = RequestMethod.GET) - public void getPolicyUserInfo(HttpServletRequest request, HttpServletResponse response){ - JsonMessage msg = null; - try { - String userId = UserUtils.getUserSession(request).getOrgUserId(); - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("userid", userId); - msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } catch (Exception e) { - LOGGER.error("Exception Occured"+e); - } - } +public class PolicyUserInfoController extends RestrictedBaseController { + private static final Logger LOGGER = FlexLogger.getLogger(PolicyUserInfoController.class); + + @RequestMapping(value = "/get_PolicyUserInfo", method = RequestMethod.GET) + public void getPolicyUserInfo(HttpServletRequest request, HttpServletResponse response) { + JsonMessage msg; + try { + String userId = UserUtils.getUserSession(request).getOrgUserId(); + Map<String, Object> model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("userid", userId); + msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } catch (Exception e) { + LOGGER.error("Exception Occurred" + e); + } + } } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java index c09944c2f..2ccc92eb3 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2017-2018 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,8 +22,6 @@ package org.onap.policy.admin; - - import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -33,6 +32,7 @@ import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; +import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.HashMap; @@ -74,7 +74,7 @@ import org.onap.policy.common.logging.flexlogger.Logger; public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyEngine { private static final Logger LOGGER = FlexLogger.getLogger(RESTfulPAPEngine.class); - private static final String groupID = "groupId="; + private static final String GROUP_ID = "groupId="; // // URL of the PAP Servlet that this Admin Console talks to @@ -83,7 +83,7 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP /** * Set up link with PAP Servlet and get our initial set of Groups - * @throws Exception + * @throws PAPException When failing to register with PAP */ public RESTfulPAPEngine (String myURLString) throws PAPException { // @@ -112,40 +112,38 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP } } - // // High-level commands used by the Admin Console code through the PAPEngine Interface // @Override public OnapPDPGroup getDefaultGroup() throws PAPException { - return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID, "default="); + return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID, "default="); } @Override public void setDefaultGroup(OnapPDPGroup group) throws PAPException { - sendToPAP("POST", null, null, null, groupID + group.getId(), "default=true"); + sendToPAP("POST", null, null, null, GROUP_ID + group.getId(), "default=true"); } @SuppressWarnings("unchecked") @Override public Set<OnapPDPGroup> getOnapPDPGroups() throws PAPException { Set<OnapPDPGroup> newGroupSet; - newGroupSet = (Set<OnapPDPGroup>) this.sendToPAP("GET", null, Set.class, StdPDPGroup.class, groupID); + newGroupSet = (Set<OnapPDPGroup>) this.sendToPAP("GET", null, Set.class, StdPDPGroup.class, GROUP_ID); return Collections.unmodifiableSet(newGroupSet); } - @Override public OnapPDPGroup getGroup(String id) throws PAPException { - return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID + id); + return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID + id); } @Override public void newGroup(String name, String description) throws PAPException { - String escapedName = null; - String escapedDescription = null; + String escapedName; + String escapedDescription; try { escapedName = URLEncoder.encode(name, "UTF-8"); escapedDescription = URLEncoder.encode(description, "UTF-8"); @@ -153,10 +151,9 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP throw new PAPException("Unable to send name or description to PAP: " + e.getMessage() +e); } - this.sendToPAP("POST", null, null, null, groupID, "groupName="+escapedName, "groupDescription=" + escapedDescription); + this.sendToPAP("POST", null, null, null, GROUP_ID, "groupName="+escapedName, "groupDescription=" + escapedDescription); } - /** * Update the configuration on the PAP for a single Group. * @@ -166,24 +163,17 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP */ @Override public void updateGroup(OnapPDPGroup group) throws PAPException { - try { - // // ASSUME that all of the policies mentioned in this group are already located in the correct directory on the PAP! // // Whenever a Policy is added to the group, that file must be automatically copied to the PAP from the Workspace. // - - // Copy all policies from the local machine's workspace to the PAP's PDPGroup directory. // This is not efficient since most of the policies will already exist there. // However, the policy files are (probably!) not too huge, and this is a good way to ensure that any corrupted files on the PAP get refreshed. - - // now update the group object on the PAP - - sendToPAP("PUT", group, null, null, groupID + group.getId()); + sendToPAP("PUT", group, null, null, GROUP_ID + group.getId()); } catch (Exception e) { String message = "Unable to PUT policy '" + group.getId() + "', e:" + e; LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); @@ -191,15 +181,13 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP } } - @Override - public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup) - throws PAPException { + public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup) throws PAPException { String moveToGroupString = null; if (newGroup != null) { moveToGroupString = "movePDPsToGroupId=" + newGroup.getId(); } - sendToPAP("DELETE", null, null, null, groupID + group.getId(), moveToGroupString); + sendToPAP("DELETE", null, null, null, GROUP_ID + group.getId(), moveToGroupString); } @Override @@ -207,41 +195,36 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP return getPDPGroup(pdp.getId()); } - public OnapPDPGroup getPDPGroup(String pdpId) throws PAPException { - return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID, "pdpId=" + pdpId, "getPDPGroup="); + return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID, "pdpId=" + pdpId, "getPDPGroup="); } @Override public OnapPDP getPDP(String pdpId) throws PAPException { - return (OnapPDP)sendToPAP("GET", null, null, StdPDP.class, groupID, "pdpId=" + pdpId); + return (OnapPDP)sendToPAP("GET", null, null, StdPDP.class, GROUP_ID, "pdpId=" + pdpId); } @Override public void newPDP(String id, OnapPDPGroup group, String name, String description, int jmxport) throws PAPException { StdPDP newPDP = new StdPDP(id, name, description, jmxport); - sendToPAP("PUT", newPDP, null, null, groupID + group.getId(), "pdpId=" + id); - return; + sendToPAP("PUT", newPDP, null, null, GROUP_ID + group.getId(), "pdpId=" + id); } @Override public void movePDP(OnapPDP pdp, OnapPDPGroup newGroup) throws PAPException { - sendToPAP("POST", null, null, null, groupID + newGroup.getId(), "pdpId=" + pdp.getId()); - return; + sendToPAP("POST", null, null, null, GROUP_ID + newGroup.getId(), "pdpId=" + pdp.getId()); } @Override public void updatePDP(OnapPDP pdp) throws PAPException { OnapPDPGroup group = getPDPGroup(pdp); - sendToPAP("PUT", pdp, null, null, groupID + group.getId(), "pdpId=" + pdp.getId()); - return; + sendToPAP("PUT", pdp, null, null, GROUP_ID + group.getId(), "pdpId=" + pdp.getId()); } @Override public void removePDP(OnapPDP pdp) throws PAPException { OnapPDPGroup group = getPDPGroup(pdp); - sendToPAP("DELETE", null, null, null, groupID + group.getId(), "pdpId=" + pdp.getId()); - return; + sendToPAP("DELETE", null, null, null, GROUP_ID + group.getId(), "pdpId=" + pdp.getId()); } //Validate the Policy Data @@ -257,8 +240,6 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP @Override public void publishPolicy(String id, String name, boolean isRoot, InputStream policy, OnapPDPGroup group) throws PAPException { - - // copy the (one) file into the target directory on the PAP servlet copyFile(id, group, policy); @@ -268,8 +249,6 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP // tell the PAP servlet to include the policy in the configuration updateGroup(group); - - return; } /** @@ -285,7 +264,7 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP public void copyFile(String policyId, OnapPDPGroup group, InputStream policy) throws PAPException { // send the policy file to the PAP Servlet try { - sendToPAP("POST", policy, null, null, groupID + group.getId(), "policyId="+policyId); + sendToPAP("POST", policy, null, null, GROUP_ID + group.getId(), "policyId="+policyId); } catch (Exception e) { String message = "Unable to PUT policy '" + policyId + "', e:" + e; LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); @@ -293,9 +272,8 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP } } - @Override - public void copyPolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException { + public void copyPolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException { if (policy == null || group == null) { throw new PAPException("Null input policy="+policy+" group="+group); } @@ -309,12 +287,10 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP } @Override - public void removePolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException { + public void removePolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException { throw new PAPException("NOT IMPLEMENTED"); - } - /** * Special operation - Similar to the normal PAP operations but this one contacts the PDP directly * to get detailed status info. @@ -328,7 +304,6 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP return (StdPDPStatus)sendToPAP("GET", pdp, null, StdPDPStatus.class); } - // // Internal Operations called by the PAPEngine Interface methods // @@ -347,7 +322,7 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP * @param responseContentClass * @param parameters * @return - * @throws Exception + * @throws PAPException */ @SuppressWarnings({ "rawtypes", "unchecked" }) private Object sendToPAP(String method, Object content, Class collectionTypeClass, Class responseContentClass, String... parameters ) throws PAPException { @@ -356,37 +331,34 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP LOGGER.info("User Id is " + papID); String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)); Base64.Encoder encoder = Base64.getEncoder(); - String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8)); + String encoding = encoder.encodeToString((papID + ":" + papPass).getBytes(StandardCharsets.UTF_8)); Object contentObj = content; LOGGER.info("Encoding for the PAP is: " + encoding); try { String fullURL = papServletURLString; if (parameters != null && parameters.length > 0) { StringBuilder queryString = new StringBuilder(); - for (String p : parameters) { - queryString.append("&" + p); - } + Arrays.stream(parameters).map(p -> "&" + p).forEach(queryString::append); fullURL += "?" + queryString.substring(1); } // special case - Status (actually the detailed status) comes from the PDP directly, not the PAP - if ("GET".equals(method) && (contentObj instanceof OnapPDP) && responseContentClass == StdPDPStatus.class) { + if ("GET".equals(method) && (contentObj instanceof OnapPDP) && responseContentClass == StdPDPStatus.class) { // Adjust the url and properties appropriately - String pdpID =((OnapPDP)contentObj).getId(); + String pdpID = ((OnapPDP) contentObj).getId(); fullURL = pdpID + "?type=Status"; contentObj = null; - if(CheckPDP.validateID(pdpID)){ + if (CheckPDP.validateID(pdpID)) { encoding = CheckPDP.getEncoding(pdpID); } } - URL url = new URL(fullURL); // // Open up the connection // - connection = (HttpURLConnection)url.openConnection(); + connection = (HttpURLConnection) url.openConnection(); // // Setup our method and headers // @@ -410,7 +382,7 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP } else { // The contentObj is an object to be encoded in JSON ObjectMapper mapper = new ObjectMapper(); - mapper.writeValue(connection.getOutputStream(), contentObj); + mapper.writeValue(connection.getOutputStream(), contentObj); } } // @@ -425,18 +397,18 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP String isValidData = connection.getHeaderField("isValidData"); String isSuccess = connection.getHeaderField("successMapKey"); Map<String, String> successMap = new HashMap<>(); - if (isValidData != null && "true".equalsIgnoreCase(isValidData)){ + if ("true".equalsIgnoreCase(isValidData)) { LOGGER.info("Policy Data is valid."); return true; - } else if (isValidData != null && "false".equalsIgnoreCase(isValidData)) { + } else if ("false".equalsIgnoreCase(isValidData)) { LOGGER.info("Policy Data is invalid."); return false; - } else if (isSuccess != null && "success".equalsIgnoreCase(isSuccess)) { - LOGGER.info("Policy Created Successfully!" ); + } else if ("success".equalsIgnoreCase(isSuccess)) { + LOGGER.info("Policy Created Successfully!"); String finalPolicyPath = connection.getHeaderField("finalPolicyPath"); successMap.put("success", finalPolicyPath); return successMap; - } else if (isSuccess != null && "error".equalsIgnoreCase(isSuccess)) { + } else if ("error".equalsIgnoreCase(isSuccess)) { LOGGER.info("There was an error while creating the policy!"); successMap.put("error", "error"); return successMap; @@ -450,21 +422,21 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP if (collectionTypeClass != null) { // collection of objects expected final CollectionType javaType = - mapper.getTypeFactory().constructCollectionType(collectionTypeClass, responseContentClass); - + mapper.getTypeFactory().constructCollectionType(collectionTypeClass, responseContentClass); return mapper.readValue(json, javaType); } else { // single value object expected return mapper.readValue(json, responseContentClass); } } - - } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) { + } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) { // redirection String newURL = connection.getHeaderField("Location"); if (newURL == null) { - LOGGER.error("No Location header to redirect to when response code="+connection.getResponseCode()); - throw new IOException("No redirect Location header when response code="+connection.getResponseCode()); + LOGGER + .error("No Location header to redirect to when response code=" + connection.getResponseCode()); + throw new IOException( + "No redirect Location header when response code=" + connection.getResponseCode()); } int qIndex = newURL.indexOf('?'); if (qIndex > 0) { @@ -473,12 +445,13 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP LOGGER.info("Redirect seen. Redirecting " + fullURL + " to " + newURL); return newURL; } else { - LOGGER.warn("Unexpected response code: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); - throw new IOException("Server Response: " + connection.getResponseCode() + ": " + connection.getResponseMessage()); + LOGGER.warn("Unexpected response code: " + connection.getResponseCode() + " message: " + connection + .getResponseMessage()); + throw new IOException( + "Server Response: " + connection.getResponseCode() + ": " + connection.getResponseMessage()); } - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "HTTP Request/Response to PAP: " + e,e); + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "HTTP Request/Response to PAP: " + e, e); throw new PAPException("Request/Response threw :" + e); } finally { // cleanup the connection @@ -515,7 +488,7 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP } private String getJsonString(final HttpURLConnection connection) throws IOException { - String json = null; + String json; // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file) try(java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream())) { scanner.useDelimiter("\\A"); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java index ea0dce2c0..b116af6ef 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java @@ -3,6 +3,7 @@ * ONAP Policy Engine * ================================================================================ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * 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. @@ -65,8 +66,6 @@ import org.onap.policy.rest.jpa.FunctionDefinition; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.onap.policy.xacml.util.XACMLPolicyScanner; - - public class HumanPolicyComponent { private static final Logger LOGGER = FlexLogger.getLogger(HumanPolicyComponent.class); @@ -218,8 +217,7 @@ class HtmlProcessor extends SimpleCallback { throw new IllegalArgumentException(msg); } - if (policyObject == null - || (!(policyObject instanceof PolicySetType) && !(policyObject instanceof PolicyType))) { + if ((!(policyObject instanceof PolicySetType) && !(policyObject instanceof PolicyType))) { String msg = "Invalid unmarshalled object: " + policyObject; LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + msg); throw new IllegalArgumentException(msg); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java index a556beeaa..578258403 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java @@ -3,6 +3,7 @@ * ONAP Policy Engine * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * 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. @@ -22,7 +23,6 @@ package org.onap.policy.controller; import java.util.ArrayList; import java.util.HashMap; -import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -33,7 +33,6 @@ import javax.xml.bind.JAXBElement; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.rest.adapter.PolicyRestAdapter; -import org.onap.policy.rest.jpa.PolicyEntity; import org.onap.portalsdk.core.controller.RestrictedBaseController; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @@ -56,132 +55,149 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; @RequestMapping({ "/" }) public class ActionPolicyController extends RestrictedBaseController { private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicyController.class); + private static final String PERFORMER_ATTRIBUTE_ID = "performer"; + private static final String DYNAMIC_RULE_ALGORITHM_FIELD_1 = "dynamicRuleAlgorithmField1"; + private static final String DYNAMIC_RULE_ALGORITHM_FIELD_2 = "dynamicRuleAlgorithmField2"; + private LinkedList<Integer> ruleAlgorithmTracker; + private Map<String, String> performer = new HashMap<>(); + private List<Object> ruleAlgorithmList; public ActionPolicyController() { // Default Constructor } - private ArrayList<Object> attributeList; - protected LinkedList<Integer> ruleAlgoirthmTracker; - public static final String PERFORMER_ATTRIBUTEID = "performer"; - protected Map<String, String> performer = new HashMap<>(); - private ArrayList<Object> ruleAlgorithmList; - - public void prePopulateActionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - attributeList = new ArrayList<>(); + public void prePopulateActionPolicyData(PolicyRestAdapter policyAdapter) { ruleAlgorithmList = new ArrayList<>(); performer.put("PDP", "PDPAction"); performer.put("PEP", "PEPAction"); if (policyAdapter.getPolicyData() instanceof PolicyType) { - Object policyData = policyAdapter.getPolicyData(); - PolicyType policy = (PolicyType) policyData; - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - String policyNameValue = policyAdapter.getPolicyName() - .substring(policyAdapter.getPolicyName().indexOf('_') + 1); - policyAdapter.setPolicyName(policyNameValue); - String description = ""; - try { - description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); - } catch (Exception e) { - LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e); - description = policy.getDescription(); - } - policyAdapter.setPolicyDescription(description); - // Get the target data under policy for Action. + PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); + + // 1. Set policy-name, policy-filename and description to Policy Adapter + setPolicyAdapterPolicyNameAndDesc(policyAdapter, policy); + + // 2a. Get the target data under policy for Action. TargetType target = policy.getTarget(); - if (target != null) { - // 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 AntOfType 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 Mathch. - List<MatchType> matchList = allOf.getMatch(); - if (matchList != null) { - Iterator<MatchType> iterMatch = matchList.iterator(); - while (iterMatch.hasNext()) { - MatchType match = iterMatch.next(); - // - // Under the match we have attributevalue 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(); - // Component attributes are saved under Target here we are fetching them back. - // One row is default so we are not adding dynamic component at index 0. - Map<String, String> attribute = new HashMap<>(); - attribute.put("key", attributeId); - attribute.put("value", value); - attributeList.add(attribute); - } - } - policyAdapter.setAttributes(attributeList); - } - } - } + if (target == null) { + return; + } + + // 2b. Set attributes to Policy Adapter + setPolicyAdapterAttributes(policyAdapter, target.getAnyOf()); + + List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); + // Under rule we have Condition and obligation. + for (Object o : ruleList) { + if (!(o instanceof RuleType)) { + continue; } + // 3. Set rule-algorithm choices to Policy Adapter + setPolicyAdapterRuleAlgorithmschoices(policyAdapter, (RuleType) o); - List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); - // Under rule we have Condition and obligation. - for (Object o : ruleList) { - if (o instanceof RuleType) { - ConditionType condition = ((RuleType) o).getCondition(); - ObligationExpressionsType obligations = ((RuleType) o).getObligationExpressions(); - if (condition != null) { - int index = 0; - ApplyType actionApply = (ApplyType) condition.getExpression().getValue(); - ruleAlgoirthmTracker = new LinkedList<>(); - // Populating Rule Algorithms starting from compound. - prePopulateCompoundRuleAlgorithm(index, actionApply); - } - policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList); - // get the Obligation data under the rule for Form elements. - if (obligations != null) { - // Under the obligationExpressions we have obligationExpression. - List<ObligationExpressionType> obligationList = obligations.getObligationExpression(); - if (obligationList != null) { - Iterator<ObligationExpressionType> iterObligation = obligationList.iterator(); - while (iterObligation.hasNext()) { - ObligationExpressionType obligation = iterObligation.next(); - policyAdapter.setActionAttributeValue(obligation.getObligationId()); - // Under the obligationExpression we have attributeAssignmentExpression. - List<AttributeAssignmentExpressionType> attributeAssignmentExpressionList = obligation - .getAttributeAssignmentExpression(); - if (attributeAssignmentExpressionList != null) { - Iterator<AttributeAssignmentExpressionType> iterAttributeAssignmentExpression = attributeAssignmentExpressionList - .iterator(); - while (iterAttributeAssignmentExpression.hasNext()) { - AttributeAssignmentExpressionType attributeAssignmentExpression = iterAttributeAssignmentExpression - .next(); - String attributeID = attributeAssignmentExpression.getAttributeId(); - AttributeValueType attributeValue = (AttributeValueType) attributeAssignmentExpression - .getExpression().getValue(); - if (attributeID.equals(PERFORMER_ATTRIBUTEID)) { - for ( Entry<String, String> entry: performer.entrySet()) { - String key = entry.getKey(); - String keyValue = entry.getValue(); - if (keyValue.equals(attributeValue.getContent().get(0))) { - policyAdapter.setActionPerformer(key); - } - } - } - } - } - } - } - } + // 4a. Get the Obligation data under the rule for Form elements. + ObligationExpressionsType obligations = ((RuleType) o).getObligationExpressions(); + + // 4b. Set action attribute-value and action-performer to Policy Adapter + setPolicyAdapterActionData(policyAdapter, obligations); + } + } + } + + private void setPolicyAdapterActionData(PolicyRestAdapter policyAdapter, ObligationExpressionsType obligations) { + if (obligations == null) { + return; + } + // Under the obligationExpressions we have obligationExpression. + List<ObligationExpressionType> obligationList = obligations.getObligationExpression(); + if (obligationList == null) { + return; + } + for (ObligationExpressionType obligation : obligationList) { + policyAdapter.setActionAttributeValue(obligation.getObligationId()); + // Under the obligationExpression we have attributeAssignmentExpression. + List<AttributeAssignmentExpressionType> attributeAssignmentExpressionList = obligation + .getAttributeAssignmentExpression(); + if (attributeAssignmentExpressionList == null) { + continue; + } + for (AttributeAssignmentExpressionType attributeAssignmentExpression : attributeAssignmentExpressionList) { + String attributeID = attributeAssignmentExpression.getAttributeId(); + AttributeValueType attributeValue = (AttributeValueType) attributeAssignmentExpression + .getExpression().getValue(); + if (!attributeID.equals(PERFORMER_ATTRIBUTE_ID)) { + continue; + } + performer.forEach((key, keyValue) -> { + if (keyValue.equals(attributeValue.getContent().get(0))) { + policyAdapter.setActionPerformer(key); } + }); + } + } + } + + private void setPolicyAdapterPolicyNameAndDesc(PolicyRestAdapter policyAdapter, PolicyType policy) { + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = policyAdapter.getPolicyName() + .substring(policyAdapter.getPolicyName().indexOf('_') + 1); + policyAdapter.setPolicyName(policyNameValue); + String description; + try { + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + } catch (Exception e) { + LOGGER.error("Error while collecting the description tag in ActionPolicy " + policyNameValue, e); + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + } + + private void setPolicyAdapterRuleAlgorithmschoices(PolicyRestAdapter policyAdapter, RuleType o) { + ConditionType condition = o.getCondition(); + if (condition != null) { + int index = 0; + ApplyType actionApply = (ApplyType) condition.getExpression().getValue(); + ruleAlgorithmTracker = new LinkedList<>(); + // Populating Rule Algorithms starting from compound. + prePopulateCompoundRuleAlgorithm(index, actionApply); + } + policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList); + } + + private void setPolicyAdapterAttributes(PolicyRestAdapter policyAdapter, List<AnyOfType> anyOfList) { + List<Object> attributeList = new ArrayList<>(); + if (anyOfList == null) { + return; + } + // under target we have AnyOFType + for (AnyOfType anyOf : anyOfList) { + // Under AntOfType we have AllOfType + List<AllOfType> allOfList = anyOf.getAllOf(); + if (allOfList == null) { + continue; + } + // Under AllOfType we have Match. + for (AllOfType allOfType : allOfList) { + List<MatchType> matchList = allOfType.getMatch(); + if (matchList != null) { + // + // Under the match we have attributeValue and + // attributeDesignator. So,finally down to the actual attribute. + // + // Component attributes are saved under Target here we are fetching them back. + // One row is default so we are not adding dynamic component at index 0. + matchList.forEach(match -> { + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + Map<String, String> attribute = new HashMap<>(); + attribute.put("key", attributeId); + attribute.put("value", value); + attributeList.add(attribute); + }); } + policyAdapter.setAttributes(attributeList); } } } @@ -197,7 +213,7 @@ public class ActionPolicyController extends RestrictedBaseController { // Check to see if Attribute Value exists, if yes then it is not a compound rule if (jaxbElement.getValue() instanceof AttributeValueType) { prePopulateRuleAlgorithms(index, actionApply, jaxbActionTypes); - ruleAlgoirthmTracker.addLast(index); + ruleAlgorithmTracker.addLast(index); isCompoundRule = false; index++; } @@ -221,11 +237,11 @@ public class ActionPolicyController extends RestrictedBaseController { } rule.put("id", "A" + (index + 1)); // Populate Key and values for Compound Rule - rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1)); - ruleAlgoirthmTracker.removeLast(); - rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1)); - ruleAlgoirthmTracker.removeLast(); - ruleAlgoirthmTracker.addLast(index); + rule.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, "A" + (ruleAlgorithmTracker.getLast() + 1)); + ruleAlgorithmTracker.removeLast(); + rule.put(DYNAMIC_RULE_ALGORITHM_FIELD_2, "A" + (ruleAlgorithmTracker.getLast() + 1)); + ruleAlgorithmTracker.removeLast(); + ruleAlgorithmTracker.addLast(index); ruleAlgorithmList.add(rule); index++; } @@ -250,26 +266,25 @@ public class ActionPolicyController extends RestrictedBaseController { List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression(); AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0) .getValue(); - ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId()); + ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, attributeDesignator.getAttributeId()); // Get from Attribute Value AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbActionTypes.get(1).getValue(); String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); - ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); + ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_2, attributeValue); } // Rule Attribute added as value else if ((jaxbActionTypes.get(0).getValue()) instanceof AttributeValueType) { AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbActionTypes.get(0).getValue(); String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); - ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); + ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_2, attributeValue); ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(1).getValue(); List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression(); AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0) .getValue(); - ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId()); + ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, attributeDesignator.getAttributeId()); } ruleAlgorithmList.add(ruleMap); } - } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java index 346b95aff..fc25e29f0 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java @@ -3,13 +3,14 @@ * ONAP Policy Engine * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * 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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,7 +21,6 @@ package org.onap.policy.controller; - import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; @@ -50,77 +50,82 @@ import com.fasterxml.jackson.databind.ObjectMapper; @Controller @RequestMapping({"/"}) -public class AdminTabController extends RestrictedBaseController{ - - private static final Logger LOGGER = FlexLogger.getLogger(AdminTabController.class); - - private static CommonClassDao commonClassDao; - - public AdminTabController() { - //default constructor - } - - @Autowired - private AdminTabController(CommonClassDao commonClassDao){ - AdminTabController.commonClassDao = commonClassDao; - } - - public static CommonClassDao getCommonClassDao() { - return commonClassDao; - } - - public static void setCommonClassDao(CommonClassDao commonClassDao) { - AdminTabController.commonClassDao = commonClassDao; - } - - @RequestMapping(value={"/get_LockDownData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getAdminTabEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("lockdowndata", mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error("Exception Occured"+e); - } - } - - @RequestMapping(value={"/adminTabController/save_LockDownValue.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveAdminTabLockdownValue(HttpServletRequest request, HttpServletResponse response) throws IOException{ - try { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - String userId = UserUtils.getUserSession(request).getOrgUserId(); - LOGGER.info("****************************************Logging UserID for Application Lockdown Function*****************************************"); - LOGGER.info("UserId: " + userId); - LOGGER.info("*********************************************************************************************************************************"); - JsonNode root = mapper.readTree(request.getReader()); - GlobalRoleSettings globalRole = mapper.readValue(root.get("lockdowndata").toString(), GlobalRoleSettings.class); - globalRole.setRole("super-admin"); - commonClassDao.update(globalRole); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class)); - JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}"); - - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error("Exception Occured"+e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - } - return null; - } +public class AdminTabController extends RestrictedBaseController { + + private static final Logger LOGGER = FlexLogger.getLogger(AdminTabController.class); + private static final String CHARACTER_ENCODING = "UTF-8"; + + private static CommonClassDao commonClassDao; + + public AdminTabController() { + //default constructor + } + + @Autowired + private AdminTabController(CommonClassDao commonClassDao) { + AdminTabController.commonClassDao = commonClassDao; + } + + public static CommonClassDao getCommonClassDao() { + return commonClassDao; + } + + public static void setCommonClassDao(CommonClassDao commonClassDao) { + AdminTabController.commonClassDao = commonClassDao; + } + + @RequestMapping(value = {"/get_LockDownData"}, method = { + org.springframework.web.bind.annotation.RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) + public void getAdminTabEntityData(HttpServletRequest request, HttpServletResponse response) { + try { + Map<String, Object> model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("lockdowndata", mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } catch (Exception e) { + LOGGER.error("Exception Occured" + e); + } + } + + @RequestMapping(value = {"/adminTabController/save_LockDownValue.htm"}, method = { + org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveAdminTabLockdownValue(HttpServletRequest request, HttpServletResponse response) + throws IOException { + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + String userId = UserUtils.getUserSession(request).getOrgUserId(); + LOGGER.info( + "****************************************Logging UserID for Application Lockdown Function*****************************************"); + LOGGER.info("UserId: " + userId); + LOGGER.info( + "*********************************************************************************************************************************"); + JsonNode root = mapper.readTree(request.getReader()); + GlobalRoleSettings globalRole = mapper + .readValue(root.get("lockdowndata").toString(), GlobalRoleSettings.class); + globalRole.setRole("super-admin"); + commonClassDao.update(globalRole); + + response.setCharacterEncoding(CHARACTER_ENCODING); + response.setContentType("application / json"); + request.setCharacterEncoding(CHARACTER_ENCODING); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class)); + JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}"); + + out.write(j.toString()); + + return null; + } catch (Exception e) { + LOGGER.error("Exception Occured" + e); + response.setCharacterEncoding(CHARACTER_ENCODING); + request.setCharacterEncoding(CHARACTER_ENCODING); + PrintWriter out = response.getWriter(); + out.write(PolicyUtils.CATCH_EXCEPTION); + } + return null; + } } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java index 018668fc7..3af430f45 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java @@ -3,6 +3,7 @@ * ONAP Policy Engine * ================================================================================ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * 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. @@ -37,6 +38,9 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; import javax.script.SimpleBindings; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -63,6 +67,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; 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.api.pap.PAPException; @@ -82,11 +87,9 @@ public class AutoPushController extends RestrictedBaseController { CommonClassDao commonClassDao; private PDPGroupContainer container; - protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<OnapPDPGroup>()); - private PDPPolicyContainer policyContainer; - private PolicyController policyController; + protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<>()); public PolicyController getPolicyController() { return policyController; @@ -96,8 +99,6 @@ public class AutoPushController extends RestrictedBaseController { this.policyController = policyController; } - private List<Object> data; - public synchronized void refreshGroups() { synchronized (this.groups) { this.groups.clear(); @@ -116,35 +117,26 @@ public class AutoPushController extends RestrictedBaseController { return policyController != null ? getPolicyController() : new PolicyController(); } - @RequestMapping(value = { "/get_AutoPushPoliciesContainerData" }, method = { - org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value = {"/get_AutoPushPoliciesContainerData"}, method = { + RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response) { try { - Set<String> scopes; - List<String> roles; - data = new ArrayList<>(); - String userId = UserUtils.getUserSession(request).getOrgUserId(); + Set<String> scopes = new HashSet<>(); + List<String> roles = new ArrayList<>(); + List<Object> data = new ArrayList<>(); Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); + + String userId = UserUtils.getUserSession(request).getOrgUserId(); + PolicyController controller = policyController != null ? getPolicyController() : new PolicyController(); List<Object> userRoles = controller.getRoles(userId); - roles = new ArrayList<>(); - scopes = new HashSet<>(); for (Object role : userRoles) { Roles userRole = (Roles) role; roles.add(userRole.getRole()); - if (userRole.getScope() != null) { - if (userRole.getScope().contains(",")) { - String[] multipleScopes = userRole.getScope().split(","); - for (int i = 0; i < multipleScopes.length; i++) { - scopes.add(multipleScopes[i].replace("[", "").replace("]", "").replace("\"", "").trim()); - } - } else { - if (!"".equals(userRole.getScope())) { - scopes.add(userRole.getScope().replace("[", "").replace("]", "").replace("\"", "").trim()); - } - } - } + scopes.addAll(Stream.of(userRole.getScope().split(",")) + .map(String::new) + .collect(Collectors.toSet()) + ); } if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) { data = commonClassDao.getData(PolicyVersion.class); @@ -157,29 +149,27 @@ public class AutoPushController extends RestrictedBaseController { params.put("scope", scope); List<Object> filterdatas = commonClassDao.getDataByQuery(query, params); if (filterdatas != null) { - for (int i = 0; i < filterdatas.size(); i++) { - data.add(filterdatas.get(i)); - } + data.addAll(filterdatas); } } } else { PolicyVersion emptyPolicyName = new PolicyVersion(); emptyPolicyName - .setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you"); + .setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you"); data.add(emptyPolicyName); } } + ObjectMapper mapper = new ObjectMapper(); model.put("policydatas", mapper.writeValueAsString(data)); JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); JSONObject j = new JSONObject(msg); response.getWriter().write(j.toString()); } catch (Exception e) { - logger.error("Exception Occured" + e); + logger.error("Exception Occurred" + e); } } - @RequestMapping(value = { "/auto_Push/PushPolicyToPDP.htm" }, method = { - org.springframework.web.bind.annotation.RequestMethod.POST }) + @RequestMapping(value = { "/auto_Push/PushPolicyToPDP.htm" }, method = { RequestMethod.POST }) public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException { try { @@ -224,16 +214,15 @@ public class AutoPushController extends RestrictedBaseController { // // Get the current selection - String selectedItem = policyId; // - assert selectedItem != null; + assert policyId != null; // create the id of the target file // Our standard for file naming is: // <domain>.<filename>.<version>.xml // since the file name usually has a ".xml", we need to strip // that // before adding the other parts - String name = selectedItem.replace(File.separator, "."); + String name = policyId.replace(File.separator, "."); String id = name; if (id.endsWith(".xml")) { id = id.replace(".xml", ""); @@ -265,7 +254,6 @@ public class AutoPushController extends RestrictedBaseController { bw.close(); URI selectedURI = temp.toURI(); try { - // // Create the policy selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI); } catch (IOException e) { @@ -352,8 +340,7 @@ public class AutoPushController extends RestrictedBaseController { } @SuppressWarnings("unchecked") - @RequestMapping(value = { "/auto_Push/remove_GroupPolicies.htm" }, method = { - org.springframework.web.bind.annotation.RequestMethod.POST }) + @RequestMapping(value = { "/auto_Push/remove_GroupPolicies.htm" }, method = { RequestMethod.POST }) public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException { try { PolicyController controller = getPolicyControllerInstance(); @@ -374,12 +361,10 @@ public class AutoPushController extends RestrictedBaseController { policyContainer = new PDPPolicyContainer(group); if (removePolicyData.size() > 0) { - for (int i = 0; i < removePolicyData.size(); i++) { - String polData = removePolicyData.get(i).toString(); - this.policyContainer.removeItem(polData); - } - Set<PDPPolicy> changedPolicies = new HashSet<>(); - changedPolicies.addAll((Collection<PDPPolicy>) this.policyContainer.getItemIds()); + IntStream.range(0, removePolicyData.size()).mapToObj(i -> removePolicyData.get(i).toString()) + .forEach(polData -> this.policyContainer.removeItem(polData)); + Set<PDPPolicy> changedPolicies = new HashSet<>( + (Collection<PDPPolicy>) this.policyContainer.getItemIds()); StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(), group.getDescription(), null); updatedGroupObject.setPolicies(changedPolicies); @@ -411,5 +396,4 @@ public class AutoPushController extends RestrictedBaseController { } return null; } - } 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 69444c478..3485163e4 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 @@ -4,6 +4,7 @@ * ================================================================================ * 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. @@ -28,6 +29,7 @@ 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; @@ -35,12 +37,12 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; -import java.nio.charset.StandardCharsets; 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; @@ -71,8 +73,6 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; @Controller @RequestMapping("/") @@ -182,8 +182,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"; } @@ -234,17 +235,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 @@ -260,7 +263,7 @@ public class PolicyController extends RestrictedBaseController { /** * Get FunctionData Type from DB. - * + * * @return list of FunctionData. */ public static Map<Datatype, List<FunctionDefinition>> getFunctionDatatypeMap() { @@ -274,7 +277,7 @@ public class PolicyController extends RestrictedBaseController { /** * Get Function ID. - * + * * @return Function ID. */ public static Map<String, FunctionDefinition> getFunctionIdMap() { @@ -294,7 +297,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<FunctionDefinition>()); + mapDatatype2Function.put(value.getDatatypeBean(), + new ArrayList<FunctionDefinition>()); } mapDatatype2Function.get(value.getDatatypeBean()).add(value); } @@ -302,31 +306,33 @@ public class PolicyController extends RestrictedBaseController { /** * Get Functional Definition data. - * - * @param request HttpServletRequest. + * + * @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) { + @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<String, Object> 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 scope scopeName. * @param policyName policyName. * @return policyEntity data. */ @@ -338,7 +344,7 @@ public class PolicyController extends RestrictedBaseController { /** * Get Policy User Roles from db. - * + * * @param userId LoginID. * @return list of Roles. */ @@ -357,12 +363,13 @@ public class PolicyController extends RestrictedBaseController { /** * Get List of User Roles. - * - * @param request HttpServletRequest. + * + * @param request HttpServletRequest. * @param response HttpServletResponse. */ - @RequestMapping(value = { "/get_UserRolesData" }, method = { - org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) + @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(); @@ -379,11 +386,11 @@ public class PolicyController extends RestrictedBaseController { /** * Policy tabs Model and View. - * + * * @param request Request input. * @return view model. */ - @RequestMapping(value = { "/policy", "/policy/Editor" }, method = RequestMethod.GET) + @RequestMapping(value = {"/policy", "/policy/Editor"}, method = RequestMethod.GET) public ModelAndView view(HttpServletRequest request) { getUserRoleFromSession(request); String myRequestUrl = request.getRequestURL().toString(); @@ -394,7 +401,8 @@ public class PolicyController extends RestrictedBaseController { 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<String, Object> model = new HashMap<>(); return new ModelAndView("policy_Editor", "model", model); @@ -402,7 +410,7 @@ public class PolicyController extends RestrictedBaseController { /** * Read the role from session for inserting into the database. - * + * * @param request Request input for Role. */ public void getUserRoleFromSession(HttpServletRequest request) { @@ -429,7 +437,8 @@ public class PolicyController extends RestrictedBaseController { savePolicyRoles(name, filteredRole, userId); } else { userRoles = getRoles(userId); - Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles); + Pair<Set<String>, List<String>> pair = + org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles); roles = pair.u; if (!roles.contains(filteredRole)) { savePolicyRoles(name, filteredRole, userId); @@ -440,9 +449,9 @@ public class PolicyController extends RestrictedBaseController { /** * Build a delete query for cleaning up roles and execute it. - * + * * @param filteredRoles Filtered roles list. - * @param userId UserID. + * @param userId UserID. */ private void cleanUpRoles(List<String> filteredRoles, String userId) { StringBuilder query = new StringBuilder(); @@ -460,10 +469,10 @@ public class PolicyController extends RestrictedBaseController { /** * Save the Role to DB. - * - * @param name User Name. + * + * @param name User Name. * @param filteredRole Role Name. - * @param userId User LoginID. + * @param userId User LoginID. */ private void savePolicyRoles(String name, String filteredRole, String userId) { UserInfo userInfo = new UserInfo(); @@ -479,7 +488,7 @@ public class PolicyController extends RestrictedBaseController { /** * Filter the list of roles hierarchy wise. - * + * * @param newRoles list of roles from request. * @return */ @@ -501,7 +510,8 @@ public class PolicyController extends RestrictedBaseController { roles.clear(); roles.add(SUPERADMIN); } - if (!roles.contains(SUPERADMIN) || (POLICYGUEST.equalsIgnoreCase(role) && !superCheck)) { + if (!roles.contains(SUPERADMIN) + || (POLICYGUEST.equalsIgnoreCase(role) && !superCheck)) { if ("Policy Admin".equalsIgnoreCase(role.trim())) { roles.add("admin"); } else if ("Policy Editor".equalsIgnoreCase(role.trim())) { @@ -524,7 +534,7 @@ public class PolicyController extends RestrictedBaseController { /** * Get UserName based on LoginID. - * + * * @param createdBy loginID. * @return name. */ @@ -536,7 +546,7 @@ public class PolicyController extends RestrictedBaseController { /** * Check if the Policy is Active or not. - * + * * @param query sql query. * @return boolean. */ @@ -565,7 +575,8 @@ 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<Object> getDataByQuery(String query, SimpleBindings params) { @@ -579,24 +590,19 @@ public class PolicyController extends RestrictedBaseController { /** * Watch Policy Function. - * - * @param entity PolicyVersion entity. + * + * @param entity PolicyVersion entity. * @param policyName updated policy name. - * @param mode type of action rename/delete/import. + * @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. */ @@ -613,7 +619,8 @@ public class PolicyController extends RestrictedBaseController { 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]); @@ -629,8 +636,8 @@ public class PolicyController extends RestrictedBaseController { 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); @@ -654,14 +661,16 @@ public class PolicyController extends RestrictedBaseController { } public String getDescription(PolicyEntity data) { - InputStream stream = new ByteArrayInputStream(data.getPolicyData().getBytes(StandardCharsets.UTF_8)); + 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: " + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + + "Expecting a PolicySet/Policy/Rule object. Got: " + policy.getClass().getCanonicalName()); return null; } @@ -670,14 +679,20 @@ public class PolicyController extends RestrictedBaseController { public String[] getUserInfo(PolicyEntity data, List<PolicyVersion> activePolicies) { String policyName = data.getScope().replace(".", File.separator) + File.separator + data.getPolicyName().substring(0, data.getPolicyName().indexOf('.')); - PolicyVersion pVersion = activePolicies.stream().filter(a -> policyName.equals(a.getPolicyName())).findAny() - .orElse(null); + 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()); + } - UserInfo userCreate = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", pVersion.getCreatedBy()); - UserInfo userModify = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", pVersion.getModifiedBy()); - result[0] = userCreate != null ? userCreate.getUserName() : "super-admin"; - result[1] = userModify != null ? userModify.getUserName() : "super-admin"; + result[0] = userCreate != null ? userCreate.getUserName() : SUPERADMIN; + result[1] = userModify != null ? userModify.getUserName() : SUPERADMIN; return result; } @@ -710,7 +725,8 @@ public class PolicyController extends RestrictedBaseController { return mapDatatype2Function; } - public static void setMapDatatype2Function(Map<Datatype, List<FunctionDefinition>> mapDatatype2Function) { + public static void setMapDatatype2Function( + Map<Datatype, List<FunctionDefinition>> mapDatatype2Function) { PolicyController.mapDatatype2Function = mapDatatype2Function; } @@ -936,7 +952,7 @@ public class PolicyController extends RestrictedBaseController { /** * Set File Size limit. - * + * * @param uploadSize value. */ public static void setFileSizeLimit(String uploadSize) { @@ -954,7 +970,7 @@ public class PolicyController extends RestrictedBaseController { /** * Function to convert date. - * + * * @param dateTTL input date value. * @return */ |