diff options
author | Jorge Hernandez <jorge.hernandez-herrero@att.com> | 2019-03-29 19:36:38 +0000 |
---|---|---|
committer | Gerrit Code Review <gerrit@onap.org> | 2019-03-29 19:36:38 +0000 |
commit | 180257725caf46bdf7f5bb8e08d8390c255ac5d6 (patch) | |
tree | 3101af05ef3d7ecf890b4d3bc62d3c23ca6216ee /POLICY-SDK-APP/src | |
parent | 79ba275a19253eb1e63b128520a29e4516f89a3e (diff) | |
parent | 84540cb5794753f9ade18149238ccde443edac35 (diff) |
Merge "Fix Sonar Issues policy/engine POLICY-SDK-APP module"
Diffstat (limited to 'POLICY-SDK-APP/src')
9 files changed, 383 insertions, 465 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..b7fbbdd98 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())){ + if ("Action".equalsIgnoreCase(policyAdapter.getPolicyType())) { new ActionPolicyController().prePopulateActionPolicyData(policyAdapter, entity); } - 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/PolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java index 7df8602c9..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. @@ -37,7 +38,6 @@ import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import javax.annotation.PostConstruct; -import javax.mail.MessagingException; import javax.script.SimpleBindings; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -597,12 +597,7 @@ public class PolicyController extends RestrictedBaseController { */ 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); } /** |