diff options
Diffstat (limited to 'POLICY-SDK-APP/src/main/java/org/onap')
35 files changed, 2613 insertions, 2569 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 26b9798ac..0965ee63b 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 @@ -22,8 +22,8 @@ package org.onap.policy.admin; - import com.att.research.xacml.util.XACMLProperties; + import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; @@ -39,6 +39,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; + import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.rest.XACMLRestProperties; @@ -63,7 +64,7 @@ public class CheckPDP { private static final Logger LOGGER = FlexLogger.getLogger(CheckPDP.class); private CheckPDP() { - //default constructor + // default constructor } public static Map<String, String> getPdpMap() { @@ -104,9 +105,8 @@ public class CheckPDP { } 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; } @@ -173,7 +173,7 @@ public class CheckPDP { Base64.Encoder encoder = Base64.getEncoder(); // 0 - PDPURL pdpMap.put(pdpValues.get(0), - encoder.encodeToString((userID + ":" + pass).getBytes(StandardCharsets.UTF_8))); + encoder.encodeToString((userID + ":" + pass).getBytes(StandardCharsets.UTF_8))); } else { LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpValues); } 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 6aa40dacf..339702297 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. * Modifications Copyright (C) 2019 Bell Canada * ================================================================================ @@ -22,6 +22,8 @@ package org.onap.policy.admin; +import com.att.research.xacml.util.XACMLProperties; + import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.controller.ActionPolicyController; @@ -37,8 +39,6 @@ import org.onap.policy.controller.DecisionPolicyController; import org.onap.policy.rest.adapter.PolicyRestAdapter; import org.onap.policy.rest.jpa.PolicyEntity; -import com.att.research.xacml.util.XACMLProperties; - public class PolicyAdapter { private static final Logger LOGGER = FlexLogger.getLogger(PolicyAdapter.class); @@ -78,8 +78,8 @@ public class PolicyAdapter { configPolicyName = "Micro Service"; } 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 { configPolicyName = "Base"; @@ -109,10 +109,11 @@ public class PolicyAdapter { 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) { + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException + | IllegalArgumentException e) { LOGGER.error("Exception Occurred" + e); } return null; 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 513fc5795..78d7e5a19 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 @@ -25,6 +25,7 @@ package org.onap.policy.admin; import com.att.research.xacml.util.XACMLProperties; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; @@ -48,6 +49,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; + import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonReader; @@ -59,6 +61,7 @@ import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.apache.commons.compress.utils.IOUtils; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; @@ -89,9 +92,13 @@ import org.onap.policy.xacml.api.XACMLErrorConstants; import org.onap.policy.xacml.util.XACMLPolicyScanner; import org.onap.portalsdk.core.web.support.UserUtils; - -@WebServlet(value = "/fm/*", loadOnStartup = 1, initParams = { - @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.admin.properties", description = "The location of the properties file holding configuration information.") }) +@WebServlet( + value = "/fm/*", + loadOnStartup = 1, + initParams = {@WebInitParam( + name = "XACML_PROPERTIES_NAME", + value = "xacml.admin.properties", + description = "The location of the properties file holding configuration information.")}) public class PolicyManagerServlet extends HttpServlet { private static final Logger LOGGER = FlexLogger.getLogger(PolicyManagerServlet.class); private static final long serialVersionUID = -8453502699403909016L; @@ -126,11 +133,13 @@ public class PolicyManagerServlet extends HttpServlet { private static final String BACKSLASH = "\\"; private static final String ESCAPE_BACKSLASH = "\\\\"; private static final String BACKSLASH_8TIMES = "\\\\\\\\"; - private static final String DELETE_POLICY_VERSION_WHERE_POLICY_NAME = "delete from PolicyVersion where policy_name ='"; + private static final String DELETE_POLICY_VERSION_WHERE_POLICY_NAME = + "delete from PolicyVersion where policy_name ='"; private static final String UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION = "update PolicyVersion set active_version='"; private static final String SPLIT_1 = "split_1"; private static final String SPLIT_0 = "split_0"; - private static final String FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME = "from PolicyEditorScopes where SCOPENAME like :scopeName"; + private static final String FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME = + "from PolicyEditorScopes where SCOPENAME like :scopeName"; private static final String SCOPE_NAME = "scopeName"; private static final String SUCCESS = "success"; private static final String SUB_SCOPENAME = "subScopename"; @@ -141,8 +150,7 @@ public class PolicyManagerServlet extends HttpServlet { private static String testUserId = null; private enum Mode { - LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, - EXPORT, SEARCHLIST + LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT, SEARCHLIST } private static PolicyController policyController; @@ -467,7 +475,8 @@ public class PolicyManagerServlet extends HttpServlet { if (policyName.contains(BACKSLASH)) { policyName = policyName.replace(BACKSLASH, ESCAPE_BACKSLASH); } - String policyVersionQuery = "From PolicyVersion where policy_name = :policyName and active_version = :version and id >0"; + String policyVersionQuery = + "From PolicyVersion where policy_name = :policyName and active_version = :version and id >0"; SimpleBindings pvParams = new SimpleBindings(); pvParams.put("policyName", policyName); pvParams.put(VERSION, version); @@ -672,39 +681,37 @@ public class PolicyManagerServlet extends HttpServlet { Map<String, String> roleByScope) { if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) { List<Object> scopesList = queryPolicyEditorScopes(null); - 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()); - el.put(SIZE, ""); - el.put(TYPE, "dir"); - el.put(CREATED_BY, scope.getUserCreatedBy().getUserName()); - el.put(MODIFIED_BY, scope.getUserModifiedBy().getUserName()); - el.put(ROLETYPE, roleByScope.get(ALLSCOPES)); - resultList.add(el); - }); + 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()); + el.put(SIZE, ""); + el.put(TYPE, "dir"); + el.put(CREATED_BY, scope.getUserCreatedBy().getUserName()); + el.put(MODIFIED_BY, scope.getUserModifiedBy().getUserName()); + el.put(ROLETYPE, roleByScope.get(ALLSCOPES)); + resultList.add(el); + }); } if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)) { - 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()); - el.put(SIZE, ""); - el.put(TYPE, "dir"); - el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName()); - el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName()); - if ((resultList).stream().noneMatch(item -> item.get("name").equals(scopeById.getScopeName()))) { - el.put(ROLETYPE, roleByScope.get(scopeById.getScopeName())); - resultList.add(el); - } - }); + 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()); + el.put(SIZE, ""); + el.put(TYPE, "dir"); + el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName()); + el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName()); + if ((resultList).stream() + .noneMatch(item -> item.get("name").equals(scopeById.getScopeName()))) { + el.put(ROLETYPE, roleByScope.get(scopeById.getScopeName())); + resultList.add(el); + } + }); } } @@ -739,18 +746,18 @@ public class PolicyManagerServlet extends HttpServlet { List<Object> activePolicies = getDataByQueryFromController(controller, query, params); List<Object> scopesList = getDataByQueryFromController(controller, - FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME, params); + FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME, params); for (Object list : scopesList) { scopeName = checkScope(resultList, scopeName, (PolicyEditorScopes) list, roleByScope); } for (Object list : activePolicies) { PolicyVersion policy = (PolicyVersion) list; - String scopeNameValue = policy.getPolicyName().substring(0, - policy.getPolicyName().lastIndexOf(File.separator)); + String scopeNameValue = + policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator)); if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) { String scopeNameCheck = - scopeName.contains(ESCAPE_BACKSLASH) ? scopeName.replace(ESCAPE_BACKSLASH, File.separator) : - scopeName; + scopeName.contains(ESCAPE_BACKSLASH) ? scopeName.replace(ESCAPE_BACKSLASH, File.separator) + : scopeName; if (!scopeNameValue.equals(scopeNameCheck)) { continue; } @@ -762,8 +769,8 @@ public class PolicyManagerServlet extends HttpServlet { 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); + 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)) { @@ -781,7 +788,7 @@ public class PolicyManagerServlet extends HttpServlet { } private List<Object> getDataByQueryFromController(final PolicyController controller, final String query, - final SimpleBindings params) { + final SimpleBindings params) { final List<Object> activePolicies; if (PolicyController.isjUnit()) { activePolicies = controller.getDataByQuery(query, null); @@ -858,8 +865,8 @@ public class PolicyManagerServlet extends HttpServlet { String checkValidation; if (oldPath.endsWith(".xml")) { checkValidation = newPath.replace(".xml", ""); - checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, - checkValidation.lastIndexOf('.')); + checkValidation = + checkValidation.substring(checkValidation.indexOf('_') + 1, 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."); @@ -888,7 +895,8 @@ public class PolicyManagerServlet extends HttpServlet { SimpleBindings pvParams = new SimpleBindings(); pvParams.put(SCOPE_NAME, scopeName + "%"); List<Object> activePolicies = controller.getDataByQuery(query, pvParams); - List<Object> scopesList = controller.getDataByQuery(FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME, 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) + "." @@ -958,7 +966,8 @@ public class PolicyManagerServlet extends HttpServlet { String[] oldPolicySplit = modifyPolicyName(oldPath); // Check PolicyEntity table with newPolicy Name - String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0"; + String policyEntityquery = + "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0"; SimpleBindings policyParams = new SimpleBindings(); policyParams.put("newPolicySplit_1", newPolicySplit[1]); policyParams.put("newPolicySplit_0", newPolicySplit[0]); @@ -969,8 +978,8 @@ 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]); @@ -1042,10 +1051,10 @@ public class PolicyManagerServlet extends HttpServlet { String oldPolicyNameWithoutExtension = removeOldPolicyExtension; String newPolicyNameWithoutExtension = removeNewPolicyExtension; if (removeOldPolicyExtension.endsWith(".xml")) { - oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, - oldPolicyNameWithoutExtension.indexOf('.')); - newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, - newPolicyNameWithoutExtension.indexOf('.')); + oldPolicyNameWithoutExtension = + oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf('.')); + newPolicyNameWithoutExtension = + newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf('.')); } entity.setPolicyName( entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension)); @@ -1065,8 +1074,8 @@ public class PolicyManagerServlet extends HttpServlet { newConfigurationName = configEntity.getConfigurationName(); File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName); if (file.exists()) { - File renameFile = new File( - PolicyController.getConfigHome() + File.separator + newConfigurationName); + File renameFile = + new File(PolicyController.getConfigHome() + File.separator + newConfigurationName); file.renameTo(renameFile); } } else if (newPolicyName.contains(ACTION2)) { @@ -1078,8 +1087,8 @@ public class PolicyManagerServlet extends HttpServlet { newConfigurationName = actionEntity.getActionBodyName(); File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName); if (file.exists()) { - File renameFile = new File( - PolicyController.getActionHome() + File.separator + newConfigurationName); + File renameFile = + new File(PolicyController.getActionHome() + File.separator + newConfigurationName); file.renameTo(renameFile); } } @@ -1087,8 +1096,8 @@ public class PolicyManagerServlet extends HttpServlet { PolicyRestController restController = new PolicyRestController(); restController.notifyOtherPAPSToUpdateConfigurations("rename", newConfigurationName, oldConfigurationName); - PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", - oldPolicyName); + PolicyVersion versionEntity = + (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldPolicyName); versionEntity.setPolicyName(policyName); versionEntity.setModifiedBy(userId); controller.updateData(versionEntity); @@ -1136,8 +1145,8 @@ public class PolicyManagerServlet extends HttpServlet { .getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName); cloneEntity.setConfigurationData(configEntiy); newConfigurationName = configEntiy.getConfigurationName(); - try (FileWriter fw = new FileWriter( - PolicyController.getConfigHome() + File.separator + newConfigurationName); + try (FileWriter fw = + new FileWriter(PolicyController.getConfigHome() + File.separator + newConfigurationName); BufferedWriter bw = new BufferedWriter(fw)) { bw.write(configEntiy.getConfigBody()); } catch (IOException e) { @@ -1158,8 +1167,8 @@ public class PolicyManagerServlet extends HttpServlet { "actionBodyName", queryEntityName); cloneEntity.setActionBodyEntity(actionEntiy); newConfigurationName = actionEntiy.getActionBodyName(); - try (FileWriter fw = new FileWriter( - PolicyController.getActionHome() + File.separator + newConfigurationName); + try (FileWriter fw = + new FileWriter(PolicyController.getActionHome() + File.separator + newConfigurationName); BufferedWriter bw = new BufferedWriter(fw)) { bw.write(actionEntiy.getActionBody()); } catch (IOException e) { @@ -1210,8 +1219,8 @@ public class PolicyManagerServlet extends HttpServlet { String[] newPolicySplit = newPolicyCheck.split(":"); String checkValidation = newPolicySplit[1].replace(".xml", ""); - checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, - checkValidation.lastIndexOf('.')); + checkValidation = + checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf('.')); if (!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)) { return error("Policy Clone Failed. The Name contains special characters."); } @@ -1224,7 +1233,8 @@ public class PolicyManagerServlet extends HttpServlet { boolean success = false; // Check PolicyEntity table with newPolicy Name - String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0"; + String policyEntityquery = + "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0"; SimpleBindings policyParams = new SimpleBindings(); policyParams.put("newPolicySplit_1", newPolicySplit[1]); policyParams.put("newPolicySplit_0", newPolicySplit[0]); @@ -1307,8 +1317,8 @@ public class PolicyManagerServlet extends HttpServlet { if (!policyEntityObjects.isEmpty()) { for (Object object : policyEntityObjects) { policyEntity = (PolicyEntity) object; - String groupEntityquery = "from PolicyGroupEntity where policyid ='" - + policyEntity.getPolicyId() + "'"; + String groupEntityquery = + "from PolicyGroupEntity where policyid ='" + policyEntity.getPolicyId() + "'"; SimpleBindings pgeParams = new SimpleBindings(); List<Object> groupobject = controller.getDataByQuery(groupEntityquery, pgeParams); if (!groupobject.isEmpty()) { @@ -1316,7 +1326,7 @@ public class PolicyManagerServlet extends HttpServlet { activePolicyName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); } else { deleteEntityFromEsAndPolicyEntityTable(controller, restController, policyEntity, - policyNamewithoutExtension); + policyNamewithoutExtension); } } } @@ -1328,8 +1338,8 @@ public class PolicyManagerServlet extends HttpServlet { if (pdpCheck) { // Delete from policyVersion table String getActivePDPPolicyVersion = activePolicyName.replace(".xml", ""); - getActivePDPPolicyVersion = getActivePDPPolicyVersion - .substring(getActivePDPPolicyVersion.lastIndexOf('.') + 1); + getActivePDPPolicyVersion = + getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf('.') + 1); String policyVersionQuery = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION + getActivePDPPolicyVersion + "' , highest_version='" + getActivePDPPolicyVersion + "' where policy_name ='" + policyNamewithoutExtension.replace(BACKSLASH, ESCAPE_BACKSLASH) + "' and id >0"; @@ -1344,11 +1354,11 @@ public class PolicyManagerServlet extends HttpServlet { controller.executeQuery(policyVersionQuery); } } else if ("CURRENT".equals(deleteVersion)) { - String currentVersionPolicyName = policyNamewithExtension - .substring(policyNamewithExtension.lastIndexOf(File.separator) + 1); - String currentVersionScope = policyNamewithExtension - .substring(0, policyNamewithExtension.lastIndexOf(File.separator)) - .replace(File.separator, "."); + String currentVersionPolicyName = + policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator) + 1); + String currentVersionScope = + policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator)) + .replace(File.separator, "."); query = "FROM PolicyEntity where policyName = :currentVersionPolicyName and scope = :currentVersionScope"; SimpleBindings peParams = new SimpleBindings(); @@ -1363,7 +1373,8 @@ public class PolicyManagerServlet extends HttpServlet { return success(); } - String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId and policyid > 0"; + String groupEntityquery = + "from PolicyGroupEntity where policyid = :policyEntityId and policyid > 0"; SimpleBindings geParams = new SimpleBindings(); geParams.put("policyEntityId", policyEntity.getPolicyId()); List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams); @@ -1374,7 +1385,7 @@ public class PolicyManagerServlet extends HttpServlet { // Delete the entity from Elastic Search Database deleteEntityFromEsAndPolicyEntityTable(controller, restController, policyEntity, - policyNamewithoutExtension); + policyNamewithoutExtension); if (version > 1) { int highestVersion = 0; @@ -1495,8 +1506,8 @@ public class PolicyManagerServlet extends HttpServlet { } private void deleteEntityFromEsAndPolicyEntityTable(final PolicyController controller, - final PolicyRestController restController, final PolicyEntity policyEntity, - final String policyNamewithoutExtension) throws IOException { + 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); @@ -1504,16 +1515,16 @@ public class PolicyManagerServlet extends HttpServlet { controller.deleteData(policyEntity); if (policyNamewithoutExtension.contains(CONFIG2)) { Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator - + policyEntity.getConfigurationData().getConfigurationName())); + + policyEntity.getConfigurationData().getConfigurationName())); controller.deleteData(policyEntity.getConfigurationData()); restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, - policyEntity.getConfigurationData().getConfigurationName()); + policyEntity.getConfigurationData().getConfigurationName()); } else if (policyNamewithoutExtension.contains(ACTION2)) { Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator - + policyEntity.getActionBodyEntity().getActionBodyName())); + + policyEntity.getActionBodyEntity().getActionBodyName())); controller.deleteData(policyEntity.getActionBodyEntity()); restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, - policyEntity.getActionBodyEntity().getActionBodyName()); + policyEntity.getActionBodyEntity().getActionBodyName()); } } @@ -1581,7 +1592,7 @@ public class PolicyManagerServlet extends HttpServlet { try { String name = getNameFromParams(params); String validateName = - name.contains(File.separator) ? name.substring(name.lastIndexOf(File.separator) + 1) : name; + name.contains(File.separator) ? name.substring(name.lastIndexOf(File.separator) + 1) : name; if (!name.isEmpty()) { String validate = PolicyUtils.policySpecialCharValidator(validateName); if (!validate.contains(SUCCESS)) { @@ -1591,8 +1602,8 @@ public class PolicyManagerServlet extends HttpServlet { if (name.startsWith(File.separator)) { name = name.substring(1); } - PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, - SCOPE_NAME, name); + PolicyEditorScopes entity = + (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, SCOPE_NAME, name); if (entity != null) { return error("Scope Already Exists"); } 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 1fccfda78..a135397af 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. * Modifications Copyright (C) 2019 Bell Canada * ================================================================================ @@ -51,17 +51,18 @@ import org.springframework.mail.javamail.MimeMessageHelper; * Send policy notification mail depending on the mode for every policy being watched */ @Configurable -public class PolicyNotificationMail{ +public class PolicyNotificationMail { private static final String POLICY_WATCHING_MESSAGE = "The Policy Which you are watching in "; - private static final String EMAIL_MESSAGE_POSTSCRIPT = "Policy Notification System (please don't respond to this email)"; + private static final String EMAIL_MESSAGE_POSTSCRIPT = + "Policy Notification System (please don't respond to this email)"; private static final String ACTIVE_VERSION = "Active Version : "; private static final String SCOPE_POLICY_NAME = "Scope + Policy Name : "; private static final String DELETED_TIME = "Deleted Time : "; private static final String DELETED_BY = "Deleted By : "; - private static Logger policyLogger = FlexLogger.getLogger(PolicyNotificationMail.class); + private static Logger policyLogger = FlexLogger.getLogger(PolicyNotificationMail.class); @Bean - public JavaMailSenderImpl javaMailSenderImpl(){ + public JavaMailSenderImpl javaMailSenderImpl() { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost(PolicyController.getSmtpHost()); mailSender.setPort(Integer.parseInt(PolicyController.getSmtpPort())); @@ -79,51 +80,71 @@ public class PolicyNotificationMail{ * Depending on the mode of operation on the policy, compose the subject and message. * Invoke another internal method to actual send the mail. If the watch list is empty , then * this method returns without sending notification mail + * * @param entityItem Database item from which policy name could be extracted * @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 */ - public void sendMail(PolicyVersion entityItem, String policyName, String mode, CommonClassDao policyNotificationDao) { + public void sendMail(PolicyVersion entityItem, String policyName, String mode, + CommonClassDao policyNotificationDao) { String subject = ""; String message = ""; DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); - if("EditPolicy".equalsIgnoreCase(mode)){ - subject = "Policy has been Updated : "+entityItem.getPolicyName(); - message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been Updated" + '\n' + '\n' + '\n'+ SCOPE_POLICY_NAME + policyName + '\n' + ACTIVE_VERSION +entityItem.getActiveVersion() - + '\n' + '\n' + "Modified By : " +entityItem.getModifiedBy() + '\n' + "Modified Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT; + if ("EditPolicy".equalsIgnoreCase(mode)) { + subject = "Policy has been Updated : " + entityItem.getPolicyName(); + message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been Updated" + '\n' + + '\n' + '\n' + SCOPE_POLICY_NAME + policyName + '\n' + ACTIVE_VERSION + + entityItem.getActiveVersion() + '\n' + '\n' + "Modified By : " + entityItem.getModifiedBy() + '\n' + + "Modified Time : " + dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + + EMAIL_MESSAGE_POSTSCRIPT; } - if("Rename".equalsIgnoreCase(mode)){ - subject = "Policy has been Renamed : "+entityItem.getPolicyName(); - message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been Renamed" + '\n' + '\n' + '\n'+ SCOPE_POLICY_NAME + policyName + '\n' + ACTIVE_VERSION +entityItem.getActiveVersion() - + '\n' + '\n' + "Renamed By : " +entityItem.getModifiedBy() + '\n' + "Renamed Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT; + if ("Rename".equalsIgnoreCase(mode)) { + subject = "Policy has been Renamed : " + entityItem.getPolicyName(); + message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been Renamed" + '\n' + + '\n' + '\n' + SCOPE_POLICY_NAME + policyName + '\n' + ACTIVE_VERSION + + entityItem.getActiveVersion() + '\n' + '\n' + "Renamed By : " + entityItem.getModifiedBy() + '\n' + + "Renamed Time : " + dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + + EMAIL_MESSAGE_POSTSCRIPT; } - if("DeleteAll".equalsIgnoreCase(mode)){ - subject = "Policy has been Deleted : "+entityItem.getPolicyName(); - message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been Deleted with All Versions" + '\n' + '\n' + '\n'+ SCOPE_POLICY_NAME + policyName + '\n' - + '\n' + '\n' + DELETED_BY +entityItem.getModifiedBy() + '\n' + DELETED_TIME +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT; + if ("DeleteAll".equalsIgnoreCase(mode)) { + subject = "Policy has been Deleted : " + entityItem.getPolicyName(); + message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + + " has been Deleted with All Versions" + '\n' + '\n' + '\n' + SCOPE_POLICY_NAME + policyName + '\n' + + '\n' + '\n' + DELETED_BY + entityItem.getModifiedBy() + '\n' + DELETED_TIME + + dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT; } - if("DeleteOne".equalsIgnoreCase(mode)){ - subject = "Policy has been Deleted : "+entityItem.getPolicyName(); - message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been Deleted" + '\n' + '\n' + '\n'+ SCOPE_POLICY_NAME + policyName + '\n' +"Policy Version : " +entityItem.getActiveVersion() - + '\n' + '\n' + DELETED_BY +entityItem.getModifiedBy() + '\n' + DELETED_TIME +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT; + if ("DeleteOne".equalsIgnoreCase(mode)) { + subject = "Policy has been Deleted : " + entityItem.getPolicyName(); + message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been Deleted" + '\n' + + '\n' + '\n' + SCOPE_POLICY_NAME + policyName + '\n' + "Policy Version : " + + entityItem.getActiveVersion() + '\n' + '\n' + DELETED_BY + entityItem.getModifiedBy() + '\n' + + DELETED_TIME + dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT; } - if("DeleteScope".equalsIgnoreCase(mode)){ - subject = "Scope has been Deleted : "+entityItem.getPolicyName(); - message = "The Scope Which you are watching in " + PolicyController.getSmtpApplicationName() + " has been Deleted" + '\n' + '\n' + '\n'+ "Scope + Scope Name : " + policyName + '\n' - + '\n' + '\n' + DELETED_BY +entityItem.getModifiedBy() + '\n' + DELETED_TIME +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT; + if ("DeleteScope".equalsIgnoreCase(mode)) { + subject = "Scope has been Deleted : " + entityItem.getPolicyName(); + message = "The Scope Which you are watching in " + PolicyController.getSmtpApplicationName() + + " has been Deleted" + '\n' + '\n' + '\n' + "Scope + Scope Name : " + policyName + '\n' + '\n' + + '\n' + DELETED_BY + entityItem.getModifiedBy() + '\n' + DELETED_TIME + dateFormat.format(date) + + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT; } - if("SwitchVersion".equalsIgnoreCase(mode)){ - subject = "Policy has been SwitchedVersion : "+entityItem.getPolicyName(); - message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been SwitchedVersion" + '\n' + '\n' + '\n'+ SCOPE_POLICY_NAME + policyName + '\n' + ACTIVE_VERSION +entityItem.getActiveVersion() - + '\n' + '\n' + "Switched By : " +entityItem.getModifiedBy() + '\n' + "Switched Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT; + if ("SwitchVersion".equalsIgnoreCase(mode)) { + subject = "Policy has been SwitchedVersion : " + entityItem.getPolicyName(); + message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been SwitchedVersion" + + '\n' + '\n' + '\n' + SCOPE_POLICY_NAME + policyName + '\n' + ACTIVE_VERSION + + entityItem.getActiveVersion() + '\n' + '\n' + "Switched By : " + entityItem.getModifiedBy() + '\n' + + "Switched Time : " + dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + + EMAIL_MESSAGE_POSTSCRIPT; } - if("Move".equalsIgnoreCase(mode)){ - subject = "Policy has been Moved to Other Scope : "+entityItem.getPolicyName(); - message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been Moved to Other Scope" + '\n' + '\n' + '\n'+ SCOPE_POLICY_NAME + policyName + '\n' + ACTIVE_VERSION +entityItem.getActiveVersion() - + '\n' + '\n' + "Moved By : " +entityItem.getModifiedBy() + '\n' + "Moved Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT; + if ("Move".equalsIgnoreCase(mode)) { + subject = "Policy has been Moved to Other Scope : " + entityItem.getPolicyName(); + message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + + " has been Moved to Other Scope" + '\n' + '\n' + '\n' + SCOPE_POLICY_NAME + policyName + '\n' + + ACTIVE_VERSION + entityItem.getActiveVersion() + '\n' + '\n' + "Moved By : " + + entityItem.getModifiedBy() + '\n' + "Moved Time : " + dateFormat.format(date) + '\n' + '\n' + + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT; } String checkPolicyName = findCheckPolicyName(policyName); @@ -147,7 +168,7 @@ public class PolicyNotificationMail{ if (watchList == null || watchList.isEmpty()) { policyLogger - .debug("List of policy being watched is either null or empty, hence return without sending mail"); + .debug("List of policy being watched is either null or empty, hence return without sending mail"); watchList = new ArrayList<>(); } return watchList; @@ -155,11 +176,11 @@ public class PolicyNotificationMail{ private String findPolicyFileName(PolicyVersion entityItem) { String policyFileName = entityItem.getPolicyName(); - if(policyFileName.contains("/")){ + if (policyFileName.contains("/")) { policyFileName = policyFileName.substring(0, policyFileName.indexOf('/')); policyFileName = policyFileName.replace("/", File.separator); } - if(policyFileName.contains("\\")){ + if (policyFileName.contains("\\")) { policyFileName = policyFileName.substring(0, policyFileName.indexOf('\\')); policyFileName = policyFileName.replace("\\", "\\\\"); } @@ -170,7 +191,7 @@ public class PolicyNotificationMail{ private String findCheckPolicyName(String policyName) { String checkPolicyName = policyName; - if(checkPolicyName.endsWith(".xml") || checkPolicyName.contains(".")){ + if (checkPolicyName.endsWith(".xml") || checkPolicyName.contains(".")) { checkPolicyName = checkPolicyName.substring(0, checkPolicyName.indexOf('.')); } return checkPolicyName; @@ -179,6 +200,7 @@ public class PolicyNotificationMail{ /** * For every policy being watched and when the policy name is one of the Config_, Action_ or Decision_, * send the notification + * * @param mode * @param policyNotificationDao * @param subject @@ -186,21 +208,22 @@ public class PolicyNotificationMail{ * @param checkPolicyName * @param watchList */ - private void composeAndSendMail(String mode, CommonClassDao policyNotificationDao, String subject, String message, String checkPolicyName, List<Object> watchList) { + private void composeAndSendMail(String mode, CommonClassDao policyNotificationDao, String subject, String message, + String checkPolicyName, List<Object> watchList) { String from = PolicyController.getSmtpUsername(); String to; - for(Object watch : watchList){ + for (Object watch : watchList) { WatchPolicyNotificationTable list = (WatchPolicyNotificationTable) watch; String watchPolicyName = list.getPolicyName(); - //this conditino check for specific stringin policy name being watched and - //also if the policy being checked is different from the watched ones, - //then there is no need to send mail, hence continue with next policy in the loop - if((watchPolicyName.contains("Config_") || watchPolicyName.contains("Action_") || watchPolicyName.contains("Decision_")) - && !watchPolicyName.equals(checkPolicyName)){ + // this conditino check for specific stringin policy name being watched and + // also if the policy being checked is different from the watched ones, + // then there is no need to send mail, hence continue with next policy in the loop + if ((watchPolicyName.contains("Config_") || watchPolicyName.contains("Action_") + || watchPolicyName.contains("Decision_")) && !watchPolicyName.equals(checkPolicyName)) { continue; } try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) { - to = list.getLoginIds()+"@"+PolicyController.getSmtpEmailExtension(); + to = list.getLoginIds() + "@" + PolicyController.getSmtpEmailExtension(); to = to.trim(); ctx.register(PolicyNotificationMail.class); ctx.refresh(); @@ -212,11 +235,12 @@ public class PolicyNotificationMail{ mailMsg.setSubject(subject); mailMsg.setText(message); mailSender.send(mimeMessage); - if("Rename".equalsIgnoreCase(mode) || mode.contains("Delete") || mode.contains("Move")){ + if ("Rename".equalsIgnoreCase(mode) || mode.contains("Delete") || mode.contains("Move")) { policyNotificationDao.delete(watch); } } catch (Exception e) { - policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Exception Occured in Policy Notification" +e); + policyLogger + .error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception Occured in Policy Notification" + e); } } 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 03dbccfd9..9d078a983 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 @@ -27,6 +27,7 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; + import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; @@ -39,8 +40,10 @@ import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Base64; import java.util.List; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; @@ -121,8 +124,6 @@ public class PolicyRestController extends RestrictedBaseController { PolicyRestController.commonClassDao = commonClassDao; } - - @RequestMapping(value = {"/policycreation/save_policy"}, method = {RequestMethod.POST}) public void policyCreationController(HttpServletRequest request, HttpServletResponse response) { String userId = UserUtils.getUserSession(request).getOrgUserId(); @@ -227,7 +228,6 @@ public class PolicyRestController extends RestrictedBaseController { } } - private ResponseEntity<?> sendToPAP(String body, String requestURI, HttpMethod method) { String papUrl = PolicyController.getPapUrl(); String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); @@ -292,7 +292,6 @@ public class PolicyRestController extends RestrictedBaseController { headers.set(AUTHORIZATION, BASIC + encoding); headers.set(CONTENT_TYPE, PolicyController.getContenttype()); - HttpURLConnection connection = null; List<FileItem> items; FileItem item = null; 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 7e0aef2e9..ac11776a1 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * 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"); @@ -18,8 +18,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.admin; +import com.fasterxml.jackson.databind.ObjectMapper; + import java.util.HashMap; import java.util.Map; @@ -36,8 +39,6 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; -import com.fasterxml.jackson.databind.ObjectMapper; - @Controller @RequestMapping("/") public class PolicyUserInfoController extends RestrictedBaseController { 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 c0987c38c..fc1a70466 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 @@ -22,6 +22,14 @@ package org.onap.policy.admin; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.att.research.xacml.api.pap.PDPStatus; +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.type.CollectionType; + import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -39,6 +47,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; + import org.apache.commons.io.IOUtils; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; @@ -55,13 +64,6 @@ import org.onap.policy.xacml.std.pap.StdPDPGroup; import org.onap.policy.xacml.std.pap.StdPDPItemSetChangeNotifier; import org.onap.policy.xacml.std.pap.StdPDPPolicy; import org.onap.policy.xacml.std.pap.StdPDPStatus; -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.api.pap.PDPPolicy; -import com.att.research.xacml.api.pap.PDPStatus; -import com.att.research.xacml.util.XACMLProperties; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.type.CollectionType; /** * Implementation of the PAPEngine interface that communicates with a PAP engine in a remote servlet through a RESTful @@ -259,8 +261,6 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP "policyType=" + policyType); } - - @Override public void publishPolicy(String id, String name, boolean isRoot, InputStream policy, OnapPDPGroup group) throws PAPException { 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 b116af6ef..60029f8d7 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2019 Bell Canada * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -39,7 +39,9 @@ import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; + import javax.xml.bind.JAXBElement; + import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; @@ -57,6 +59,7 @@ 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 oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType; + import org.apache.commons.io.FilenameUtils; import org.json.JSONObject; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -95,7 +98,6 @@ public class HumanPolicyComponent { public static final String EMPTY_STRING = ""; private static final String ENTER = "ENTER"; - private static HtmlProcessor htmlProcessor; private static File policyFile; @@ -357,7 +359,6 @@ class HtmlProcessor extends SimpleCallback { String id = "-"; String version = "-"; - if (policySet.getPolicyCombiningAlgId() != null) combiningAlgorithm = extractLastIdentifier(policySet.getPolicyCombiningAlgId(), ":"); @@ -367,7 +368,6 @@ class HtmlProcessor extends SimpleCallback { if (policySet.getVersion() != null) version = policySet.getVersion(); - htmlOut.println("<" + htmlListElement + "><b>Policy Set ID</b>: <i>" + id + "</i> (v" + version + ") " + "</" + htmlListElement + ">"); @@ -441,7 +441,6 @@ class HtmlProcessor extends SimpleCallback { String id = "-"; String version = "-"; - if (policy.getRuleCombiningAlgId() != null) combiningAlgorithm = extractLastIdentifier(policy.getRuleCombiningAlgId(), ":"); @@ -477,7 +476,6 @@ class HtmlProcessor extends SimpleCallback { } } - @Override public CallbackResult onPreVisitRule(PolicyType parent, RuleType rule) { if (LOGGER.isTraceEnabled()) diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/conf/HibernateSession.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/conf/HibernateSession.java index 0e1be9349..82583c5f5 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/conf/HibernateSession.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/conf/HibernateSession.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,41 +35,40 @@ import org.onap.policy.controller.PolicyController; import org.onap.policy.rest.jpa.SystemLogDB; @SuppressWarnings("deprecation") -public class HibernateSession{ +public class HibernateSession { - private static final Logger LOGGER = FlexLogger.getLogger(HibernateSession.class); - - private static SessionFactory logSessionFactory; - - static { - try { - Properties prop= new Properties(); - prop.setProperty("hibernate.connection.url", PolicyController.getLogdbUrl()); - prop.setProperty("hibernate.connection.username", PolicyController.getLogdbUserName()); - prop.setProperty("hibernate.connection.password", PolicyController.getLogdbPassword()); - prop.setProperty("dialect", PolicyController.getLogdbDialect()); - prop.setProperty("hibernate.connection.driver_class", PolicyController.getLogdbDriver()); - prop.setProperty("show_sql", "false"); - logSessionFactory = new Configuration().addPackage("org.onap.policy.*").addProperties(prop) - .addAnnotatedClass(SystemLogDB.class).buildSessionFactory(); - } catch (Exception ex) { - LOGGER.error("Exception Occured while creating Log database Hibernate session"+ex); - } - } + private static final Logger LOGGER = FlexLogger.getLogger(HibernateSession.class); - private HibernateSession(){ - /** - empty implementation - */ - } + private static SessionFactory logSessionFactory; - public static Session getSession(){ - return logSessionFactory.openSession(); - } - - public static void setSession(SessionFactory logSessionFactory1){ - logSessionFactory = logSessionFactory1; - } + static { + try { + Properties prop = new Properties(); + prop.setProperty("hibernate.connection.url", PolicyController.getLogdbUrl()); + prop.setProperty("hibernate.connection.username", PolicyController.getLogdbUserName()); + prop.setProperty("hibernate.connection.password", PolicyController.getLogdbPassword()); + prop.setProperty("dialect", PolicyController.getLogdbDialect()); + prop.setProperty("hibernate.connection.driver_class", PolicyController.getLogdbDriver()); + prop.setProperty("show_sql", "false"); + logSessionFactory = new Configuration().addPackage("org.onap.policy.*").addProperties(prop) + .addAnnotatedClass(SystemLogDB.class).buildSessionFactory(); + } catch (Exception ex) { + LOGGER.error("Exception Occured while creating Log database Hibernate session" + ex); + } + } + private HibernateSession() { + /** + * empty implementation + */ + } + + public static Session getSession() { + return logSessionFactory.openSession(); + } + + public static void setSession(SessionFactory logSessionFactory1) { + logSessionFactory = logSessionFactory1; + } } 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 578258403..9f89ea0cf 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * 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"); @@ -30,13 +30,6 @@ import java.util.Map.Entry; 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.portalsdk.core.controller.RestrictedBaseController; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType; @@ -51,8 +44,15 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +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.portalsdk.core.controller.RestrictedBaseController; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + @Controller -@RequestMapping({ "/" }) +@RequestMapping({"/"}) public class ActionPolicyController extends RestrictedBaseController { private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicyController.class); private static final String PERFORMER_ATTRIBUTE_ID = "performer"; @@ -116,15 +116,15 @@ public class ActionPolicyController extends RestrictedBaseController { for (ObligationExpressionType obligation : obligationList) { policyAdapter.setActionAttributeValue(obligation.getObligationId()); // Under the obligationExpression we have attributeAssignmentExpression. - List<AttributeAssignmentExpressionType> attributeAssignmentExpressionList = obligation - .getAttributeAssignmentExpression(); + List<AttributeAssignmentExpressionType> attributeAssignmentExpressionList = + obligation.getAttributeAssignmentExpression(); if (attributeAssignmentExpressionList == null) { continue; } for (AttributeAssignmentExpressionType attributeAssignmentExpression : attributeAssignmentExpressionList) { String attributeID = attributeAssignmentExpression.getAttributeId(); - AttributeValueType attributeValue = (AttributeValueType) attributeAssignmentExpression - .getExpression().getValue(); + AttributeValueType attributeValue = + (AttributeValueType) attributeAssignmentExpression.getExpression().getValue(); if (!attributeID.equals(PERFORMER_ATTRIBUTE_ID)) { continue; } @@ -139,8 +139,8 @@ public class ActionPolicyController extends RestrictedBaseController { private void setPolicyAdapterPolicyNameAndDesc(PolicyRestAdapter policyAdapter, PolicyType policy) { policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - String policyNameValue = policyAdapter.getPolicyName() - .substring(policyAdapter.getPolicyName().indexOf('_') + 1); + String policyNameValue = + policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf('_') + 1); policyAdapter.setPolicyName(policyNameValue); String description; try { @@ -253,7 +253,7 @@ public class ActionPolicyController extends RestrictedBaseController { ruleMap.put("id", "A" + (index + 1)); // Populate combo box Map<String, String> dropDownMap = PolicyController.getDropDownMap(); - for ( Entry<String, String> entry : dropDownMap.entrySet()) { + for (Entry<String, String> entry : dropDownMap.entrySet()) { if (entry.getValue().equals(actionApply.getFunctionId())) { ruleMap.put("dynamicRuleAlgorithmCombo", entry.getKey()); } @@ -264,8 +264,8 @@ public class ActionPolicyController extends RestrictedBaseController { // Get from Attribute Designator ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(0).getValue(); List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression(); - AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0) - .getValue(); + AttributeDesignatorType attributeDesignator = + (AttributeDesignatorType) jaxbInnerActionTypes.get(0).getValue(); ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, attributeDesignator.getAttributeId()); // Get from Attribute Value @@ -281,8 +281,8 @@ public class ActionPolicyController extends RestrictedBaseController { ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(1).getValue(); List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression(); - AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0) - .getValue(); + AttributeDesignatorType attributeDesignator = + (AttributeDesignatorType) jaxbInnerActionTypes.get(0).getValue(); 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 fc25e29f0..92f125a7d 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * 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"); @@ -21,6 +21,10 @@ package org.onap.policy.controller; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; @@ -44,10 +48,6 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - @Controller @RequestMapping({"/"}) public class AdminTabController extends RestrictedBaseController { @@ -58,7 +58,7 @@ public class AdminTabController extends RestrictedBaseController { private static CommonClassDao commonClassDao; public AdminTabController() { - //default constructor + // default constructor } @Autowired @@ -74,8 +74,10 @@ public class AdminTabController extends RestrictedBaseController { AdminTabController.commonClassDao = commonClassDao; } - @RequestMapping(value = {"/get_LockDownData"}, method = { - org.springframework.web.bind.annotation.RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) + @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<>(); @@ -89,22 +91,23 @@ public class AdminTabController extends RestrictedBaseController { } } - @RequestMapping(value = {"/adminTabController/save_LockDownValue.htm"}, method = { - org.springframework.web.bind.annotation.RequestMethod.POST}) + @RequestMapping( + value = {"/adminTabController/save_LockDownValue.htm"}, + method = {org.springframework.web.bind.annotation.RequestMethod.POST}) public ModelAndView saveAdminTabLockdownValue(HttpServletRequest request, HttpServletResponse response) - throws IOException { + 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*****************************************"); + "****************************************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); + GlobalRoleSettings globalRole = + mapper.readValue(root.get("lockdowndata").toString(), GlobalRoleSettings.class); globalRole.setRole("super-admin"); commonClassDao.update(globalRole); 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 a42d3d8d7..ca62d82a4 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 @@ -26,6 +26,7 @@ import com.att.research.xacml.api.pap.PDPPolicy; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -45,9 +46,11 @@ 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; + import org.json.JSONObject; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; @@ -121,7 +124,9 @@ public class AutoPushController extends RestrictedBaseController { return scopes; } - @RequestMapping(value = {"/get_AutoPushPoliciesContainerData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_AutoPushPoliciesContainerData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response) { try { diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java index 8c14048c4..33b780348 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. * Modifications Copyright (C) 2019 Bell Canada * ================================================================================ @@ -22,6 +22,10 @@ package org.onap.policy.controller; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; @@ -36,12 +40,23 @@ import java.util.Objects; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; - import java.util.stream.Collectors; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.bind.JAXBElement; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + import org.apache.commons.collections.CollectionUtils; import org.json.JSONObject; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -57,21 +72,6 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; - @Controller @RequestMapping("/") public class CreateBRMSParamController extends RestrictedBaseController { @@ -104,8 +104,7 @@ public class CreateBRMSParamController extends RestrictedBaseController { private static String brmsTemplateVlaue = "<$%BRMSParamTemplate="; private static String string = "String"; - - @RequestMapping(value = {"/policyController/getBRMSTemplateData.htm"}, method = { RequestMethod.POST}) + @RequestMapping(value = {"/policyController/getBRMSTemplateData.htm"}, method = {RequestMethod.POST}) public void getBRMSParamPolicyRuleData(HttpServletRequest request, HttpServletResponse response) { try { dynamicLayoutMap = new HashMap<>(); @@ -129,7 +128,7 @@ public class CreateBRMSParamController extends RestrictedBaseController { private String findRule(String ruleTemplate) { List<Object> datas = commonClassDao.getDataById(BRMSParamTemplate.class, "ruleName", ruleTemplate); - if(CollectionUtils.isNotEmpty(datas)){ + if (CollectionUtils.isNotEmpty(datas)) { BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate) datas.get(0); return bRMSParamTemplate.getRule(); } @@ -151,7 +150,7 @@ public class CreateBRMSParamController extends RestrictedBaseController { private void processRule(String rule) { StringBuilder params = getParamsBuilderFromRule(rule); params = new StringBuilder( - params.toString().replace("declare Params", "").replace("end", "").replaceAll("\\s+", "")); + params.toString().replace("declare Params", "").replace("end", "").replaceAll("\\s+", "")); String[] components = params.toString().split(":"); String caption = ""; for (int i = 0; i < components.length; i++) { @@ -244,7 +243,8 @@ public class CreateBRMSParamController extends RestrictedBaseController { } /* - * When the User Click Edit or View Policy the following method will get invoked for setting the data to PolicyRestAdapter. + * When the User Click Edit or View Policy the following method will get invoked for setting the data to + * PolicyRestAdapter. * Which is used to bind the data in GUI */ public void prePopulateBRMSParamPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { @@ -254,11 +254,11 @@ public class CreateBRMSParamController extends RestrictedBaseController { policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); // policy name value is the policy name without any prefix and // Extensions. - String policyNameValue = policyAdapter.getPolicyName() - .substring(policyAdapter.getPolicyName().indexOf("BRMS_Param_") + 11); + String policyNameValue = + policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Param_") + 11); if (policyLogger.isDebugEnabled()) { policyLogger - .debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName()); + .debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName()); } policyAdapter.setPolicyName(policyNameValue); String description; @@ -281,11 +281,10 @@ public class CreateBRMSParamController extends RestrictedBaseController { // Get the target data under policy. policyAdapter.setDynamicLayoutMap(dynamicLayoutMap); if (policyAdapter.getDynamicLayoutMap().size() > 0) { - LinkedHashMap<String, String> drlRule = policyAdapter.getDynamicLayoutMap() - .keySet().stream() - .collect(Collectors - .toMap(String::toString, keyValue -> policyAdapter.getDynamicLayoutMap().get(keyValue), - (a, b) -> b, LinkedHashMap::new)); + LinkedHashMap<String, String> drlRule = policyAdapter.getDynamicLayoutMap().keySet().stream() + .collect(Collectors.toMap(String::toString, + keyValue -> policyAdapter.getDynamicLayoutMap().get(keyValue), (a, b) -> b, + LinkedHashMap::new)); policyAdapter.setRuleData(drlRule); } TargetType target = policy.getTarget(); @@ -298,24 +297,25 @@ public class CreateBRMSParamController extends RestrictedBaseController { private void setDataAdapterFromAdviceExpressions(PolicyType policy, PolicyRestAdapter policyAdapter) { ArrayList<Object> attributeList = new ArrayList<>(); // Set Attributes. - AdviceExpressionsType expressionTypes = ((RuleType) policy - .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions(); + AdviceExpressionsType expressionTypes = + ((RuleType) policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)) + .getAdviceExpressions(); for (AdviceExpressionType adviceExpression : expressionTypes.getAdviceExpression()) { for (AttributeAssignmentExpressionType attributeAssignment : adviceExpression - .getAttributeAssignmentExpression()) { + .getAttributeAssignmentExpression()) { if (attributeAssignment.getAttributeId().startsWith("key:")) { Map<String, String> attribute = new HashMap<>(); String key = attributeAssignment.getAttributeId().replace("key:", ""); attribute.put("key", key); @SuppressWarnings("unchecked") - JAXBElement<AttributeValueType> attributeValue = (JAXBElement<AttributeValueType>) attributeAssignment - .getExpression(); + JAXBElement<AttributeValueType> attributeValue = + (JAXBElement<AttributeValueType>) attributeAssignment.getExpression(); String value = (String) attributeValue.getValue().getContent().get(0); attribute.put("value", value); attributeList.add(attribute); } else if (attributeAssignment.getAttributeId().startsWith("dependencies:")) { - ArrayList<String> dependencies = new ArrayList<>( - Arrays.asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(","))); + ArrayList<String> dependencies = new ArrayList<>(Arrays + .asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(","))); dependencies.remove(""); policyAdapter.setBrmsDependency(dependencies); } else if (attributeAssignment.getAttributeId().startsWith("controller:")) { @@ -332,10 +332,8 @@ public class CreateBRMSParamController extends RestrictedBaseController { if (anyOfList == null) { return; } - anyOfList.stream().map(AnyOfType::getAllOf) - .filter(Objects::nonNull) - .flatMap(Collection::stream) - .forEach(allOf -> setDataToAdapterFromMatchList(allOf.getMatch(), policyAdapter)); + anyOfList.stream().map(AnyOfType::getAllOf).filter(Objects::nonNull).flatMap(Collection::stream) + .forEach(allOf -> setDataToAdapterFromMatchList(allOf.getMatch(), policyAdapter)); } private void setDataToAdapterFromMatchList(List<MatchType> matchList, PolicyRestAdapter policyAdapter) { @@ -390,8 +388,8 @@ public class CreateBRMSParamController extends RestrictedBaseController { String value = line.substring(line.indexOf("<%$"), line.indexOf("$%>")); value = value.replaceAll("<%\\$Values=", ""); Arrays.stream(value.split(":\\|:")).map(keyValue -> keyValue.split(":-:")) - .filter(pair -> pair.length > 0) - .forEach(pair -> dynamicLayoutMap.put(pair[0], (pair.length > 1) ? pair[1] : "")); + .filter(pair -> pair.length > 0) + .forEach(pair -> dynamicLayoutMap.put(pair[0], (pair.length > 1) ? pair[1] : "")); return; } if (line.startsWith("/*")) { @@ -429,32 +427,26 @@ public class CreateBRMSParamController extends RestrictedBaseController { } } params = new StringBuilder(params.substring(params.indexOf(".Params\"") + 11)); - params = new StringBuilder(params.toString().replaceAll("\\s+", "") - .replace("salience1000whenthenParamsparams=newParams();", "") - .replace("insert(params);end", "") - .replace("params.set", "")); + params = new StringBuilder( + params.toString().replaceAll("\\s+", "").replace("salience1000whenthenParamsparams=newParams();", "") + .replace("insert(params);end", "").replace("params.set", "")); updateCaptionToDynamicLayoutMap(params); } private void updateCaptionToDynamicLayoutMap(final StringBuilder params) { String[] components = params.toString().split("\\);"); - if(components.length > 0){ + if (components.length > 0) { for (int i = 0; i < components.length; i++) { String value; components[i] = components[i] + ")"; - String caption = components[i].substring(0, - components[i].indexOf('(')); + String caption = components[i].substring(0, components[i].indexOf('(')); caption = caption.substring(0, 1).toLowerCase() + caption.substring(1); if (components[i].contains("(\"")) { - value = components[i] - .substring(components[i].indexOf("(\""), - components[i].indexOf("\")")) - .replace("(\"", "").replace("\")", ""); + value = components[i].substring(components[i].indexOf("(\""), components[i].indexOf("\")")) + .replace("(\"", "").replace("\")", ""); } else { - value = components[i] - .substring(components[i].indexOf('('), - components[i].indexOf(')')) - .replace("(", "").replace(")", ""); + value = components[i].substring(components[i].indexOf('('), components[i].indexOf(')')) + .replace("(", "").replace(")", ""); } dynamicLayoutMap.put(caption, value); } @@ -473,8 +465,7 @@ public class CreateBRMSParamController extends RestrictedBaseController { private String processMultiLineFullComment(String line) { try { - line = splitMultiLineStartComment(line) - + splitMultiLineEndComment(line); + line = splitMultiLineStartComment(line) + splitMultiLineEndComment(line); } catch (Exception e) { policyLogger.info("Just for Logging" + e); line = splitMultiLineStartComment(line); @@ -484,26 +475,25 @@ public class CreateBRMSParamController extends RestrictedBaseController { // set View Rule @SuppressWarnings("unchecked") - @RequestMapping(value = {"/policyController/ViewBRMSParamPolicyRule.htm"}, method = { RequestMethod.POST}) + @RequestMapping(value = {"/policyController/ViewBRMSParamPolicyRule.htm"}, method = {RequestMethod.POST}) public void setViewRule(HttpServletRequest request, HttpServletResponse response) { try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); - PolicyRestAdapter policyData = mapper - .readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), - PolicyRestAdapter.class); + PolicyRestAdapter policyData = mapper.readValue( + root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class); policyData.setDomainDir( - root.get(PolicyController.getPolicydata()).get("model").get("name").toString().replace("\"", "")); + root.get(PolicyController.getPolicydata()).get("model").get("name").toString().replace("\"", "")); if (root.get(PolicyController.getPolicydata()).get("model").get("type").toString().replace("\"", "") - .equals(PolicyController.getFile())) { + .equals(PolicyController.getFile())) { policyData.setEditPolicy(true); } String body = findRule(policyData.getRuleName()) + "\n"; StringBuilder generatedMetadata = new StringBuilder().append( - "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t ") - .append(brmsTemplateVlaue).append(policyData.getRuleName()).append("%$> \n */ \n"); + "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t ") + .append(brmsTemplateVlaue).append(policyData.getRuleName()).append("%$> \n */ \n"); if (policyData.getDynamicLayoutMap().size() > 0) { generatedMetadata.append("/* <%$Values="); @@ -518,26 +508,25 @@ public class CreateBRMSParamController extends RestrictedBaseController { policyLogger.info("Metadata generated with :" + generatedMetadata.toString()); body = generatedMetadata.toString() + body; // Expand the body. - Map<String, String> copyMap = new HashMap<>( - (Map<? extends String, ? extends String>) policyData.getRuleData()); + Map<String, String> copyMap = + new HashMap<>((Map<? extends String, ? extends String>) policyData.getRuleData()); copyMap.put("policyName", - policyData.getDomainDir().replace("\\", ".") + ".Config_BRMS_Param_" + policyData.getPolicyName()); + policyData.getDomainDir().replace("\\", ".") + ".Config_BRMS_Param_" + policyData.getPolicyName()); copyMap.put("policyScope", policyData.getDomainDir().replace("\\", ".")); copyMap.put("policyVersion", "1"); - //Finding all the keys in the Map data-structure. + // Finding all the keys in the Map data-structure. Set<String> keySet = copyMap.keySet(); Iterator<String> iterator = keySet.iterator(); Pattern p; Matcher m; while (iterator.hasNext()) { - //Converting the first character of the key into a lower case. + // Converting the first character of the key into a lower case. String input = iterator.next(); - String output = Character.toLowerCase(input.charAt(0)) + - (input.length() > 1 ? input.substring(1) : ""); - //Searching for a pattern in the String using the key. + String output = Character.toLowerCase(input.charAt(0)) + (input.length() > 1 ? input.substring(1) : ""); + // Searching for a pattern in the String using the key. p = Pattern.compile("\\$\\{" + output + "\\}"); m = p.matcher(body); - //Replacing the value with the inputs provided by the user in the editor. + // Replacing the value with the inputs provided by the user in the editor. body = m.replaceAll(copyMap.get(input)); } response.setCharacterEncoding("UTF-8"); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java index 93ca28190..9974292fb 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * 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"); @@ -27,8 +27,8 @@ import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; - import java.util.Objects; + import javax.xml.bind.JAXBElement; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; @@ -90,37 +90,35 @@ public class CreateBRMSRawController { private void setPolicyAdapterMatchAttributes(PolicyRestAdapter policyAdapter, List<AnyOfType> anyOfList) { anyOfList.stream() - //Extract nonNull list of AllOfType objs from each AnyOfType obj - .map(AnyOfType::getAllOf).filter(Objects::nonNull) - .forEach(allOfList -> - //Extract nonNull list of MatchType objs from each AllOFType obj - allOfList.stream().map(AllOfType::getMatch).filter(Objects::nonNull) - .flatMap(Collection::stream) - .forEach(match -> { - // Under the match we have attribute value and - // attributeDesignator. So,finally down to the actual attribute. - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - if ("RiskType".equals(attributeId)) { - policyAdapter.setRiskType(value); - } else if ("RiskLevel".equals(attributeId)) { - policyAdapter.setRiskLevel(value); - } else if ("guard".equals(attributeId)) { - policyAdapter.setGuard(value); - } else if ("TTLDate".equals(attributeId) && !value.contains("NA")) { - PolicyController controller = new PolicyController(); - String newDate = controller.convertDate(value); - policyAdapter.setTtlDate(newDate); - } - })); + // Extract nonNull list of AllOfType objs from each AnyOfType obj + .map(AnyOfType::getAllOf).filter(Objects::nonNull).forEach(allOfList -> + // Extract nonNull list of MatchType objs from each AllOFType obj + allOfList.stream().map(AllOfType::getMatch).filter(Objects::nonNull).flatMap(Collection::stream) + .forEach(match -> { + // Under the match we have attribute value and + // attributeDesignator. So,finally down to the actual attribute. + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + if ("RiskType".equals(attributeId)) { + policyAdapter.setRiskType(value); + } else if ("RiskLevel".equals(attributeId)) { + policyAdapter.setRiskLevel(value); + } else if ("guard".equals(attributeId)) { + policyAdapter.setGuard(value); + } else if ("TTLDate".equals(attributeId) && !value.contains("NA")) { + PolicyController controller = new PolicyController(); + String newDate = controller.convertDate(value); + policyAdapter.setTtlDate(newDate); + } + })); } private void setPolicyAdapterNameValue(final PolicyRestAdapter policyAdapter) { // policy name value is the policy name without any prefix and extensions. - String policyNameValue = policyAdapter.getPolicyName() - .substring(policyAdapter.getPolicyName().indexOf("BRMS_Raw_") + 9); + String policyNameValue = + policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Raw_") + 9); if (logger.isDebugEnabled()) { logger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName()); } @@ -140,28 +138,28 @@ public class CreateBRMSRawController { private void setPolicyAdapterAttributes(final PolicyRestAdapter policyAdapter, final PolicyType policy) { ArrayList<Object> attributeList = new ArrayList<>(); - AdviceExpressionsType expressionTypes = ((RuleType) policy - .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions(); + AdviceExpressionsType expressionTypes = + ((RuleType) policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)) + .getAdviceExpressions(); for (AdviceExpressionType adviceExpression : expressionTypes.getAdviceExpression()) { for (AttributeAssignmentExpressionType attributeAssignment : adviceExpression - .getAttributeAssignmentExpression()) { + .getAttributeAssignmentExpression()) { if (attributeAssignment.getAttributeId().startsWith("key:")) { Map<String, String> attribute = new HashMap<>(); String key = attributeAssignment.getAttributeId().replace("key:", ""); attribute.put("key", key); - JAXBElement<AttributeValueType> attributeValue = (JAXBElement<AttributeValueType>) attributeAssignment - .getExpression(); + JAXBElement<AttributeValueType> attributeValue = + (JAXBElement<AttributeValueType>) attributeAssignment.getExpression(); String value = (String) attributeValue.getValue().getContent().get(0); attribute.put("value", value); attributeList.add(attribute); } else if (attributeAssignment.getAttributeId().startsWith("dependencies:")) { ArrayList<String> dependencies = new ArrayList<>(Arrays - .asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(","))); + .asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(","))); dependencies.remove(""); policyAdapter.setBrmsDependency(dependencies); } else if (attributeAssignment.getAttributeId().startsWith("controller:")) { - policyAdapter - .setBrmsController(attributeAssignment.getAttributeId().replace("controller:", "")); + policyAdapter.setBrmsController(attributeAssignment.getAttributeId().replace("controller:", "")); } } policyAdapter.setAttributes(attributeList); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java index 4c3249311..b88a59958 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * 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"); @@ -21,6 +21,11 @@ package org.onap.policy.controller; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; + import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; @@ -29,9 +34,16 @@ import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; - import java.util.Objects; import java.util.stream.IntStream; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.rest.adapter.ClosedLoopFaultBody; @@ -48,18 +60,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectWriter; - -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; - @Controller @RequestMapping("/") public class CreateClosedLoopFaultController extends RestrictedBaseController { @@ -94,15 +94,14 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - ClosedLoopFaultTrapDatas trapDatas = mapper - .readValue(root.get("trapData").toString(), ClosedLoopFaultTrapDatas.class); - ClosedLoopFaultTrapDatas faultDatas = mapper - .readValue(root.get("faultData").toString(), ClosedLoopFaultTrapDatas.class); - ClosedLoopGridJSONData policyJsonData = mapper - .readValue(root.get("policyData").get("policy").toString(), ClosedLoopGridJSONData.class); - ClosedLoopFaultBody jsonBody = mapper - .readValue(root.get("policyData").get("policy").get("jsonBodyData").toString(), - ClosedLoopFaultBody.class); + ClosedLoopFaultTrapDatas trapDatas = + mapper.readValue(root.get("trapData").toString(), ClosedLoopFaultTrapDatas.class); + ClosedLoopFaultTrapDatas faultDatas = + mapper.readValue(root.get("faultData").toString(), ClosedLoopFaultTrapDatas.class); + ClosedLoopGridJSONData policyJsonData = + mapper.readValue(root.get("policyData").get("policy").toString(), ClosedLoopGridJSONData.class); + ClosedLoopFaultBody jsonBody = mapper.readValue( + root.get("policyData").get("policy").get("jsonBodyData").toString(), ClosedLoopFaultBody.class); // Build trapSignatureDatas list from faultData List<Object> trapSignatureDatas = new ArrayList<>(); @@ -121,7 +120,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { uiTriggerSignatures.setSignatures(getUITriggerSignature(TRAP, trapSignatureDatas.get(0))); if (!policyJsonData.getConnecttriggerSignatures().isEmpty()) { uiTriggerSignatures - .setConnectSignatures(getUIConnectTraps(policyJsonData.getConnecttriggerSignatures())); + .setConnectSignatures(getUIConnectTraps(policyJsonData.getConnecttriggerSignatures())); } } jsonBody.setTriggerSignaturesUsedForUI(uiTriggerSignatures); @@ -146,8 +145,8 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { if (!faultSignatureDatas.isEmpty()) { uifaultSignatures.setSignatures(getUITriggerSignature(FAULT, faultSignatureDatas.get(0))); if (!policyJsonData.getConnectVerificationSignatures().isEmpty()) { - uifaultSignatures - .setConnectSignatures(getUIConnectTraps(policyJsonData.getConnectVerificationSignatures())); + uifaultSignatures.setConnectSignatures( + getUIConnectTraps(policyJsonData.getConnectVerificationSignatures())); } } jsonBody.setVerificationSignaturesUsedForUI(uifaultSignatures); @@ -170,8 +169,9 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { if (!policyJsonData.getConnecttriggerSignatures().isEmpty()) { resultBody.append("("); IntStream.range(0, policyJsonData.getConnecttriggerSignatures().size()) - .mapToObj(i -> connectTriggerSignature(i, policyJsonData.getConnecttriggerSignatures(), - trapSignatureDatas.get(0))).forEach(resultBody::append); + .mapToObj(i -> connectTriggerSignature(i, policyJsonData.getConnecttriggerSignatures(), + trapSignatureDatas.get(0))) + .forEach(resultBody::append); resultBody.append(resultBody).append(")"); } else { if (!trapSignatureDatas.isEmpty()) { @@ -186,8 +186,9 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { if (!policyJsonData.getConnectVerificationSignatures().isEmpty()) { faultBody.append("("); IntStream.range(0, policyJsonData.getConnectVerificationSignatures().size()) - .mapToObj(i -> connectTriggerSignature(i, policyJsonData.getConnectVerificationSignatures(), - faultSignatureDatas.get(0))).forEach(faultBody::append); + .mapToObj(i -> connectTriggerSignature(i, policyJsonData.getConnectVerificationSignatures(), + faultSignatureDatas.get(0))) + .forEach(faultBody::append); faultBody.append(")"); } else { if (!faultSignatureDatas.isEmpty()) { @@ -237,7 +238,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { } private void appendTrapToResultBody(List<Object> triggerSignatures, Object object, StringBuilder resultBody, - Map<String, String> connectTraps, String connectTrapName) { + Map<String, String> connectTraps, String connectTrapName) { String connectTrap = connectTraps.get(connectTrapName); if (connectTrap.startsWith(TRAP) || connectTrap.startsWith(FAULT)) { String trapBody = callTrap(connectTrap, object); @@ -359,8 +360,8 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { private String getVarbindOID(String attrib) { VarbindDictionary varbindId; try { - varbindId = (VarbindDictionary) commonclassdao - .getEntityItem(VarbindDictionary.class, "varbindName", attrib); + varbindId = + (VarbindDictionary) commonclassdao.getEntityItem(VarbindDictionary.class, "varbindName", attrib); return varbindId.getVarbindOID(); } catch (Exception e) { policyLogger.error("Error during retrieving varbindName " + attrib, e); @@ -368,7 +369,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { } } - //connect traps data set to JSON Body as String + // connect traps data set to JSON Body as String @SuppressWarnings({"unchecked", "rawtypes"}) private String getUIConnectTraps(List<Object> connectTrapSignatures) { StringBuilder resultBody = new StringBuilder(); @@ -401,9 +402,8 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { if (((LinkedHashMap) connectTraps).get(TRAP_COUNT_2) != null) { trapCount2 = ((LinkedHashMap) connectTraps).get(TRAP_COUNT_2).toString(); } - connectBody = - notBox + "@!" + connectTrap1 + "@!" + trapCount1 + "@!" + operatorBox + "@!" + connectTrap2 + "@!" - + trapCount2 + "#!?!"; + connectBody = notBox + "@!" + connectTrap1 + "@!" + trapCount1 + "@!" + operatorBox + "@!" + + connectTrap2 + "@!" + trapCount2 + "#!?!"; } resultBody.append(connectBody); } @@ -502,50 +502,48 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { private void setPolicyAdapterMatchAttributes(PolicyRestAdapter policyAdapter, List<AnyOfType> anyOfList) { anyOfList.stream() - //Extract nonNull list of AllOfType objs from each AnyOfType obj - .map(AnyOfType::getAllOf).filter(Objects::nonNull) - .forEach(allOfList -> - //Extract nonNull list of MatchType objs from each AllOFType obj - allOfList.stream().map(AllOfType::getMatch).filter(Objects::nonNull) - .flatMap(Collection::stream) - .forEach(match -> { - // Under the match we have attribute value and - // attributeDesignator. So,finally down to the actual attribute. - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - // First match in the target is OnapName, so set that value. - if ("ONAPName".equals(attributeId)) { - policyAdapter.setOnapName(value); - OnapName onapName = new OnapName(); - onapName.setOnapName(value); - policyAdapter.setOnapNameField(onapName); - } else if ("RiskType".equals(attributeId)) { - policyAdapter.setRiskType(value); - } else if ("RiskLevel".equals(attributeId)) { - policyAdapter.setRiskLevel(value); - } else if ("guard".equals(attributeId)) { - policyAdapter.setGuard(value); - } else if ("TTLDate".equals(attributeId) && !value.contains("NA")) { - PolicyController controller = new PolicyController(); - String newDate = controller.convertDate(value); - policyAdapter.setTtlDate(newDate); - } - })); + // Extract nonNull list of AllOfType objs from each AnyOfType obj + .map(AnyOfType::getAllOf).filter(Objects::nonNull).forEach(allOfList -> + // Extract nonNull list of MatchType objs from each AllOFType obj + allOfList.stream().map(AllOfType::getMatch).filter(Objects::nonNull).flatMap(Collection::stream) + .forEach(match -> { + // Under the match we have attribute value and + // attributeDesignator. So,finally down to the actual attribute. + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + // First match in the target is OnapName, so set that value. + if ("ONAPName".equals(attributeId)) { + policyAdapter.setOnapName(value); + OnapName onapName = new OnapName(); + onapName.setOnapName(value); + policyAdapter.setOnapNameField(onapName); + } else if ("RiskType".equals(attributeId)) { + policyAdapter.setRiskType(value); + } else if ("RiskLevel".equals(attributeId)) { + policyAdapter.setRiskLevel(value); + } else if ("guard".equals(attributeId)) { + policyAdapter.setGuard(value); + } else if ("TTLDate".equals(attributeId) && !value.contains("NA")) { + PolicyController controller = new PolicyController(); + String newDate = controller.convertDate(value); + policyAdapter.setTtlDate(newDate); + } + })); } private void setPolicyAdapterPolicyNameAndDescription(PolicyRestAdapter policyAdapter, PolicyType policy) { policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - String policyNameValue = policyAdapter.getPolicyName() - .substring(policyAdapter.getPolicyName().indexOf("Fault_") + 6); + String policyNameValue = + policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("Fault_") + 6); policyAdapter.setPolicyName(policyNameValue); String description; try { description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); } catch (Exception e) { policyLogger.error( - "Error during collecting the description tag info for createClosedLoopFault " + policyNameValue, e); + "Error during collecting the description tag info for createClosedLoopFault " + policyNameValue, e); description = policy.getDescription(); } policyAdapter.setPolicyDescription(description); @@ -554,8 +552,8 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { private void setClosedLoopJSONFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) { ObjectMapper mapper = new ObjectMapper(); try { - ClosedLoopFaultBody closedLoopBody = mapper - .readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopFaultBody.class); + ClosedLoopFaultBody closedLoopBody = + mapper.readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopFaultBody.class); if ("ACTIVE".equalsIgnoreCase(closedLoopBody.getClosedLoopPolicyStatus())) { closedLoopBody.setClosedLoopPolicyStatus("Active"); } else { @@ -570,7 +568,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { } if (closedLoopBody.getVerificationTimeWindowUsedForUI() != null) { policyAdapter - .setVerificationclearTimeOut(closedLoopBody.getVerificationTimeWindowUsedForUI().toString()); + .setVerificationclearTimeOut(closedLoopBody.getVerificationTimeWindowUsedForUI().toString()); } } catch (Exception e) { policyLogger.error("Exception Occured" + e); @@ -578,6 +576,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { } } + class ClosedLoopGridJSONData { private String clearTimeOut; @@ -610,7 +609,6 @@ class ClosedLoopGridJSONData { this.verificationclearTimeOut = verificationclearTimeOut; } - public List<Object> getConnecttriggerSignatures() { return connecttriggerSignatures; } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java index d2b04e024..4862efd06 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * 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"); @@ -21,23 +21,16 @@ package org.onap.policy.controller; +import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; import java.util.LinkedHashMap; import java.util.List; - import java.util.Objects; + import javax.json.JsonArray; import javax.json.JsonObject; -import org.onap.policy.admin.PolicyManagerServlet; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.rest.adapter.ClosedLoopPMBody; -import org.onap.policy.rest.adapter.PolicyRestAdapter; -import org.onap.policy.rest.jpa.PolicyEntity; - -import com.fasterxml.jackson.databind.ObjectMapper; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; @@ -45,6 +38,13 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import org.onap.policy.admin.PolicyManagerServlet; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.ClosedLoopPMBody; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.PolicyEntity; + public class CreateClosedLoopPMController { private static final Logger LOGGER = FlexLogger.getLogger(CreateClosedLoopPMController.class); @@ -82,8 +82,8 @@ public class CreateClosedLoopPMController { } private void setPolicyAdapterNameValueAndDescription(PolicyRestAdapter policyAdapter, PolicyType policy) { - String policyNameValue = policyAdapter.getPolicyName() - .substring(policyAdapter.getPolicyName().indexOf("PM_") + 3); + String policyNameValue = + policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("PM_") + 3); policyAdapter.setPolicyName(policyNameValue); String description; try { @@ -98,8 +98,8 @@ public class CreateClosedLoopPMController { private void setClosedLoopJSONFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) { ObjectMapper mapper = new ObjectMapper(); try { - ClosedLoopPMBody closedLoopBody = mapper - .readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopPMBody.class); + ClosedLoopPMBody closedLoopBody = + mapper.readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopPMBody.class); policyAdapter.setJsonBodyData(closedLoopBody); } catch (IOException e) { LOGGER.error("Exception Occured" + e); @@ -107,51 +107,50 @@ public class CreateClosedLoopPMController { } private void setPolicyAdapterMatchAttributes(final PolicyRestAdapter policyAdapter, - final List<AnyOfType> anyOfList) { + final List<AnyOfType> anyOfList) { anyOfList.stream() - //Extract nonNull list of AllOfType objs from each AnyOfType obj - .map(AnyOfType::getAllOf).filter(Objects::nonNull) - .forEach(allOfList -> - //Extract nonNull list of MatchType objs from each AllOFType obj + // Extract nonNull list of AllOfType objs from each AnyOfType obj + .map(AnyOfType::getAllOf).filter(Objects::nonNull).forEach(allOfList -> + // Extract nonNull list of MatchType objs from each AllOFType obj allOfList.stream().map(AllOfType::getMatch).filter(Objects::nonNull) - .forEach(matchList -> matchList.forEach(match -> { - // Under the match we have attribute value and - // attributeDesignator. So,finally down to the actual attribute. - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - // First match in the target is OnapName, so set that value. - if ("ONAPName".equals(attributeId)) { - policyAdapter.setOnapName(value); - } else if ("RiskType".equals(attributeId)) { - policyAdapter.setRiskType(value); - } else if ("RiskLevel".equals(attributeId)) { - policyAdapter.setRiskLevel(value); - } else if ("guard".equals(attributeId)) { - policyAdapter.setGuard(value); - } else if ("TTLDate".equals(attributeId) && !value.contains("NA")) { - PolicyController controller = new PolicyController(); - String newDate = controller.convertDate(value); - policyAdapter.setTtlDate(newDate); - } else if ("ServiceType".equals(attributeId)) { - LinkedHashMap<String, String> serviceTypePolicyName1 = new LinkedHashMap<>(); - serviceTypePolicyName1.put(KEY_SERVICE_TYPE_POLICY_NAME, value); - policyAdapter.setServiceTypePolicyName(serviceTypePolicyName1); - LinkedHashMap<String, String> vertica = new LinkedHashMap<>(); - vertica.put("verticaMetrics", getVertica(value)); - policyAdapter.setVerticaMetrics(vertica); - LinkedHashMap<String, String> desc = new LinkedHashMap<>(); - desc.put("policyDescription", getDescription(value)); - policyAdapter.setDescription(desc); - LinkedHashMap<String, Object> attributes = new LinkedHashMap<>(); - attributes.put("attributes", getAttributes(value)); - policyAdapter.setAttributeFields(attributes); - } - }))); + .forEach(matchList -> matchList.forEach(match -> { + // Under the match we have attribute value and + // attributeDesignator. So,finally down to the actual attribute. + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + // First match in the target is OnapName, so set that value. + if ("ONAPName".equals(attributeId)) { + policyAdapter.setOnapName(value); + } else if ("RiskType".equals(attributeId)) { + policyAdapter.setRiskType(value); + } else if ("RiskLevel".equals(attributeId)) { + policyAdapter.setRiskLevel(value); + } else if ("guard".equals(attributeId)) { + policyAdapter.setGuard(value); + } else if ("TTLDate".equals(attributeId) && !value.contains("NA")) { + PolicyController controller = new PolicyController(); + String newDate = controller.convertDate(value); + policyAdapter.setTtlDate(newDate); + } else if ("ServiceType".equals(attributeId)) { + LinkedHashMap<String, String> serviceTypePolicyName1 = new LinkedHashMap<>(); + serviceTypePolicyName1.put(KEY_SERVICE_TYPE_POLICY_NAME, value); + policyAdapter.setServiceTypePolicyName(serviceTypePolicyName1); + LinkedHashMap<String, String> vertica = new LinkedHashMap<>(); + vertica.put("verticaMetrics", getVertica(value)); + policyAdapter.setVerticaMetrics(vertica); + LinkedHashMap<String, String> desc = new LinkedHashMap<>(); + desc.put("policyDescription", getDescription(value)); + policyAdapter.setDescription(desc); + LinkedHashMap<String, Object> attributes = new LinkedHashMap<>(); + attributes.put("attributes", getAttributes(value)); + policyAdapter.setAttributeFields(attributes); + } + }))); } - //get vertica metrics data from the table + // get vertica metrics data from the table private String getVertica(String policyName) { JsonArray data = PolicyManagerServlet.getPolicyNames(); for (int i = 0; i < data.size(); i++) { @@ -162,7 +161,7 @@ public class CreateClosedLoopPMController { return null; } - //get policy description from the table + // get policy description from the table private String getDescription(String policyName) { JsonArray data = PolicyManagerServlet.getPolicyNames(); for (int i = 0; i < data.size(); i++) { @@ -173,7 +172,7 @@ public class CreateClosedLoopPMController { return null; } - //get Attributes + // get Attributes private JsonObject getAttributes(String policyName) { JsonArray data = PolicyManagerServlet.getPolicyNames(); for (int i = 0; i < data.size(); i++) { diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java index a8df74add..f7e5c081f 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java @@ -20,7 +20,6 @@ package org.onap.policy.controller; - import com.att.research.xacml.util.XACMLProperties; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -31,6 +30,7 @@ import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.gson.Gson; + import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; @@ -59,6 +59,7 @@ import java.util.UUID; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; + import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonArrayBuilder; @@ -68,6 +69,7 @@ import javax.json.JsonReader; import javax.json.JsonValue; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; @@ -75,6 +77,7 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + import org.apache.commons.compress.utils.IOUtils; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; @@ -825,7 +828,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { return jsonResult; } - @RequestMapping(value = {"/policyController/getDCAEMSTemplateData.htm"}, + @RequestMapping( + value = {"/policyController/getDCAEMSTemplateData.htm"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST}) public ModelAndView getDCAEMSTemplateData(HttpServletRequest request, HttpServletResponse response) throws IOException { @@ -1042,7 +1046,6 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { return object; } - public JSONObject convertToArrayElement(JSONObject json, String keyValue) { return convertToArrayElement(json, new HashSet<>(), keyValue); } @@ -1135,8 +1138,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { return keys; } - - @RequestMapping(value = {"/policyController/getModelServiceVersioneData.htm"}, + @RequestMapping( + value = {"/policyController/getModelServiceVersioneData.htm"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST}) public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response) throws IOException { @@ -1201,7 +1204,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { modelName); } - @RequestMapping(value = {"/get_DCAEPriorityValues"}, + @RequestMapping( + value = {"/get_DCAEPriorityValues"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response) { @@ -1321,7 +1325,6 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { return map; } - /** * Read file. * @@ -1448,7 +1451,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { return attribute; } - @RequestMapping(value = {"/ms_dictionary/set_MSModelData"}, + @RequestMapping( + value = {"/ms_dictionary/set_MSModelData"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST}) public void SetMSModelData(HttpServletRequest request, HttpServletResponse response) throws IOException, FileUploadException { @@ -1800,7 +1804,6 @@ class DCAEMicroServiceObject { private Object content; - public String getPolicyName() { return policyName; } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java index 3e24dc7c4..8aad4216d 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,14 @@ */ package org.onap.policy.controller; + +import com.fasterxml.jackson.core.JsonGenerationException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; + import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; @@ -32,6 +40,14 @@ import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + import org.hibernate.SessionFactory; import org.json.JSONObject; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -69,886 +85,860 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.core.JsonGenerationException; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectWriter; - -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; - @Controller @RequestMapping("/") public class CreateFirewallController extends RestrictedBaseController { - private static Logger policyLogger = FlexLogger.getLogger(CreateFirewallController.class); - private static final String ANY="ANY"; - private static final String GROUP="Group_"; - - @Autowired - SessionFactory sessionFactory; - - private static CommonClassDao commonClassDao; - - public static CommonClassDao getCommonClassDao() { - return commonClassDao; - } - - public static void setCommonClassDao(CommonClassDao commonClassDao) { - CreateFirewallController.commonClassDao = commonClassDao; - } - - private List<String> tagCollectorList; - - List<String> expandablePrefixIPList = new ArrayList<>(); - List<String> expandableServicesList= new ArrayList<>(); - @Autowired - private CreateFirewallController(CommonClassDao commonClassDao){ - CreateFirewallController.commonClassDao = commonClassDao; - } - - public CreateFirewallController(){ - // Empty constructor - } - private List<String> termCollectorList; - - - - public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData){ - String jsonBody; - termCollectorList = new ArrayList <>(); - tagCollectorList = new ArrayList <>(); - if(! policyData.getAttributes().isEmpty()){ - for(Object attribute : policyData.getAttributes()){ - if(attribute instanceof LinkedHashMap<?, ?>){ - String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString(); - termCollectorList.add(key); - - String tag = ((LinkedHashMap<?, ?>) attribute).get("value").toString(); - tagCollectorList.add(tag); - } - } - } - jsonBody = constructJson(policyData); - if (jsonBody != null && ! "".equalsIgnoreCase(jsonBody)) { - policyData.setJsonBody(jsonBody); - } else { - policyData.setJsonBody("{}"); - } - policyData.setJsonBody(jsonBody); - - return policyData; - } - - private List<String> mapping(String expandableList) { - String value; - String desc; - List <String> valueDesc= new ArrayList<>(); - List<Object> prefixListData = commonClassDao.getData(PrefixList.class); - for (int i = 0; i< prefixListData.size(); i++) { - PrefixList prefixList = (PrefixList) prefixListData.get(i); - if (prefixList.getPrefixListName().equals(expandableList)) { - value = prefixList.getPrefixListValue(); - valueDesc.add(value); - desc= prefixList.getDescription(); - valueDesc.add(desc); - break; - } - } - return valueDesc; - } - - private ServiceList mappingServiceList(String expandableList) { - ServiceList serviceList=null; - List<Object> serviceListData = commonClassDao.getData(ServiceList.class); - for (int i = 0; i< serviceListData.size(); i++) { - serviceList = (ServiceList) serviceListData.get(i); - if (serviceList.getServiceName().equals(expandableList)) { - break; - } - } - return serviceList; - } - - private GroupServiceList mappingServiceGroup(String expandableList) { - - GroupServiceList serviceGroup=null; - List<Object> serviceGroupData = commonClassDao.getData(GroupServiceList.class); - for (int i = 0; i< serviceGroupData.size(); i++) { - serviceGroup = (GroupServiceList) serviceGroupData.get(i); - if (serviceGroup.getGroupName().equals(expandableList)) { - break; - } - } - return serviceGroup; - } - - private AddressGroup mappingAddressGroup(String expandableList) { - - AddressGroup addressGroup=null; - List<Object> addressGroupData = commonClassDao.getData(AddressGroup.class); - for (int i = 0; i< addressGroupData.size(); i++) { - addressGroup = (AddressGroup) addressGroupData.get(i); - if (addressGroup.getGroupName().equals(expandableList)) { - break; - } - } - return addressGroup; - } - - public void prePopulateFWPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - ArrayList<Object> attributeList; - attributeList = new ArrayList<>(); - if (policyAdapter.getPolicyData() instanceof PolicyType) { - Object policyData = policyAdapter.getPolicyData(); - PolicyType policy = (PolicyType) policyData; - // policy name value is the policy name without any prefix and Extensions. - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("FW_") +3); - if (policyLogger.isDebugEnabled()) { - policyLogger.debug("Prepopulating form data for Config Policy selected:"+ policyAdapter.getPolicyName()); - } - policyAdapter.setPolicyName(policyNameValue); - String description = ""; - try{ - description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); - }catch(Exception e){ - policyLogger.info("General error", e); - description = policy.getDescription(); - } - policyAdapter.setPolicyDescription(description); - - ObjectMapper mapper = new ObjectMapper(); - - TermCollector tc1=null; - try { - //Json conversion. - String data; - SecurityZone jpaSecurityZone; - data = entity.getConfigurationData().getConfigBody(); - tc1 = mapper.readValue(data, TermCollector.class); - List<Object> securityZoneData = commonClassDao.getData(SecurityZone.class); - for (int i = 0; i < securityZoneData.size() ; i++) { - jpaSecurityZone = (SecurityZone) securityZoneData.get(i); - if (jpaSecurityZone.getZoneValue().equals(tc1.getSecurityZoneId())){ - policyAdapter.setSecurityZone(jpaSecurityZone.getZoneName()); - break; - } - } - } - catch(Exception e) { - policyLogger.error("Exception Caused while Retriving the JSON body data" +e); - } - - Map<String, String> termTagMap; - if(tc1 != null){ - for(int i=0;i<tc1.getFirewallRuleList().size();i++){ - termTagMap = new HashMap <>(); - String ruleName= tc1.getFirewallRuleList().get(i).getRuleName(); - String tagPickerName=tc1.getRuleToTag().get(i).getTagPickerName(); - termTagMap.put("key", ruleName); - termTagMap.put("value", tagPickerName); - attributeList.add(termTagMap); - } - } - policyAdapter.setAttributes(attributeList); - // Get the target data under policy. - 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 AnyOFType we have AllOFType - List<AllOfType> allOfList = anyOf.getAllOf(); - if (allOfList != null) { - Iterator<AllOfType> iterAllOf = allOfList.iterator(); - while (iterAllOf.hasNext()) { - AllOfType allOf = iterAllOf.next(); - // Under AllOFType we have Match - List<MatchType> matchList = allOf.getMatch(); - if (matchList != null) { - - Iterator<MatchType> iterMatch = matchList.iterator(); - while (iterMatch.hasNext()) { - MatchType match = iterMatch.next(); - // - // Under the match we have attribute value and - // attributeDesignator. So,finally down to the actual attribute. - // - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - if (("ConfigName").equals(attributeId)) { - policyAdapter.setConfigName(value); - } - if (("RiskType").equals(attributeId)){ - policyAdapter.setRiskType(value); - } - if (("RiskLevel").equals(attributeId)){ - policyAdapter.setRiskLevel(value); - } - if (("guard").equals(attributeId)){ - policyAdapter.setGuard(value); - } - if ("TTLDate".equals(attributeId) && !value.contains("NA")){ - PolicyController controller = new PolicyController(); - String newDate = controller.convertDate(value); - policyAdapter.setTtlDate(newDate); - } - } - } - } - } - } - } - } - } - } - - @RequestMapping(value={"/policyController/ViewFWPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView setFWViewRule(HttpServletRequest request, HttpServletResponse response){ - try { - termCollectorList = new ArrayList<>(); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - PolicyRestAdapter policyData = mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.class); - if(! policyData.getAttributes().isEmpty()){ - for(Object attribute : policyData.getAttributes()){ - if(attribute instanceof LinkedHashMap<?, ?>){ - String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString(); - termCollectorList.add(key); - } - } - } - TermList jpaTermList; - String ruleSrcList; - String ruleDestList; - String ruleSrcPort; - String ruleDestPort; - String ruleAction; - List <String> valueDesc; - StringBuilder displayString = new StringBuilder(); - for (String id : termCollectorList) { - List<Object> tmList = commonClassDao.getDataById(TermList.class, "termName", id); - jpaTermList = (TermList) tmList.get(0); - if (jpaTermList != null){ - ruleSrcList= jpaTermList.getSrcIPList(); - if ((ruleSrcList!= null) && (!ruleSrcList.isEmpty()) && !"null".equals(ruleSrcList)){ - displayString.append("Source IP List: " + jpaTermList.getSrcIPList()); - displayString.append(" ; \t\n"); - for(String srcList:ruleSrcList.split(",")){ - if(srcList.startsWith(GROUP)){ - AddressGroup ag; - ag= mappingAddressGroup(srcList); - displayString.append("\n\t"+"Group has :"+(ag != null ? ag.getPrefixList() : "") +"\n"); - if (ag != null) { - for(String groupItems:ag.getPrefixList().split(",")){ - valueDesc=mapping(groupItems); - displayString.append("\n\t"+"Name: "+groupItems); - if(!valueDesc.isEmpty()){ - displayString.append("\n\t"+"Description: "+valueDesc.get(1)); - displayString.append("\n\t"+"Value: "+valueDesc.get(0)); - } - displayString.append("\n"); - } - } - }else{ - if(!srcList.equals(ANY)){ - valueDesc=mapping(srcList); - displayString.append("\n\t"+"Name: "+srcList); - displayString.append("\n\t"+"Description: "+valueDesc.get(1)); - displayString.append("\n\t"+"Value: "+valueDesc.get(0)); - displayString.append("\n"); - } - } - } - displayString.append("\n"); - } - ruleDestList= jpaTermList.getDestIPList(); - if ( ruleDestList!= null && (!ruleDestList.isEmpty())&& ! "null".equals(ruleDestList)){ - displayString.append("Destination IP List: " + jpaTermList.getDestIPList()); - displayString.append(" ; \t\n"); - for(String destList:ruleDestList.split(",")){ - if(destList.startsWith(GROUP)){ - AddressGroup ag; - ag= mappingAddressGroup(destList); - displayString.append("\n\t"+"Group has :"+ (ag != null ? ag.getPrefixList() : "") +"\n"); - if (ag != null) { - for(String groupItems:ag.getPrefixList().split(",")){ - valueDesc=mapping(groupItems); - displayString.append("\n\t"+"Name: "+groupItems); - displayString.append("\n\t"+"Description: "+valueDesc.get(1)); - displayString.append("\n\t"+"Value: "+valueDesc.get(0)); - displayString.append("\n\t"); - } - } - }else{ - if(!destList.equals(ANY)){ - valueDesc=mapping(destList); - displayString.append("\n\t"+"Name: "+destList); - displayString.append("\n\t"+"Description: "+valueDesc.get(1)); - displayString.append("\n\t"+"Value: "+valueDesc.get(0)); - displayString.append("\n\t"); - } - } - } - displayString.append("\n"); - } - - ruleSrcPort=jpaTermList.getSrcPortList(); - if ( ruleSrcPort!= null && (!ruleSrcPort.isEmpty())&& !"null".equals(ruleSrcPort)) { - displayString.append("\n"+"Source Port List:" - + ruleSrcPort); - displayString.append(" ; \t\n"); - } - - ruleDestPort= jpaTermList.getDestPortList(); - if (ruleDestPort != null && (!ruleDestPort.isEmpty())&& !"null".equals(ruleDestPort)) { - displayString.append("\n"+"Destination Port List:" - + ruleDestPort); - displayString.append(" ; \t\n"); - for(String destServices:ruleDestPort.split(",")){ - if(destServices.startsWith(GROUP)){ - GroupServiceList sg; - sg= mappingServiceGroup(destServices); - displayString.append("\n\t"+"Service Group has :"+ (sg != null ? sg.getServiceList() : "") +"\n"); - if (sg != null) { - for(String groupItems:sg.getServiceList().split(",")){ - ServiceList sl; - sl= mappingServiceList(groupItems); - displayString.append("\n\t"+"Name: "+ - sl.getServiceName()); - displayString.append("\n\t"+"Description: "+ - sl.getServiceDescription()); - displayString.append("\n\t"+"Transport-Protocol: "+ - sl.getServiceTransProtocol()); - displayString.append("\n\t"+"Ports: "+ - sl.getServicePorts()); - displayString.append("\n"); - } - } - } - else{ - if(!destServices.equals(ANY)){ - ServiceList sl; - sl= mappingServiceList(destServices); - displayString.append("\n\t"+"Name: "+ - sl.getServiceName()); - displayString.append("\n\t"+"Description: "+ - sl.getServiceDescription()); - displayString.append("\n\t"+"Transport-Protocol: "+ - sl.getServiceTransProtocol()); - displayString.append("\n\t"+"Ports: "+ - sl.getServicePorts()); - displayString.append("\n"); - } - } - } - displayString.append("\n"); - } - - ruleAction=(jpaTermList).getAction(); - if ( ruleAction!= null && (!ruleAction.isEmpty())) { - displayString.append("\n"+"Action List:" - + ruleAction); - displayString.append(" ; \t\n"); - } - } - } - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(displayString); - JSONObject j = new JSONObject("{policyData: " + responseString + "}"); - out.write(j.toString()); - return null; - } catch (Exception e) { - policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - return null; - } - - private String constructJson(PolicyRestAdapter policyData) { - int ruleCount=1; - //Maps to assosciate the values read from the TermList dictionary - Map<Integer, String> srcIP_map =null; - Map<Integer, String> destIP_map=null; - Map<Integer, String> srcPort_map =null; - Map<Integer, String> destPort_map =null; - Map<Integer, String> action_map=null; - Map<Integer, String> fromZone_map=null; - Map<Integer, String> toZone_map=null; - - String ruleDesc=null; - String ruleFromZone=null; - String ruleToZone=null; - String ruleSrcPrefixList=null; - String ruleDestPrefixList=null; - String ruleSrcPort=null; - String ruleDestPort=null; - String ruleAction=null; - - String json = null; - - - List<String> expandableList = new ArrayList<>(); - TermList jpaTermList; - TermCollector tc = new TermCollector(); - SecurityZone jpaSecurityZone; - List<Term> termList = new ArrayList<>(); - - Tags tags=null; - List<Tags>tagsList= new ArrayList<>(); - - TagDefines tagDefine= new TagDefines(); - List<TagDefines> tagList=null; - ServiceListJson targetSl=null; - AddressMembers addressMembersJson=null; - int i=0; - try{ - String networkRole=""; - for(String tag:tagCollectorList){ - tags= new Tags(); - List<Object> tagListData = commonClassDao.getData(FWTagPicker.class); - for(int tagCounter=0; tagCounter<tagListData.size(); tagCounter++){ - FWTagPicker jpaTagPickerList=(FWTagPicker) tagListData.get(tagCounter); - if (jpaTagPickerList.getTagPickerName().equals(tag) ){ - String tagValues=jpaTagPickerList.getTagValues(); - tagList= new ArrayList<>(); - for(String val:tagValues.split("#")) { - int index=val.indexOf(':'); - String keyToStore=val.substring(0,index); - String valueToStore=val.substring(index+1,val.length()); - - tagDefine= new TagDefines(); - tagDefine.setKey(keyToStore); - tagDefine.setValue(valueToStore); - //Add to the collection. - tagList.add(tagDefine); - - } - networkRole=jpaTagPickerList.getNetworkRole(); - break; - } - } - tags.setTags(tagList); - tags.setTagPickerName(tag); - tags.setRuleName(termCollectorList.get(i)); - tags.setNetworkRole(networkRole); - tagsList.add(tags); - i++; - } - tc.setRuleToTag(tagsList); - - for (int tl = 0 ; tl< termCollectorList.size(); tl++) { - expandableList.add(termCollectorList.get(tl)); - Term targetTerm = new Term(); - targetTerm.setRuleName(termCollectorList.get(tl)); - List<Object> termListData = commonClassDao.getData(TermList.class); - for (int j =0; j < termListData.size(); j++) { - jpaTermList = (TermList) termListData.get(j); - if (jpaTermList.getTermName().equals(termCollectorList.get(tl))){ - ruleDesc=jpaTermList.getTermDescription(); - if ((ruleDesc!=null)&& (!ruleDesc.isEmpty())){ - targetTerm.setDescription(ruleDesc); - } - ruleFromZone=jpaTermList.getFromZone(); - - if ((ruleFromZone != null) && (!ruleFromZone.isEmpty())){ - fromZone_map = new HashMap<>(); - fromZone_map.put(tl, ruleFromZone); - } - ruleToZone=jpaTermList.getToZone(); - - if ((ruleToZone != null) && (!ruleToZone.isEmpty())){ - toZone_map = new HashMap<>(); - toZone_map.put(tl, ruleToZone); - } - ruleSrcPrefixList=jpaTermList.getSrcIPList(); - - if ((ruleSrcPrefixList != null) && (!ruleSrcPrefixList.isEmpty())){ - srcIP_map = new HashMap<>(); - srcIP_map.put(tl, ruleSrcPrefixList); - } - - ruleDestPrefixList= jpaTermList.getDestIPList(); - if ((ruleDestPrefixList != null) && (!ruleDestPrefixList.isEmpty())){ - destIP_map = new HashMap<>(); - destIP_map.put(tl, ruleDestPrefixList); - } - - ruleSrcPort=jpaTermList.getSrcPortList(); - - if (ruleSrcPort != null && (!ruleSrcPort.isEmpty())){ - srcPort_map = new HashMap<>(); - srcPort_map.put(tl, ruleSrcPort); - } - - ruleDestPort= jpaTermList.getDestPortList(); - - if (ruleDestPort!= null && (!jpaTermList.getDestPortList().isEmpty())){ - destPort_map = new HashMap<>(); - destPort_map.put(tl, ruleDestPort); - } - - ruleAction=jpaTermList.getAction(); - - if (( ruleAction!= null) && (!ruleAction.isEmpty())){ - action_map = new HashMap<>(); - action_map.put(tl, ruleAction); - } - } - } - targetTerm.setEnabled(true); - targetTerm.setLog(true); - targetTerm.setNegateSource(false); - targetTerm.setNegateDestination(false); - - if(action_map!=null){ - targetTerm.setAction(action_map.get(tl)); - } - - //FromZone arrays - if(fromZone_map!=null){ - List<String> fromZone= new ArrayList<>(); - for(String fromZoneStr:fromZone_map.get(tl).split(",") ){ - fromZone.add(fromZoneStr); - } - targetTerm.setFromZones(fromZone); - } - - //ToZone arrays - if(toZone_map!=null){ - List<String> toZone= new ArrayList<>(); - for(String toZoneStr:toZone_map.get(tl).split(",") ){ - toZone.add(toZoneStr); - } - targetTerm.setToZones(toZone); - } - - //Destination Services. - if(destPort_map!=null){ - Set<ServicesJson> destServicesJsonList= new HashSet<>(); - for(String destServices:destPort_map.get(tl).split(",") ){ - ServicesJson destServicesJson= new ServicesJson(); - destServicesJson.setType("REFERENCE"); - if(destServices.equals(ANY)){ - destServicesJson.setName("any"); - destServicesJsonList.add(destServicesJson); - break; - }else{ - if(destServices.startsWith(GROUP)){ - destServicesJson.setName(destServices.substring(6,destServices.length())); - } else{ - destServicesJson.setName(destServices); - } - destServicesJsonList.add(destServicesJson); - } - } - targetTerm.setDestServices(destServicesJsonList); - } - //ExpandableServicesList - if((srcPort_map!=null) && (destPort_map!=null)){ - String servicesCollateString = srcPort_map.get(tl) + "," + destPort_map.get(tl); - expandableServicesList.add(servicesCollateString); - }else if (srcPort_map!=null){ - expandableServicesList.add(srcPort_map.get(tl)); - }else if (destPort_map!=null){ - expandableServicesList.add(destPort_map.get(tl)); - } - - if(srcIP_map!=null){ - //Source List - List<AddressJson> sourceListArrayJson= new ArrayList<>(); - for(String srcList:srcIP_map.get(tl).split(",") ){ - AddressJson srcListJson= new AddressJson(); - if(srcList.equals(ANY)){ - srcListJson.setType("any"); - sourceListArrayJson.add(srcListJson); - break; - }else{ - srcListJson.setType("REFERENCE"); - if(srcList.startsWith(GROUP)){ - srcListJson.setName(srcList.substring(6,srcList.length())); - }else{ - srcListJson.setName(srcList); - } - sourceListArrayJson.add(srcListJson); - } - } - targetTerm.setSourceList(sourceListArrayJson); - } - if(destIP_map!=null){ - //Destination List - List<AddressJson> destListArrayJson= new ArrayList<>(); - for(String destList:destIP_map.get(tl).split(",")){ - AddressJson destListJson= new AddressJson(); - if(destList.equals(ANY)){ - destListJson.setType("any"); - destListArrayJson.add(destListJson); - break; - }else{ - destListJson.setType("REFERENCE"); - if(destList.startsWith(GROUP)){ - destListJson.setName(destList.substring(6,destList.length())); - }else{ - destListJson.setName(destList); - } - destListArrayJson.add(destListJson); - } - } - targetTerm.setDestinationList(destListArrayJson); - } - //ExpandablePrefixIPList - if ((srcIP_map!=null) && (destIP_map!=null)) - { - String collateString = srcIP_map.get(tl) + "," + destIP_map - .get(tl); - expandablePrefixIPList.add(collateString); - } - else if(srcIP_map!=null){ - expandablePrefixIPList.add(srcIP_map.get(tl)); - } - else if(destIP_map!=null){ - expandablePrefixIPList.add(destIP_map.get(tl)); - } - termList.add(targetTerm); - targetTerm.setPosition(Integer.toString (ruleCount++)); - } - - List<Object> securityZoneData = commonClassDao.getData(SecurityZone.class); - for (int j =0 ; j< securityZoneData.size() ; j++){ - jpaSecurityZone = (SecurityZone) securityZoneData.get(j); - if (jpaSecurityZone.getZoneName().equals(policyData.getSecurityZone())){ - tc.setSecurityZoneId(jpaSecurityZone.getZoneValue()); - IdMap idMapInstance= new IdMap(); - idMapInstance.setAstraId(jpaSecurityZone.getZoneValue()); - idMapInstance.setVendorId("deviceGroup:dev"); - - List<IdMap> idMap = new ArrayList <>(); - idMap.add(idMapInstance); - - VendorSpecificData vendorStructure= new VendorSpecificData(); - vendorStructure.setIdMap(idMap); - tc.setVendorSpecificData(vendorStructure); - break; - } - } - - tc.setServiceTypeId("/v0/firewall/pan"); - tc.setConfigName(policyData.getConfigName()); - tc.setVendorServiceId("vipr"); - - DeployNowJson deployNow= new DeployNowJson(); - deployNow.setDeployNow(false); - - tc.setDeploymentOption(deployNow); - - Set<ServiceListJson> servListArray = new HashSet<>(); - Set<ServiceGroupJson> servGroupArray= new HashSet<>(); - Set<AddressGroupJson> addrGroupArray= new HashSet<>(); - Set<AddressMembers> addrArray= new HashSet<> (); - - ServiceGroupJson targetSg; - AddressGroupJson addressSg; - ServiceListJson targetAny; - ServiceListJson targetAnyTcp; - ServiceListJson targetAnyUdp; - - for(String serviceList:expandableServicesList){ - for(String t: serviceList.split(",")){ - if(!t.startsWith(GROUP)){ - if(!t.equals(ANY)){ - ServiceList sl; - targetSl= new ServiceListJson(); - sl= mappingServiceList(t); - targetSl.setName(sl.getServiceName()); - targetSl.setDescription(sl.getServiceDescription()); - targetSl.setTransportProtocol(sl.getServiceTransProtocol()); - targetSl.setType(sl.getServiceType()); - targetSl.setPorts(sl.getServicePorts()); - servListArray.add(targetSl); - }else{ - //Any for destinationServices. - //Add names any, any-tcp, any-udp to the serviceGroup object. - targetAny= new ServiceListJson(); - targetAny.setName("any"); - targetAny.setType("SERVICE"); - targetAny.setTransportProtocol("any"); - targetAny.setPorts("any"); - - servListArray.add(targetAny); - - targetAnyTcp= new ServiceListJson(); - targetAnyTcp.setName("any-tcp"); - targetAnyTcp.setType("SERVICE"); - targetAnyTcp.setTransportProtocol("tcp"); - targetAnyTcp.setPorts("any"); - - servListArray.add(targetAnyTcp); - - targetAnyUdp= new ServiceListJson(); - targetAnyUdp.setName("any-udp"); - targetAnyUdp.setType("SERVICE"); - targetAnyUdp.setTransportProtocol("udp"); - targetAnyUdp.setPorts("any"); - - servListArray.add(targetAnyUdp); - } - }else{//This is a group - GroupServiceList sg; - targetSg= new ServiceGroupJson(); - sg= mappingServiceGroup(t); - - String name=sg.getGroupName(); - //Removing the "Group_" prepending string before packing the JSON - targetSg.setName(name.substring(6,name.length())); - List<ServiceMembers> servMembersList= new ArrayList<>(); - - for(String groupString: sg.getServiceList().split(",")){ - ServiceMembers serviceMembers= new ServiceMembers(); - serviceMembers.setType("REFERENCE"); - serviceMembers.setName(groupString); - servMembersList.add(serviceMembers); - //Expand the group Name - ServiceList expandGroupSl ; - targetSl= new ServiceListJson(); - expandGroupSl= mappingServiceList(groupString); - - targetSl.setName(expandGroupSl.getServiceName()); - targetSl.setDescription(expandGroupSl.getServiceDescription()); - targetSl.setTransportProtocol(expandGroupSl.getServiceTransProtocol()); - targetSl.setType(expandGroupSl.getServiceType()); - targetSl.setPorts(expandGroupSl.getServicePorts()); - servListArray.add(targetSl); - } - - targetSg.setMembers(servMembersList); - servGroupArray.add(targetSg); - - } - } - } - - Set<PrefixIPList> prefixIPList = new HashSet<>(); - for(String prefixList:expandablePrefixIPList){ - for(String prefixIP: prefixList.split(",")){ - if(!prefixIP.startsWith(GROUP)){ - if(!prefixIP.equals(ANY)){ - List<AddressMembers> addMembersList= new ArrayList<>(); - List<String> valueDesc; - PrefixIPList targetAddressList = new PrefixIPList(); - AddressMembers addressMembers= new AddressMembers(); - targetAddressList.setName(prefixIP); - policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "PrefixList value:"+prefixIP); - valueDesc = mapping(prefixIP); - if(!valueDesc.isEmpty()){ - policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "PrefixList description:"+valueDesc.get(1)); - targetAddressList.setDescription(valueDesc.get(1)); - } - - - addressMembers.setType("SUBNET"); - if(!valueDesc.isEmpty()) { - addressMembers.setValue(valueDesc.get(0)); - } - - addMembersList.add(addressMembers); - - targetAddressList.setMembers(addMembersList); - prefixIPList.add(targetAddressList); - } - } - else{//This is a group - AddressGroup ag; - addressSg= new AddressGroupJson(); - ag= mappingAddressGroup(prefixIP); - - String name=ag.getGroupName(); - //Removing the "Group_" prepending string before packing the JSON - addressSg.setName(name.substring(6,name.length())); - - List<AddressMembersJson> addrMembersList= new ArrayList<>(); - for(String groupString: ag.getPrefixList().split(",")){ - List<String> valueDesc; - AddressMembersJson addressMembers= new AddressMembersJson(); - addressMembers.setType("REFERENCES"); - addressMembers.setName(groupString); - addrMembersList.add(addressMembers); - //Expand the group Name - addressMembersJson= new AddressMembers(); - valueDesc= mapping (groupString); - - addressMembersJson.setName(groupString); - addressMembersJson.setType("SUBNET"); - addressMembersJson.setValue(valueDesc.get(0)); - - addrArray.add(addressMembersJson); - - } - addressSg.setMembers(addrMembersList); - addrGroupArray.add(addressSg); - } - - } - } - - Set<Object> serviceGroup= new HashSet<>(); - - for(Object obj1:servGroupArray){ - serviceGroup.add(obj1); - } - - for(Object obj:servListArray){ - serviceGroup.add(obj); - } - - Set<Object> addressGroup= new HashSet<>(); - - for(Object addObj:prefixIPList){ - addressGroup.add(addObj); - } - - for(Object addObj1:addrGroupArray){ - addressGroup.add(addObj1); - } - - for(Object addObj2:addrArray){ - addressGroup.add(addObj2); - } - - - tc.setServiceGroups(serviceGroup); - tc.setAddressGroups(addressGroup); - tc.setFirewallRuleList(termList); - - ObjectWriter om = new ObjectMapper().writer(); - try { - json = om.writeValueAsString(tc); - } catch (JsonGenerationException e) { - policyLogger.error("JsonGenerationException Ocured",e); - } catch (JsonMappingException e) { - policyLogger.error("IOException Occured",e); - } - - }catch (Exception e) { - policyLogger.error("Exception Occured"+e); - } - - return json; - } + private static Logger policyLogger = FlexLogger.getLogger(CreateFirewallController.class); + private static final String ANY = "ANY"; + private static final String GROUP = "Group_"; + + @Autowired + SessionFactory sessionFactory; + + private static CommonClassDao commonClassDao; + + public static CommonClassDao getCommonClassDao() { + return commonClassDao; + } + + public static void setCommonClassDao(CommonClassDao commonClassDao) { + CreateFirewallController.commonClassDao = commonClassDao; + } + + private List<String> tagCollectorList; + + List<String> expandablePrefixIPList = new ArrayList<>(); + List<String> expandableServicesList = new ArrayList<>(); + + @Autowired + private CreateFirewallController(CommonClassDao commonClassDao) { + CreateFirewallController.commonClassDao = commonClassDao; + } + + public CreateFirewallController() { + // Empty constructor + } + + private List<String> termCollectorList; + + public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData) { + String jsonBody; + termCollectorList = new ArrayList<>(); + tagCollectorList = new ArrayList<>(); + if (!policyData.getAttributes().isEmpty()) { + for (Object attribute : policyData.getAttributes()) { + if (attribute instanceof LinkedHashMap<?, ?>) { + String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString(); + termCollectorList.add(key); + + String tag = ((LinkedHashMap<?, ?>) attribute).get("value").toString(); + tagCollectorList.add(tag); + } + } + } + jsonBody = constructJson(policyData); + if (jsonBody != null && !"".equalsIgnoreCase(jsonBody)) { + policyData.setJsonBody(jsonBody); + } else { + policyData.setJsonBody("{}"); + } + policyData.setJsonBody(jsonBody); + + return policyData; + } + + private List<String> mapping(String expandableList) { + String value; + String desc; + List<String> valueDesc = new ArrayList<>(); + List<Object> prefixListData = commonClassDao.getData(PrefixList.class); + for (int i = 0; i < prefixListData.size(); i++) { + PrefixList prefixList = (PrefixList) prefixListData.get(i); + if (prefixList.getPrefixListName().equals(expandableList)) { + value = prefixList.getPrefixListValue(); + valueDesc.add(value); + desc = prefixList.getDescription(); + valueDesc.add(desc); + break; + } + } + return valueDesc; + } + + private ServiceList mappingServiceList(String expandableList) { + ServiceList serviceList = null; + List<Object> serviceListData = commonClassDao.getData(ServiceList.class); + for (int i = 0; i < serviceListData.size(); i++) { + serviceList = (ServiceList) serviceListData.get(i); + if (serviceList.getServiceName().equals(expandableList)) { + break; + } + } + return serviceList; + } + + private GroupServiceList mappingServiceGroup(String expandableList) { + + GroupServiceList serviceGroup = null; + List<Object> serviceGroupData = commonClassDao.getData(GroupServiceList.class); + for (int i = 0; i < serviceGroupData.size(); i++) { + serviceGroup = (GroupServiceList) serviceGroupData.get(i); + if (serviceGroup.getGroupName().equals(expandableList)) { + break; + } + } + return serviceGroup; + } + + private AddressGroup mappingAddressGroup(String expandableList) { + + AddressGroup addressGroup = null; + List<Object> addressGroupData = commonClassDao.getData(AddressGroup.class); + for (int i = 0; i < addressGroupData.size(); i++) { + addressGroup = (AddressGroup) addressGroupData.get(i); + if (addressGroup.getGroupName().equals(expandableList)) { + break; + } + } + return addressGroup; + } + + public void prePopulateFWPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + ArrayList<Object> attributeList; + attributeList = new ArrayList<>(); + if (policyAdapter.getPolicyData() instanceof PolicyType) { + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + // policy name value is the policy name without any prefix and Extensions. + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = + policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("FW_") + 3); + if (policyLogger.isDebugEnabled()) { + policyLogger + .debug("Prepopulating form data for Config Policy selected:" + policyAdapter.getPolicyName()); + } + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try { + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + } catch (Exception e) { + policyLogger.info("General error", e); + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + + ObjectMapper mapper = new ObjectMapper(); + + TermCollector tc1 = null; + try { + // Json conversion. + String data; + SecurityZone jpaSecurityZone; + data = entity.getConfigurationData().getConfigBody(); + tc1 = mapper.readValue(data, TermCollector.class); + List<Object> securityZoneData = commonClassDao.getData(SecurityZone.class); + for (int i = 0; i < securityZoneData.size(); i++) { + jpaSecurityZone = (SecurityZone) securityZoneData.get(i); + if (jpaSecurityZone.getZoneValue().equals(tc1.getSecurityZoneId())) { + policyAdapter.setSecurityZone(jpaSecurityZone.getZoneName()); + break; + } + } + } catch (Exception e) { + policyLogger.error("Exception Caused while Retriving the JSON body data" + e); + } + + Map<String, String> termTagMap; + if (tc1 != null) { + for (int i = 0; i < tc1.getFirewallRuleList().size(); i++) { + termTagMap = new HashMap<>(); + String ruleName = tc1.getFirewallRuleList().get(i).getRuleName(); + String tagPickerName = tc1.getRuleToTag().get(i).getTagPickerName(); + termTagMap.put("key", ruleName); + termTagMap.put("value", tagPickerName); + attributeList.add(termTagMap); + } + } + policyAdapter.setAttributes(attributeList); + // Get the target data under policy. + 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 AnyOFType we have AllOFType + List<AllOfType> allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator<AllOfType> iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOFType we have Match + List<MatchType> matchList = allOf.getMatch(); + if (matchList != null) { + + Iterator<MatchType> iterMatch = matchList.iterator(); + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attribute value and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + if (("ConfigName").equals(attributeId)) { + policyAdapter.setConfigName(value); + } + if (("RiskType").equals(attributeId)) { + policyAdapter.setRiskType(value); + } + if (("RiskLevel").equals(attributeId)) { + policyAdapter.setRiskLevel(value); + } + if (("guard").equals(attributeId)) { + policyAdapter.setGuard(value); + } + if ("TTLDate".equals(attributeId) && !value.contains("NA")) { + PolicyController controller = new PolicyController(); + String newDate = controller.convertDate(value); + policyAdapter.setTtlDate(newDate); + } + } + } + } + } + } + } + } + } + } + + @RequestMapping( + value = {"/policyController/ViewFWPolicyRule.htm"}, + method = {org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView setFWViewRule(HttpServletRequest request, HttpServletResponse response) { + try { + termCollectorList = new ArrayList<>(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyRestAdapter policyData = mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.class); + if (!policyData.getAttributes().isEmpty()) { + for (Object attribute : policyData.getAttributes()) { + if (attribute instanceof LinkedHashMap<?, ?>) { + String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString(); + termCollectorList.add(key); + } + } + } + TermList jpaTermList; + String ruleSrcList; + String ruleDestList; + String ruleSrcPort; + String ruleDestPort; + String ruleAction; + List<String> valueDesc; + StringBuilder displayString = new StringBuilder(); + for (String id : termCollectorList) { + List<Object> tmList = commonClassDao.getDataById(TermList.class, "termName", id); + jpaTermList = (TermList) tmList.get(0); + if (jpaTermList != null) { + ruleSrcList = jpaTermList.getSrcIPList(); + if ((ruleSrcList != null) && (!ruleSrcList.isEmpty()) && !"null".equals(ruleSrcList)) { + displayString.append("Source IP List: " + jpaTermList.getSrcIPList()); + displayString.append(" ; \t\n"); + for (String srcList : ruleSrcList.split(",")) { + if (srcList.startsWith(GROUP)) { + AddressGroup ag; + ag = mappingAddressGroup(srcList); + displayString.append( + "\n\t" + "Group has :" + (ag != null ? ag.getPrefixList() : "") + "\n"); + if (ag != null) { + for (String groupItems : ag.getPrefixList().split(",")) { + valueDesc = mapping(groupItems); + displayString.append("\n\t" + "Name: " + groupItems); + if (!valueDesc.isEmpty()) { + displayString.append("\n\t" + "Description: " + valueDesc.get(1)); + displayString.append("\n\t" + "Value: " + valueDesc.get(0)); + } + displayString.append("\n"); + } + } + } else { + if (!srcList.equals(ANY)) { + valueDesc = mapping(srcList); + displayString.append("\n\t" + "Name: " + srcList); + displayString.append("\n\t" + "Description: " + valueDesc.get(1)); + displayString.append("\n\t" + "Value: " + valueDesc.get(0)); + displayString.append("\n"); + } + } + } + displayString.append("\n"); + } + ruleDestList = jpaTermList.getDestIPList(); + if (ruleDestList != null && (!ruleDestList.isEmpty()) && !"null".equals(ruleDestList)) { + displayString.append("Destination IP List: " + jpaTermList.getDestIPList()); + displayString.append(" ; \t\n"); + for (String destList : ruleDestList.split(",")) { + if (destList.startsWith(GROUP)) { + AddressGroup ag; + ag = mappingAddressGroup(destList); + displayString.append( + "\n\t" + "Group has :" + (ag != null ? ag.getPrefixList() : "") + "\n"); + if (ag != null) { + for (String groupItems : ag.getPrefixList().split(",")) { + valueDesc = mapping(groupItems); + displayString.append("\n\t" + "Name: " + groupItems); + displayString.append("\n\t" + "Description: " + valueDesc.get(1)); + displayString.append("\n\t" + "Value: " + valueDesc.get(0)); + displayString.append("\n\t"); + } + } + } else { + if (!destList.equals(ANY)) { + valueDesc = mapping(destList); + displayString.append("\n\t" + "Name: " + destList); + displayString.append("\n\t" + "Description: " + valueDesc.get(1)); + displayString.append("\n\t" + "Value: " + valueDesc.get(0)); + displayString.append("\n\t"); + } + } + } + displayString.append("\n"); + } + + ruleSrcPort = jpaTermList.getSrcPortList(); + if (ruleSrcPort != null && (!ruleSrcPort.isEmpty()) && !"null".equals(ruleSrcPort)) { + displayString.append("\n" + "Source Port List:" + ruleSrcPort); + displayString.append(" ; \t\n"); + } + + ruleDestPort = jpaTermList.getDestPortList(); + if (ruleDestPort != null && (!ruleDestPort.isEmpty()) && !"null".equals(ruleDestPort)) { + displayString.append("\n" + "Destination Port List:" + ruleDestPort); + displayString.append(" ; \t\n"); + for (String destServices : ruleDestPort.split(",")) { + if (destServices.startsWith(GROUP)) { + GroupServiceList sg; + sg = mappingServiceGroup(destServices); + displayString.append("\n\t" + "Service Group has :" + + (sg != null ? sg.getServiceList() : "") + "\n"); + if (sg != null) { + for (String groupItems : sg.getServiceList().split(",")) { + ServiceList sl; + sl = mappingServiceList(groupItems); + displayString.append("\n\t" + "Name: " + sl.getServiceName()); + displayString.append("\n\t" + "Description: " + sl.getServiceDescription()); + displayString.append( + "\n\t" + "Transport-Protocol: " + sl.getServiceTransProtocol()); + displayString.append("\n\t" + "Ports: " + sl.getServicePorts()); + displayString.append("\n"); + } + } + } else { + if (!destServices.equals(ANY)) { + ServiceList sl; + sl = mappingServiceList(destServices); + displayString.append("\n\t" + "Name: " + sl.getServiceName()); + displayString.append("\n\t" + "Description: " + sl.getServiceDescription()); + displayString + .append("\n\t" + "Transport-Protocol: " + sl.getServiceTransProtocol()); + displayString.append("\n\t" + "Ports: " + sl.getServicePorts()); + displayString.append("\n"); + } + } + } + displayString.append("\n"); + } + + ruleAction = (jpaTermList).getAction(); + if (ruleAction != null && (!ruleAction.isEmpty())) { + displayString.append("\n" + "Action List:" + ruleAction); + displayString.append(" ; \t\n"); + } + } + } + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(displayString); + JSONObject j = new JSONObject("{policyData: " + responseString + "}"); + out.write(j.toString()); + return null; + } catch (Exception e) { + policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + return null; + } + + private String constructJson(PolicyRestAdapter policyData) { + int ruleCount = 1; + // Maps to assosciate the values read from the TermList dictionary + Map<Integer, String> srcIP_map = null; + Map<Integer, String> destIP_map = null; + Map<Integer, String> srcPort_map = null; + Map<Integer, String> destPort_map = null; + Map<Integer, String> action_map = null; + Map<Integer, String> fromZone_map = null; + Map<Integer, String> toZone_map = null; + + String ruleDesc = null; + String ruleFromZone = null; + String ruleToZone = null; + String ruleSrcPrefixList = null; + String ruleDestPrefixList = null; + String ruleSrcPort = null; + String ruleDestPort = null; + String ruleAction = null; + + String json = null; + + List<String> expandableList = new ArrayList<>(); + TermList jpaTermList; + TermCollector tc = new TermCollector(); + SecurityZone jpaSecurityZone; + List<Term> termList = new ArrayList<>(); + + Tags tags = null; + List<Tags> tagsList = new ArrayList<>(); + + TagDefines tagDefine = new TagDefines(); + List<TagDefines> tagList = null; + ServiceListJson targetSl = null; + AddressMembers addressMembersJson = null; + int i = 0; + try { + String networkRole = ""; + for (String tag : tagCollectorList) { + tags = new Tags(); + List<Object> tagListData = commonClassDao.getData(FWTagPicker.class); + for (int tagCounter = 0; tagCounter < tagListData.size(); tagCounter++) { + FWTagPicker jpaTagPickerList = (FWTagPicker) tagListData.get(tagCounter); + if (jpaTagPickerList.getTagPickerName().equals(tag)) { + String tagValues = jpaTagPickerList.getTagValues(); + tagList = new ArrayList<>(); + for (String val : tagValues.split("#")) { + int index = val.indexOf(':'); + String keyToStore = val.substring(0, index); + String valueToStore = val.substring(index + 1, val.length()); + + tagDefine = new TagDefines(); + tagDefine.setKey(keyToStore); + tagDefine.setValue(valueToStore); + // Add to the collection. + tagList.add(tagDefine); + + } + networkRole = jpaTagPickerList.getNetworkRole(); + break; + } + } + tags.setTags(tagList); + tags.setTagPickerName(tag); + tags.setRuleName(termCollectorList.get(i)); + tags.setNetworkRole(networkRole); + tagsList.add(tags); + i++; + } + tc.setRuleToTag(tagsList); + + for (int tl = 0; tl < termCollectorList.size(); tl++) { + expandableList.add(termCollectorList.get(tl)); + Term targetTerm = new Term(); + targetTerm.setRuleName(termCollectorList.get(tl)); + List<Object> termListData = commonClassDao.getData(TermList.class); + for (int j = 0; j < termListData.size(); j++) { + jpaTermList = (TermList) termListData.get(j); + if (jpaTermList.getTermName().equals(termCollectorList.get(tl))) { + ruleDesc = jpaTermList.getTermDescription(); + if ((ruleDesc != null) && (!ruleDesc.isEmpty())) { + targetTerm.setDescription(ruleDesc); + } + ruleFromZone = jpaTermList.getFromZone(); + + if ((ruleFromZone != null) && (!ruleFromZone.isEmpty())) { + fromZone_map = new HashMap<>(); + fromZone_map.put(tl, ruleFromZone); + } + ruleToZone = jpaTermList.getToZone(); + + if ((ruleToZone != null) && (!ruleToZone.isEmpty())) { + toZone_map = new HashMap<>(); + toZone_map.put(tl, ruleToZone); + } + ruleSrcPrefixList = jpaTermList.getSrcIPList(); + + if ((ruleSrcPrefixList != null) && (!ruleSrcPrefixList.isEmpty())) { + srcIP_map = new HashMap<>(); + srcIP_map.put(tl, ruleSrcPrefixList); + } + + ruleDestPrefixList = jpaTermList.getDestIPList(); + if ((ruleDestPrefixList != null) && (!ruleDestPrefixList.isEmpty())) { + destIP_map = new HashMap<>(); + destIP_map.put(tl, ruleDestPrefixList); + } + + ruleSrcPort = jpaTermList.getSrcPortList(); + + if (ruleSrcPort != null && (!ruleSrcPort.isEmpty())) { + srcPort_map = new HashMap<>(); + srcPort_map.put(tl, ruleSrcPort); + } + + ruleDestPort = jpaTermList.getDestPortList(); + + if (ruleDestPort != null && (!jpaTermList.getDestPortList().isEmpty())) { + destPort_map = new HashMap<>(); + destPort_map.put(tl, ruleDestPort); + } + + ruleAction = jpaTermList.getAction(); + + if ((ruleAction != null) && (!ruleAction.isEmpty())) { + action_map = new HashMap<>(); + action_map.put(tl, ruleAction); + } + } + } + targetTerm.setEnabled(true); + targetTerm.setLog(true); + targetTerm.setNegateSource(false); + targetTerm.setNegateDestination(false); + + if (action_map != null) { + targetTerm.setAction(action_map.get(tl)); + } + + // FromZone arrays + if (fromZone_map != null) { + List<String> fromZone = new ArrayList<>(); + for (String fromZoneStr : fromZone_map.get(tl).split(",")) { + fromZone.add(fromZoneStr); + } + targetTerm.setFromZones(fromZone); + } + + // ToZone arrays + if (toZone_map != null) { + List<String> toZone = new ArrayList<>(); + for (String toZoneStr : toZone_map.get(tl).split(",")) { + toZone.add(toZoneStr); + } + targetTerm.setToZones(toZone); + } + + // Destination Services. + if (destPort_map != null) { + Set<ServicesJson> destServicesJsonList = new HashSet<>(); + for (String destServices : destPort_map.get(tl).split(",")) { + ServicesJson destServicesJson = new ServicesJson(); + destServicesJson.setType("REFERENCE"); + if (destServices.equals(ANY)) { + destServicesJson.setName("any"); + destServicesJsonList.add(destServicesJson); + break; + } else { + if (destServices.startsWith(GROUP)) { + destServicesJson.setName(destServices.substring(6, destServices.length())); + } else { + destServicesJson.setName(destServices); + } + destServicesJsonList.add(destServicesJson); + } + } + targetTerm.setDestServices(destServicesJsonList); + } + // ExpandableServicesList + if ((srcPort_map != null) && (destPort_map != null)) { + String servicesCollateString = srcPort_map.get(tl) + "," + destPort_map.get(tl); + expandableServicesList.add(servicesCollateString); + } else if (srcPort_map != null) { + expandableServicesList.add(srcPort_map.get(tl)); + } else if (destPort_map != null) { + expandableServicesList.add(destPort_map.get(tl)); + } + + if (srcIP_map != null) { + // Source List + List<AddressJson> sourceListArrayJson = new ArrayList<>(); + for (String srcList : srcIP_map.get(tl).split(",")) { + AddressJson srcListJson = new AddressJson(); + if (srcList.equals(ANY)) { + srcListJson.setType("any"); + sourceListArrayJson.add(srcListJson); + break; + } else { + srcListJson.setType("REFERENCE"); + if (srcList.startsWith(GROUP)) { + srcListJson.setName(srcList.substring(6, srcList.length())); + } else { + srcListJson.setName(srcList); + } + sourceListArrayJson.add(srcListJson); + } + } + targetTerm.setSourceList(sourceListArrayJson); + } + if (destIP_map != null) { + // Destination List + List<AddressJson> destListArrayJson = new ArrayList<>(); + for (String destList : destIP_map.get(tl).split(",")) { + AddressJson destListJson = new AddressJson(); + if (destList.equals(ANY)) { + destListJson.setType("any"); + destListArrayJson.add(destListJson); + break; + } else { + destListJson.setType("REFERENCE"); + if (destList.startsWith(GROUP)) { + destListJson.setName(destList.substring(6, destList.length())); + } else { + destListJson.setName(destList); + } + destListArrayJson.add(destListJson); + } + } + targetTerm.setDestinationList(destListArrayJson); + } + // ExpandablePrefixIPList + if ((srcIP_map != null) && (destIP_map != null)) { + String collateString = srcIP_map.get(tl) + "," + destIP_map.get(tl); + expandablePrefixIPList.add(collateString); + } else if (srcIP_map != null) { + expandablePrefixIPList.add(srcIP_map.get(tl)); + } else if (destIP_map != null) { + expandablePrefixIPList.add(destIP_map.get(tl)); + } + termList.add(targetTerm); + targetTerm.setPosition(Integer.toString(ruleCount++)); + } + + List<Object> securityZoneData = commonClassDao.getData(SecurityZone.class); + for (int j = 0; j < securityZoneData.size(); j++) { + jpaSecurityZone = (SecurityZone) securityZoneData.get(j); + if (jpaSecurityZone.getZoneName().equals(policyData.getSecurityZone())) { + tc.setSecurityZoneId(jpaSecurityZone.getZoneValue()); + IdMap idMapInstance = new IdMap(); + idMapInstance.setAstraId(jpaSecurityZone.getZoneValue()); + idMapInstance.setVendorId("deviceGroup:dev"); + + List<IdMap> idMap = new ArrayList<>(); + idMap.add(idMapInstance); + + VendorSpecificData vendorStructure = new VendorSpecificData(); + vendorStructure.setIdMap(idMap); + tc.setVendorSpecificData(vendorStructure); + break; + } + } + + tc.setServiceTypeId("/v0/firewall/pan"); + tc.setConfigName(policyData.getConfigName()); + tc.setVendorServiceId("vipr"); + + DeployNowJson deployNow = new DeployNowJson(); + deployNow.setDeployNow(false); + + tc.setDeploymentOption(deployNow); + + Set<ServiceListJson> servListArray = new HashSet<>(); + Set<ServiceGroupJson> servGroupArray = new HashSet<>(); + Set<AddressGroupJson> addrGroupArray = new HashSet<>(); + Set<AddressMembers> addrArray = new HashSet<>(); + + ServiceGroupJson targetSg; + AddressGroupJson addressSg; + ServiceListJson targetAny; + ServiceListJson targetAnyTcp; + ServiceListJson targetAnyUdp; + + for (String serviceList : expandableServicesList) { + for (String t : serviceList.split(",")) { + if (!t.startsWith(GROUP)) { + if (!t.equals(ANY)) { + ServiceList sl; + targetSl = new ServiceListJson(); + sl = mappingServiceList(t); + targetSl.setName(sl.getServiceName()); + targetSl.setDescription(sl.getServiceDescription()); + targetSl.setTransportProtocol(sl.getServiceTransProtocol()); + targetSl.setType(sl.getServiceType()); + targetSl.setPorts(sl.getServicePorts()); + servListArray.add(targetSl); + } else { + // Any for destinationServices. + // Add names any, any-tcp, any-udp to the serviceGroup object. + targetAny = new ServiceListJson(); + targetAny.setName("any"); + targetAny.setType("SERVICE"); + targetAny.setTransportProtocol("any"); + targetAny.setPorts("any"); + + servListArray.add(targetAny); + + targetAnyTcp = new ServiceListJson(); + targetAnyTcp.setName("any-tcp"); + targetAnyTcp.setType("SERVICE"); + targetAnyTcp.setTransportProtocol("tcp"); + targetAnyTcp.setPorts("any"); + + servListArray.add(targetAnyTcp); + + targetAnyUdp = new ServiceListJson(); + targetAnyUdp.setName("any-udp"); + targetAnyUdp.setType("SERVICE"); + targetAnyUdp.setTransportProtocol("udp"); + targetAnyUdp.setPorts("any"); + + servListArray.add(targetAnyUdp); + } + } else {// This is a group + GroupServiceList sg; + targetSg = new ServiceGroupJson(); + sg = mappingServiceGroup(t); + + String name = sg.getGroupName(); + // Removing the "Group_" prepending string before packing the JSON + targetSg.setName(name.substring(6, name.length())); + List<ServiceMembers> servMembersList = new ArrayList<>(); + + for (String groupString : sg.getServiceList().split(",")) { + ServiceMembers serviceMembers = new ServiceMembers(); + serviceMembers.setType("REFERENCE"); + serviceMembers.setName(groupString); + servMembersList.add(serviceMembers); + // Expand the group Name + ServiceList expandGroupSl; + targetSl = new ServiceListJson(); + expandGroupSl = mappingServiceList(groupString); + + targetSl.setName(expandGroupSl.getServiceName()); + targetSl.setDescription(expandGroupSl.getServiceDescription()); + targetSl.setTransportProtocol(expandGroupSl.getServiceTransProtocol()); + targetSl.setType(expandGroupSl.getServiceType()); + targetSl.setPorts(expandGroupSl.getServicePorts()); + servListArray.add(targetSl); + } + + targetSg.setMembers(servMembersList); + servGroupArray.add(targetSg); + + } + } + } + + Set<PrefixIPList> prefixIPList = new HashSet<>(); + for (String prefixList : expandablePrefixIPList) { + for (String prefixIP : prefixList.split(",")) { + if (!prefixIP.startsWith(GROUP)) { + if (!prefixIP.equals(ANY)) { + List<AddressMembers> addMembersList = new ArrayList<>(); + List<String> valueDesc; + PrefixIPList targetAddressList = new PrefixIPList(); + AddressMembers addressMembers = new AddressMembers(); + targetAddressList.setName(prefixIP); + policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "PrefixList value:" + prefixIP); + valueDesc = mapping(prefixIP); + if (!valueDesc.isEmpty()) { + policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "PrefixList description:" + + valueDesc.get(1)); + targetAddressList.setDescription(valueDesc.get(1)); + } + + addressMembers.setType("SUBNET"); + if (!valueDesc.isEmpty()) { + addressMembers.setValue(valueDesc.get(0)); + } + + addMembersList.add(addressMembers); + + targetAddressList.setMembers(addMembersList); + prefixIPList.add(targetAddressList); + } + } else {// This is a group + AddressGroup ag; + addressSg = new AddressGroupJson(); + ag = mappingAddressGroup(prefixIP); + + String name = ag.getGroupName(); + // Removing the "Group_" prepending string before packing the JSON + addressSg.setName(name.substring(6, name.length())); + + List<AddressMembersJson> addrMembersList = new ArrayList<>(); + for (String groupString : ag.getPrefixList().split(",")) { + List<String> valueDesc; + AddressMembersJson addressMembers = new AddressMembersJson(); + addressMembers.setType("REFERENCES"); + addressMembers.setName(groupString); + addrMembersList.add(addressMembers); + // Expand the group Name + addressMembersJson = new AddressMembers(); + valueDesc = mapping(groupString); + + addressMembersJson.setName(groupString); + addressMembersJson.setType("SUBNET"); + addressMembersJson.setValue(valueDesc.get(0)); + + addrArray.add(addressMembersJson); + + } + addressSg.setMembers(addrMembersList); + addrGroupArray.add(addressSg); + } + + } + } + + Set<Object> serviceGroup = new HashSet<>(); + + for (Object obj1 : servGroupArray) { + serviceGroup.add(obj1); + } + + for (Object obj : servListArray) { + serviceGroup.add(obj); + } + + Set<Object> addressGroup = new HashSet<>(); + + for (Object addObj : prefixIPList) { + addressGroup.add(addObj); + } + + for (Object addObj1 : addrGroupArray) { + addressGroup.add(addObj1); + } + + for (Object addObj2 : addrArray) { + addressGroup.add(addObj2); + } + + tc.setServiceGroups(serviceGroup); + tc.setAddressGroups(addressGroup); + tc.setFirewallRuleList(termList); + + ObjectWriter om = new ObjectMapper().writer(); + try { + json = om.writeValueAsString(tc); + } catch (JsonGenerationException e) { + policyLogger.error("JsonGenerationException Ocured", e); + } catch (JsonMappingException e) { + policyLogger.error("IOException Occured", e); + } + + } catch (Exception e) { + policyLogger.error("Exception Occured" + e); + } + + return json; + } } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateOptimizationController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateOptimizationController.java index 05fddb50d..719c66805 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateOptimizationController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateOptimizationController.java @@ -20,7 +20,6 @@ package org.onap.policy.controller; - import com.att.research.xacml.util.XACMLProperties; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -28,6 +27,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.google.gson.Gson; + import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; @@ -49,8 +49,10 @@ import java.util.Set; import java.util.UUID; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; @@ -58,6 +60,7 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + import org.apache.commons.compress.utils.IOUtils; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; @@ -119,7 +122,6 @@ public class CreateOptimizationController extends RestrictedBaseController { public static final String MODELNAME = "modelName"; public static final String APPLICATIONJSON = "application / json"; - @Autowired private CreateOptimizationController(CommonClassDao commonClassDao) { setCommonClassDao(commonClassDao); @@ -186,7 +188,8 @@ public class CreateOptimizationController extends RestrictedBaseController { return policyAdapter; } - @RequestMapping(value = {"/policyController/getOptimizationTemplateData.htm"}, + @RequestMapping( + value = {"/policyController/getOptimizationTemplateData.htm"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST}) public ModelAndView getOptimizationTemplateData(HttpServletRequest request, HttpServletResponse response) throws IOException { @@ -442,7 +445,8 @@ public class CreateOptimizationController extends RestrictedBaseController { return keys; } - @RequestMapping(value = {"/policyController/getModelServiceVersionData.htm"}, + @RequestMapping( + value = {"/policyController/getModelServiceVersionData.htm"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST}) public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response) throws IOException { @@ -612,7 +616,8 @@ public class CreateOptimizationController extends RestrictedBaseController { } - @RequestMapping(value = {"/oof_dictionary/set_ModelData"}, + @RequestMapping( + value = {"/oof_dictionary/set_ModelData"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST}) public void setModelData(HttpServletRequest request, HttpServletResponse response) throws IOException, FileUploadException { diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java index 6cd121ee6..f7295d587 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,21 +20,12 @@ package org.onap.policy.controller; - import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; -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; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; @@ -44,108 +35,117 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +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; + @Controller @RequestMapping("/") -public class CreatePolicyController extends RestrictedBaseController{ +public class CreatePolicyController extends RestrictedBaseController { private static Logger policyLogger = FlexLogger.getLogger(CreatePolicyController.class); - protected PolicyRestAdapter policyAdapter = null; - private ArrayList<Object> attributeList; - boolean isValidForm = false; + protected PolicyRestAdapter policyAdapter = null; + private ArrayList<Object> attributeList; + boolean isValidForm = false; - public void prePopulateBaseConfigPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - attributeList = new ArrayList<>(); - if (policyAdapter.getPolicyData() instanceof PolicyType) { - Object policyData = policyAdapter.getPolicyData(); - PolicyType policy = (PolicyType) policyData; - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - policyAdapter.setConfigType(entity.getConfigurationData().getConfigType()); - policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody()); - 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){ - policyLogger.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue ,e); - description = policy.getDescription(); - } - policyAdapter.setPolicyDescription(description); - // Get the target data under policy. - 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 AnyOFType we have AllOFType - List<AllOfType> allOfList = anyOf.getAllOf(); - if (allOfList != null) { - Iterator<AllOfType> iterAllOf = allOfList.iterator(); - int index = 0; - while (iterAllOf.hasNext()) { - AllOfType allOf = iterAllOf.next(); - // Under AllOFType we have Match - 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 attribute value and - // attributeDesignator. So,finally down to the actual attribute. - // - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - // First match in the target is OnapName, so set that value. - if ("ONAPName".equals(attributeId)) { - policyAdapter.setOnapName(value); - } - if ("RiskType".equals(attributeId)){ - policyAdapter.setRiskType(value); - } - if ("RiskLevel".equals(attributeId)){ - policyAdapter.setRiskLevel(value); - } - if ("guard".equals(attributeId)){ - policyAdapter.setGuard(value); - } - if ("TTLDate".equals(attributeId) && !value.contains("NA")){ - PolicyController controller = new PolicyController(); - String newDate = controller.convertDate(value); - policyAdapter.setTtlDate(newDate); - } - if ("ConfigName".equals(attributeId)){ - policyAdapter.setConfigName(value); - } - // After Onap and Config it is optional to have attributes, so - // check weather dynamic values or there or not. - if (index >= 7) { - Map<String, String> attribute = new HashMap<>(); - attribute.put("key", attributeId); - attribute.put("value", value); - attributeList.add(attribute); - } - index++; - } - } - } - } - } - } + public void prePopulateBaseConfigPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + attributeList = new ArrayList<>(); + if (policyAdapter.getPolicyData() instanceof PolicyType) { + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + policyAdapter.setConfigType(entity.getConfigurationData().getConfigType()); + policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody()); + 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) { + policyLogger.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e); + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Get the target data under policy. + 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 AnyOFType we have AllOFType + List<AllOfType> allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator<AllOfType> iterAllOf = allOfList.iterator(); + int index = 0; + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOFType we have Match + 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 attribute value and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + // First match in the target is OnapName, so set that value. + if ("ONAPName".equals(attributeId)) { + policyAdapter.setOnapName(value); + } + if ("RiskType".equals(attributeId)) { + policyAdapter.setRiskType(value); + } + if ("RiskLevel".equals(attributeId)) { + policyAdapter.setRiskLevel(value); + } + if ("guard".equals(attributeId)) { + policyAdapter.setGuard(value); + } + if ("TTLDate".equals(attributeId) && !value.contains("NA")) { + PolicyController controller = new PolicyController(); + String newDate = controller.convertDate(value); + policyAdapter.setTtlDate(newDate); + } + if ("ConfigName".equals(attributeId)) { + policyAdapter.setConfigName(value); + } + // After Onap and Config it is optional to have attributes, so + // check weather dynamic values or there or not. + if (index >= 7) { + Map<String, String> attribute = new HashMap<>(); + attribute.put("key", attributeId); + attribute.put("value", value); + attributeList.add(attribute); + } + index++; + } + } + } + } + } + } - policyAdapter.setAttributes(attributeList); - } - List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); - for (Object o : ruleList) { - if (o instanceof RuleType) { - // get the condition data under the rule for rule Algorithms. - policyAdapter.setRuleID(((RuleType) o).getRuleId()); - } - } - } - } + policyAdapter.setAttributes(attributeList); + } + List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); + for (Object o : ruleList) { + if (o instanceof RuleType) { + // get the condition data under the rule for rule Algorithms. + policyAdapter.setRuleID(((RuleType) o).getRuleId()); + } + } + } + } } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java index d3af75dfd..b90cc52c8 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,6 +29,7 @@ import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; import java.io.PrintWriter; import java.net.MalformedURLException; @@ -41,6 +42,7 @@ import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; + import javax.management.AttributeNotFoundException; import javax.management.InstanceNotFoundException; import javax.management.MBeanException; @@ -53,6 +55,7 @@ import javax.management.remote.JMXServiceURL; import javax.script.SimpleBindings; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.json.JSONObject; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; @@ -117,15 +120,14 @@ public class DashboardController extends RestrictedBaseController { return policyController != null ? getPolicyController() : new PolicyController(); } - - /** * This method is to retrieve all the data of last 30 days from PolicyEntity table as default. * * @param request object * @param response object contains retrieved data */ - @RequestMapping(value = {"/get_DashboardPolicyCRUDData"}, + @RequestMapping( + value = {"/get_DashboardPolicyCRUDData"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void get_DashboardPolicyCrudData(HttpServletRequest request, HttpServletResponse response) { @@ -149,7 +151,8 @@ public class DashboardController extends RestrictedBaseController { * @param request object * @param response object contains retrieved data */ - @RequestMapping(value = {"/dashboardController/dashboardAdvancedSearch.htm"}, + @RequestMapping( + value = {"/dashboardController/dashboardAdvancedSearch.htm"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST}) public void dashboardAdvancedSearch(HttpServletRequest request, HttpServletResponse response) throws IOException { String lscope = null; @@ -202,7 +205,8 @@ public class DashboardController extends RestrictedBaseController { * @param request object * @param response object contains retrieved data */ - @RequestMapping(value = {"/get_DashboardPdpPolicyCRUDData"}, + @RequestMapping( + value = {"/get_DashboardPdpPolicyCRUDData"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void get_DashboardPdpPolicyCrudData(HttpServletRequest request, HttpServletResponse response) { @@ -219,7 +223,8 @@ public class DashboardController extends RestrictedBaseController { } } - @RequestMapping(value = {"/get_DashboardLoggingData"}, + @RequestMapping( + value = {"/get_DashboardLoggingData"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getData(HttpServletRequest request, HttpServletResponse response) { @@ -235,7 +240,8 @@ public class DashboardController extends RestrictedBaseController { } } - @RequestMapping(value = {"/get_DashboardSystemAlertData"}, + @RequestMapping( + value = {"/get_DashboardSystemAlertData"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getSystemAlertData(HttpServletRequest request, HttpServletResponse response) { @@ -251,7 +257,8 @@ public class DashboardController extends RestrictedBaseController { } } - @RequestMapping(value = {"/get_DashboardPAPStatusData"}, + @RequestMapping( + value = {"/get_DashboardPAPStatusData"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPAPStatusData(HttpServletRequest request, HttpServletResponse response) { @@ -269,7 +276,8 @@ public class DashboardController extends RestrictedBaseController { } } - @RequestMapping(value = {"/get_DashboardPDPStatusData"}, + @RequestMapping( + value = {"/get_DashboardPDPStatusData"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPDPStatusData(HttpServletRequest request, HttpServletResponse response) { @@ -289,7 +297,8 @@ public class DashboardController extends RestrictedBaseController { } } - @RequestMapping(value = {"/get_DashboardPolicyActivityData"}, + @RequestMapping( + value = {"/get_DashboardPolicyActivityData"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPolicyActivityData(HttpServletRequest request, HttpServletResponse response) { @@ -337,7 +346,6 @@ public class DashboardController extends RestrictedBaseController { papStatusData.add(0, object); } - /* * Add the PAP Policy information to the PAP Table */ @@ -407,7 +415,8 @@ public class DashboardController extends RestrictedBaseController { /* * Add the Policy information to the policyStatusCRUDDataTable */ - private void getPolicyData(String inputScope, String inputStage, String isDeleted, String createdAfter, String createdBefore) { + private void getPolicyData(String inputScope, String inputStage, String isDeleted, String createdAfter, + String createdBefore) { policyStatusCrudData = new ArrayList<>(); List<Object> policyData = null; SimpleBindings geParams = new SimpleBindings(); @@ -572,9 +581,8 @@ public class DashboardController extends RestrictedBaseController { HashMap map = null; try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map)) { jmxConnection.connect(); - Object o = - jmxConnection.getMBeanServerConnection().getAttribute( - new ObjectName("PdpRest:type=PdpRestMonitor"), jmxAttribute); + Object o = jmxConnection.getMBeanServerConnection() + .getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), jmxAttribute); policyLogger.debug("pdpEvaluationNA value retreived: " + o); return (long) o; } catch (MalformedURLException e) { @@ -601,7 +609,6 @@ public class DashboardController extends RestrictedBaseController { return new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi"); } - /* * Add the information to the Policy Table */ @@ -666,14 +673,13 @@ public class DashboardController extends RestrictedBaseController { */ @SuppressWarnings({"rawtypes", "unchecked"}) private Object getPolicy(String host, int port, String jmxAttribute) { - policyLogger.debug("Create an RMI connector client and connect it to the JMX connector server for Policy: " - + host); + policyLogger + .debug("Create an RMI connector client and connect it to the JMX connector server for Policy: " + host); HashMap map = null; try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map)) { jmxConnection.connect(); - Object o = - jmxConnection.getMBeanServerConnection().getAttribute( - new ObjectName("PdpRest:type=PdpRestMonitor"), "policyMap"); + Object o = jmxConnection.getMBeanServerConnection() + .getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), "policyMap"); policyLogger.debug("policyMap value retreived: " + o); return o; } catch (MalformedURLException e) { diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java index 4e8c8c141..d6a4e8285 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,19 +30,9 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; + import javax.xml.bind.JAXBElement; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.StringUtils; -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.adapter.RainyDayParams; -import org.onap.policy.rest.adapter.YAMLParams; -import org.onap.policy.rest.jpa.PolicyEntity; -import org.onap.policy.xacml.util.XACMLPolicyWriter; -import org.onap.portalsdk.core.controller.RestrictedBaseController; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; + import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; @@ -59,27 +49,40 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.StringUtils; +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.adapter.RainyDayParams; +import org.onap.policy.rest.adapter.YAMLParams; +import org.onap.policy.rest.jpa.PolicyEntity; +import org.onap.policy.xacml.util.XACMLPolicyWriter; +import org.onap.portalsdk.core.controller.RestrictedBaseController; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + @Controller @RequestMapping("/") public class DecisionPolicyController extends RestrictedBaseController { private static final Logger policyLogger = FlexLogger.getLogger(DecisionPolicyController.class); - + public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not"; private static final String BLENTRY = "@blEntry@"; private static final String DECISIONRAWTYPE = "@#RuleProvider@#Decision_Raw@#RuleProvider@#"; - private static final String GUARD_YAML= "GUARD_YAML"; - private static final String GUARD_BL_YAML= "GUARD_BL_YAML"; - private static final String GUARD_MIN_MAX= "GUARD_MIN_MAX"; - + private static final String GUARD_YAML = "GUARD_YAML"; + private static final String GUARD_BL_YAML = "GUARD_BL_YAML"; + private static final String GUARD_MIN_MAX = "GUARD_MIN_MAX"; + protected PolicyRestAdapter policyAdapter = null; private ArrayList<Object> ruleAlgorithmList; private ArrayList<Object> treatmentList = null; protected LinkedList<Integer> ruleAlgoirthmTracker; - + public DecisionPolicyController() { // This constructor is empty } - + public void rawXACMLPolicy(PolicyRestAdapter policyAdapter, PolicyEntity entity) { try (InputStream policyXmlStream = XACMLPolicyWriter.getXmlAsInputStream(policyAdapter.getPolicyData())) { String name = StringUtils.substringAfter(entity.getPolicyName(), "Decision_"); @@ -249,7 +252,7 @@ public class DecisionPolicyController extends RestrictedBaseController { if (policyAdapter.getRuleProvider() != null && (GUARD_YAML.equals(policyAdapter.getRuleProvider()) || (GUARD_BL_YAML.equals(policyAdapter.getRuleProvider())) - || (GUARD_MIN_MAX.equals(policyAdapter.getRuleProvider())))){ + || (GUARD_MIN_MAX.equals(policyAdapter.getRuleProvider())))) { YAMLParams yamlParams = new YAMLParams(); for (int i = 0; i < attributeList.size(); i++) { Map<String, String> map = (Map<String, String>) attributeList.get(i); @@ -377,7 +380,6 @@ public class DecisionPolicyController extends RestrictedBaseController { VariableReferenceType variableReference = (VariableReferenceType) jaxbDecisionTypes.get(0).getValue(); ruleMap.put("dynamicRuleAlgorithmField1", "S_" + variableReference.getVariableId()); - // Get from Attribute Value AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbDecisionTypes.get(1).getValue(); String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntries.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntries.java index 5c2e96bb5..1cfdbb736 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntries.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntries.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,8 +39,10 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.apache.commons.compress.utils.IOUtils; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; @@ -66,7 +68,6 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; - /** * This class is used to import and export the black list entries which were used in the Decision Blacklist Guard YAML * Policy. @@ -126,7 +127,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr String formatedDate = dateFormat.format(date); String fileName = "BlackList_Scope_" + adapter.getDomainDir() + "_Name_" + adapter.getPolicyName() - + "_Version_" + root.get("version").toString() + "_Date_" + formatedDate + ".xls"; + + "_Version_" + root.get("version").toString() + "_Date_" + formatedDate + ".xls"; String deleteCheckPath = tmpFile + File.separator + fileName; File deleteCheck = new File(deleteCheckPath); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java index a8a427970..24fade137 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,11 @@ package org.onap.policy.controller; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.io.PrintWriter; @@ -51,370 +56,396 @@ import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.api.pap.PDPPolicy; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - @Controller @RequestMapping({"/"}) public class PDPController extends RestrictedBaseController { - private static final Logger policyLogger = FlexLogger.getLogger(PDPController.class); - - protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<OnapPDPGroup>()); - private PDPGroupContainer container; - - private static String SUPERADMIN = "super-admin"; - private static String SUPEREDITOR = "super-editor"; - private static String SUPERGUEST = "super-guest"; - - private Set<OnapPDPGroup> groupsData; - - private boolean junit = false; - - private PolicyController policyController; - public PolicyController getPolicyController() { - return policyController; - } - - public void setPolicyController(PolicyController policyController) { - this.policyController = policyController; - } - - public synchronized void refreshGroups(HttpServletRequest request) { - synchronized(this.groups) { - this.groups.clear(); - try { - PolicyController controller = getPolicyControllerInstance(); - Set<PDPPolicy> filteredPolicies = new HashSet<>(); - Set<String> scopes; - List<String> roles; - String userId = isJunit() ? "Test" : UserUtils.getUserSession(request).getOrgUserId(); - List<Object> userRoles = controller.getRoles(userId); - Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles); - roles = pair.u; - scopes = pair.t; - - if(!junit&& controller.getPapEngine()==null){ - setPAPEngine(request); - } - if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ) { - if(!junit){ - this.groups.addAll(controller.getPapEngine().getOnapPDPGroups()); - }else{ - this.groups.addAll(this.getGroupsData()); - } - }else{ - if(!userRoles.isEmpty() && !scopes.isEmpty()){ - this.groups.addAll(controller.getPapEngine().getOnapPDPGroups()); - List<OnapPDPGroup> tempGroups = new ArrayList<>(); - if(!groups.isEmpty()){ - Iterator<OnapPDPGroup> pdpGroup = groups.iterator(); - while(pdpGroup.hasNext()){ - OnapPDPGroup group = pdpGroup.next(); - Set<PDPPolicy> policies = group.getPolicies(); - for(PDPPolicy policy : policies){ - for(String scope : scopes){ - scope = scope.replace(File.separator, "."); - String policyName = policy.getId(); - if(policyName.contains(".Config_")){ - policyName = policyName.substring(0, policyName.lastIndexOf(".Config_")); - }else if(policyName.contains(".Action_")){ - policyName = policyName.substring(0, policyName.lastIndexOf(".Action_")); - }else if(policyName.contains(".Decision_")){ - policyName = policyName.substring(0, policyName.lastIndexOf(".Decision_")); - } - if(policyName.startsWith(scope)){ - filteredPolicies.add(policy); - } - } - } - pdpGroup.remove(); - StdPDPGroup newGroup = (StdPDPGroup) group; - newGroup.setPolicies(filteredPolicies); - tempGroups.add(newGroup); - } - groups.clear(); - groups = tempGroups; - } - } - } - } catch (PAPException e) { - String message = "Unable to retrieve Groups from server: " + e; - policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Pap Engine is Null" + message); - } - } - } - - private void setPAPEngine(HttpServletRequest request) { - String myRequestURL = request.getRequestURL().toString(); + private static final Logger policyLogger = FlexLogger.getLogger(PDPController.class); + + protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<OnapPDPGroup>()); + private PDPGroupContainer container; + + private static String SUPERADMIN = "super-admin"; + private static String SUPEREDITOR = "super-editor"; + private static String SUPERGUEST = "super-guest"; + + private Set<OnapPDPGroup> groupsData; + + private boolean junit = false; + + private PolicyController policyController; + + public PolicyController getPolicyController() { + return policyController; + } + + public void setPolicyController(PolicyController policyController) { + this.policyController = policyController; + } + + public synchronized void refreshGroups(HttpServletRequest request) { + synchronized (this.groups) { + this.groups.clear(); + try { + PolicyController controller = getPolicyControllerInstance(); + Set<PDPPolicy> filteredPolicies = new HashSet<>(); + Set<String> scopes; + List<String> roles; + String userId = isJunit() ? "Test" : UserUtils.getUserSession(request).getOrgUserId(); + List<Object> userRoles = controller.getRoles(userId); + Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles); + roles = pair.u; + scopes = pair.t; + + if (!junit && controller.getPapEngine() == null) { + setPAPEngine(request); + } + if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) { + if (!junit) { + this.groups.addAll(controller.getPapEngine().getOnapPDPGroups()); + } else { + this.groups.addAll(this.getGroupsData()); + } + } else { + if (!userRoles.isEmpty() && !scopes.isEmpty()) { + this.groups.addAll(controller.getPapEngine().getOnapPDPGroups()); + List<OnapPDPGroup> tempGroups = new ArrayList<>(); + if (!groups.isEmpty()) { + Iterator<OnapPDPGroup> pdpGroup = groups.iterator(); + while (pdpGroup.hasNext()) { + OnapPDPGroup group = pdpGroup.next(); + Set<PDPPolicy> policies = group.getPolicies(); + for (PDPPolicy policy : policies) { + for (String scope : scopes) { + scope = scope.replace(File.separator, "."); + String policyName = policy.getId(); + if (policyName.contains(".Config_")) { + policyName = policyName.substring(0, policyName.lastIndexOf(".Config_")); + } else if (policyName.contains(".Action_")) { + policyName = policyName.substring(0, policyName.lastIndexOf(".Action_")); + } else if (policyName.contains(".Decision_")) { + policyName = policyName.substring(0, policyName.lastIndexOf(".Decision_")); + } + if (policyName.startsWith(scope)) { + filteredPolicies.add(policy); + } + } + } + pdpGroup.remove(); + StdPDPGroup newGroup = (StdPDPGroup) group; + newGroup.setPolicies(filteredPolicies); + tempGroups.add(newGroup); + } + groups.clear(); + groups = tempGroups; + } + } + } + } catch (PAPException e) { + String message = "Unable to retrieve Groups from server: " + e; + policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Pap Engine is Null" + message); + } + } + } + + private void setPAPEngine(HttpServletRequest request) { + String myRequestURL = request.getRequestURL().toString(); try { // // Set the URL for the RESTful PAP Engine // PolicyController.setPapEngine((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL)); - }catch(Exception e){ - policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while loading PAP",e); + } catch (Exception e) { + policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception Occured while loading PAP", e); + } + } + + @RequestMapping( + value = {"/get_PDPGroupData"}, + method = {org.springframework.web.bind.annotation.RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getPDPGroupEntityData(HttpServletRequest request, HttpServletResponse response) { + try { + ObjectMapper mapper = new ObjectMapper(); + refreshGroups(request); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } catch (Exception e) { + policyLogger.error( + XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while retrieving the PDP Group data" + e); + } + } + + @RequestMapping( + value = {"/pdp_Group/save_pdp_group"}, + method = {org.springframework.web.bind.annotation.RequestMethod.POST}) + public void savePDPGroup(HttpServletRequest request, HttpServletResponse response) { + try { + ObjectMapper mapper = new ObjectMapper(); + PolicyController controller = getPolicyControllerInstance(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + this.container = new PDPGroupContainer(controller.getPapEngine()); + + String userId = UserUtils.getUserSession(request).getOrgUserId(); + policyLogger.info( + "****************************************Logging UserID for Save PDP Group Function*****************************************"); + policyLogger.info("UserId: " + userId + "PDP Group Data: " + root.get("pdpGroupData").toString()); + policyLogger.info( + "***************************************************************************************************************************"); + + StdPDPGroup pdpGroupData = mapper + .readValue(root.get("pdpGroupData").toString().replace("groupName", "name"), StdPDPGroup.class); + try { + if (pdpGroupData.getId() == null) { + this.container.addNewGroup(pdpGroupData.getName(), pdpGroupData.getDescription()); + } else { + this.container.updateGroup(pdpGroupData); + } + + } catch (Exception e) { + String message = "Unable to create Group. Reason:\n" + e.getMessage(); + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while creating the PDP Group" + + message + e); + } + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + refreshGroups(request); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + out.write(j.toString()); + } catch (Exception e) { + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Saving the PDP Group" + e); + response.setCharacterEncoding("UTF-8"); + PrintWriter out = null; + try { + request.setCharacterEncoding("UTF-8"); + out = response.getWriter(); + out.write(e.getMessage()); + } catch (Exception e1) { + policyLogger + .error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Saving the PDP Group" + e1); + } + } + } + + @RequestMapping( + value = {"/pdp_Group/remove_pdp_group"}, + method = {org.springframework.web.bind.annotation.RequestMethod.POST}) + public void removePDPGroup(HttpServletRequest request, HttpServletResponse response) { + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyController controller = getPolicyControllerInstance(); + this.container = new PDPGroupContainer(controller.getPapEngine()); + + String userId = UserUtils.getUserSession(request).getOrgUserId(); + policyLogger.info( + "****************************************Logging UserID for Remove PDP Group Function*****************************************"); + policyLogger.info("UserId: " + userId + "PDP Group Data: " + root.get("pdpGroupData").toString()); + policyLogger.info( + "*****************************************************************************************************************************"); + + StdPDPGroup pdpGroupData = mapper.readValue(root.get("pdpGroupData").toString(), StdPDPGroup.class); + if ("Default".equals(pdpGroupData.getName())) { + throw new UnsupportedOperationException("You can't remove the Default Group."); + } else { + this.container.removeGroup(pdpGroupData, null); + } + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + refreshGroups(request); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + out.write(j.toString()); + } catch (Exception e) { + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Removing the PDP Group" + e); + PrintWriter out; + try { + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + out = response.getWriter(); + out.write(e.getMessage()); + } catch (Exception e1) { + policyLogger.error("Exception Occured" + e1); + } } } - @RequestMapping(value={"/get_PDPGroupData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPDPGroupEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - ObjectMapper mapper = new ObjectMapper(); - refreshGroups(request); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while retrieving the PDP Group data" + e); - } - } - - @RequestMapping(value={"/pdp_Group/save_pdp_group"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public void savePDPGroup(HttpServletRequest request, HttpServletResponse response){ - try { - ObjectMapper mapper = new ObjectMapper(); - PolicyController controller = getPolicyControllerInstance(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - this.container = new PDPGroupContainer(controller.getPapEngine()); - - String userId = UserUtils.getUserSession(request).getOrgUserId(); - policyLogger.info("****************************************Logging UserID for Save PDP Group Function*****************************************"); - policyLogger.info("UserId: " + userId + "PDP Group Data: "+ root.get("pdpGroupData").toString()); - policyLogger.info("***************************************************************************************************************************"); - - StdPDPGroup pdpGroupData = mapper.readValue(root.get("pdpGroupData").toString().replace("groupName", "name"), StdPDPGroup.class); - try { - if(pdpGroupData.getId() == null){ - this.container.addNewGroup(pdpGroupData.getName(), pdpGroupData.getDescription()); - }else{ - this.container.updateGroup(pdpGroupData); - } - - } catch (Exception e) { - String message = "Unable to create Group. Reason:\n" + e.getMessage(); - policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while creating the PDP Group" + message + e); - } - - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - refreshGroups(request); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); - JSONObject j = new JSONObject(msg); - out.write(j.toString()); - } - catch (Exception e){ - policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Saving the PDP Group" + e); - response.setCharacterEncoding("UTF-8"); - PrintWriter out = null; - try { - request.setCharacterEncoding("UTF-8"); - out = response.getWriter(); - out.write(e.getMessage()); - } catch (Exception e1) { - policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Saving the PDP Group" + e1); - } - } - } - - @RequestMapping(value={"/pdp_Group/remove_pdp_group"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public void removePDPGroup(HttpServletRequest request, HttpServletResponse response){ - try{ - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - PolicyController controller = getPolicyControllerInstance(); - this.container = new PDPGroupContainer(controller.getPapEngine()); - - String userId = UserUtils.getUserSession(request).getOrgUserId(); - policyLogger.info("****************************************Logging UserID for Remove PDP Group Function*****************************************"); - policyLogger.info("UserId: " + userId + "PDP Group Data: "+ root.get("pdpGroupData").toString()); - policyLogger.info("*****************************************************************************************************************************"); - - StdPDPGroup pdpGroupData = mapper.readValue(root.get("pdpGroupData").toString(), StdPDPGroup.class); - if("Default".equals(pdpGroupData.getName())) { - throw new UnsupportedOperationException("You can't remove the Default Group."); - }else{ - this.container.removeGroup(pdpGroupData, null); - } - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - refreshGroups(request); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); - JSONObject j = new JSONObject(msg); - out.write(j.toString()); - } - catch (Exception e){ - policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing the PDP Group" + e); - PrintWriter out; - try { - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - out = response.getWriter(); - out.write(e.getMessage()); - } catch (Exception e1) { - policyLogger.error("Exception Occured"+ e1); - } - } - } - - @RequestMapping(value={"/pdp_Group/save_pdpTogroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public void savePDPToGroup(HttpServletRequest request, HttpServletResponse response){ - try { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - PolicyController controller = getPolicyControllerInstance(); - this.container = new PDPGroupContainer(controller.getPapEngine()); - String update = root.get("update").toString(); - PdpData pdpGroupData = mapper.readValue(root.get("pdpInGroup").toString(), PdpData.class); - StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class); - - String userId = UserUtils.getUserSession(request).getOrgUserId(); - policyLogger.info("****************************************Logging UserID while Saving pdp in PDP Group*****************************************"); - policyLogger.info("UserId: " + userId + "PDP Group Data: "+ root.get("pdpInGroup").toString() + "Active Group Data: "+ root.get("activePDP").toString()); - policyLogger.info("*******************************************************************************************************************************"); - - try { - - if(update.contains("false")){ - this.container.addNewPDP(pdpGroupData.getId(), activeGroupData, pdpGroupData.getName(), pdpGroupData.getDescription(), pdpGroupData.getJmxPort()); - }else{ - this.container.updateGroup(activeGroupData); - } - } catch (Exception e) { - String message = "Unable to create Group. Reason:\n" + e.getMessage(); - policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + message + e); - } - - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - refreshGroups(request); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); - JSONObject j = new JSONObject(msg); - out.write(j.toString()); - } - catch (Exception e){ - policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + e); - PrintWriter out; - try { - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - out = response.getWriter(); - out.write(e.getMessage()); - } catch (Exception e1) { - policyLogger.error("Exception Occured"+ e1); - } - } - } - - @RequestMapping(value={"/pdp_Group/remove_pdpFromGroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public void removePDPFromGroup(HttpServletRequest request, HttpServletResponse response){ - try{ - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - PolicyController controller = getPolicyControllerInstance(); - this.container = new PDPGroupContainer(controller.getPapEngine()); - StdPDP deletePdp = mapper.readValue(root.get("data").toString(), StdPDP.class); - StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class); - - String userId = UserUtils.getUserSession(request).getOrgUserId(); - policyLogger.info("****************************************Logging UserID while Removing pdp from PDP Group*****************************************"); - policyLogger.info("UserId: " + userId + "Delete PDP Group Data: "+ root.get("data").toString() + "Active Group Data: "+ root.get("activePDP").toString()); - policyLogger.info("***********************************************************************************************************************************"); - - this.container.removePDP(deletePdp, activeGroupData); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - refreshGroups(request); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); - JSONObject j = new JSONObject(msg); - out.write(j.toString()); - } - catch (Exception e){ - policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing Pdp from PDP Group" + e); - PrintWriter out; - try { - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - out = response.getWriter(); - out.write(e.getMessage()); - } catch (Exception e1) { - policyLogger.error("Exception Occured"+ e1); - } - } - } - - private PolicyController getPolicyControllerInstance(){ - return policyController != null ? getPolicyController() : new PolicyController(); - } - - public boolean isJunit() { - return junit; - } - - public void setJunit(boolean junit) { - this.junit = junit; - } - - public Set<OnapPDPGroup> getGroupsData() { - return groupsData; - } - - public void setGroupsData(Set<OnapPDPGroup> groupsData) { - this.groupsData = groupsData; - } + @RequestMapping( + value = {"/pdp_Group/save_pdpTogroup"}, + method = {org.springframework.web.bind.annotation.RequestMethod.POST}) + public void savePDPToGroup(HttpServletRequest request, HttpServletResponse response) { + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyController controller = getPolicyControllerInstance(); + this.container = new PDPGroupContainer(controller.getPapEngine()); + String update = root.get("update").toString(); + PdpData pdpGroupData = mapper.readValue(root.get("pdpInGroup").toString(), PdpData.class); + StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class); + + String userId = UserUtils.getUserSession(request).getOrgUserId(); + policyLogger.info( + "****************************************Logging UserID while Saving pdp in PDP Group*****************************************"); + policyLogger.info("UserId: " + userId + "PDP Group Data: " + root.get("pdpInGroup").toString() + + "Active Group Data: " + root.get("activePDP").toString()); + policyLogger.info( + "*******************************************************************************************************************************"); + + try { + + if (update.contains("false")) { + this.container.addNewPDP(pdpGroupData.getId(), activeGroupData, pdpGroupData.getName(), + pdpGroupData.getDescription(), pdpGroupData.getJmxPort()); + } else { + this.container.updateGroup(activeGroupData); + } + } catch (Exception e) { + String message = "Unable to create Group. Reason:\n" + e.getMessage(); + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + + "Error Occured while Creating Pdp in PDP Group" + message + e); + } + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + refreshGroups(request); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + out.write(j.toString()); + } catch (Exception e) { + policyLogger + .error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Creating Pdp in PDP Group" + e); + PrintWriter out; + try { + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + out = response.getWriter(); + out.write(e.getMessage()); + } catch (Exception e1) { + policyLogger.error("Exception Occured" + e1); + } + } + } + + @RequestMapping( + value = {"/pdp_Group/remove_pdpFromGroup"}, + method = {org.springframework.web.bind.annotation.RequestMethod.POST}) + public void removePDPFromGroup(HttpServletRequest request, HttpServletResponse response) { + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyController controller = getPolicyControllerInstance(); + this.container = new PDPGroupContainer(controller.getPapEngine()); + StdPDP deletePdp = mapper.readValue(root.get("data").toString(), StdPDP.class); + StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class); + + String userId = UserUtils.getUserSession(request).getOrgUserId(); + policyLogger.info( + "****************************************Logging UserID while Removing pdp from PDP Group*****************************************"); + policyLogger.info("UserId: " + userId + "Delete PDP Group Data: " + root.get("data").toString() + + "Active Group Data: " + root.get("activePDP").toString()); + policyLogger.info( + "***********************************************************************************************************************************"); + + this.container.removePDP(deletePdp, activeGroupData); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + refreshGroups(request); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + out.write(j.toString()); + } catch (Exception e) { + policyLogger.error( + XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Removing Pdp from PDP Group" + e); + PrintWriter out; + try { + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + out = response.getWriter(); + out.write(e.getMessage()); + } catch (Exception e1) { + policyLogger.error("Exception Occured" + e1); + } + } + } + + private PolicyController getPolicyControllerInstance() { + return policyController != null ? getPolicyController() : new PolicyController(); + } + + public boolean isJunit() { + return junit; + } + + public void setJunit(boolean junit) { + this.junit = junit; + } + + public Set<OnapPDPGroup> getGroupsData() { + return groupsData; + } + + public void setGroupsData(Set<OnapPDPGroup> groupsData) { + this.groupsData = groupsData; + } } -class PdpData{ - String id; - int jmxPort; - String name; - String description; - public String getId() { - return id; - } - public void setId(String id) { - this.id = id; - } - public int getJmxPort() { - return jmxPort; - } - public void setJmxPort(int jmxPort) { - this.jmxPort = jmxPort; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public String getDescription() { - return description; - } - public void setDescription(String description) { - this.description = description; - } - + +class PdpData { + String id; + int jmxPort; + String name; + String description; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public int getJmxPort() { + return jmxPort; + } + + public void setJmxPort(int jmxPort) { + this.jmxPort = jmxPort; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + } 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 700aa3a57..78fb87346 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 @@ -24,6 +24,7 @@ package org.onap.policy.controller; import com.att.research.xacml.util.XACMLProperties; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; @@ -37,12 +38,15 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; + import javax.annotation.PostConstruct; 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; @@ -183,9 +187,8 @@ 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"; } @@ -236,19 +239,17 @@ 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 @@ -298,8 +299,7 @@ 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); } @@ -311,22 +311,22 @@ public class PolicyController extends RestrictedBaseController { * @param request HttpServletRequest. * @param response HttpServletResponse. */ - @RequestMapping(value = {"/get_FunctionDefinitionDataByName"}, + @RequestMapping( + value = {"/get_FunctionDefinitionDataByName"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) - public void getFunctionDefinitionData(HttpServletRequest request, - HttpServletResponse response) { + public void getFunctionDefinitionData(HttpServletRequest request, HttpServletResponse response) { try { Map<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); } } @@ -368,7 +368,8 @@ public class PolicyController extends RestrictedBaseController { * @param request HttpServletRequest. * @param response HttpServletResponse. */ - @RequestMapping(value = {"/get_UserRolesData"}, + @RequestMapping( + value = {"/get_UserRolesData"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getUserRolesEntityData(HttpServletRequest request, HttpServletResponse response) { @@ -402,8 +403,7 @@ 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); @@ -438,8 +438,7 @@ 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); @@ -511,8 +510,7 @@ 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())) { @@ -576,8 +574,7 @@ 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) { @@ -620,8 +617,7 @@ 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]); @@ -637,8 +633,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); @@ -662,16 +658,14 @@ 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; } @@ -680,16 +674,14 @@ 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 polVersion = 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()); + userCreate = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", polVersion.getCreatedBy()); + userModify = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", polVersion.getModifiedBy()); } result[0] = userCreate != null ? userCreate.getUserName() : SUPERADMIN; @@ -726,8 +718,7 @@ 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; } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java index 6c7a0aff3..fb566f37d 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +23,7 @@ package org.onap.policy.controller; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; @@ -35,9 +36,11 @@ import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Set; + import javax.script.SimpleBindings; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; @@ -90,7 +93,6 @@ public class PolicyExportAndImportController extends RestrictedBaseController { private static final String ACTION = "Action_"; private static CommonClassDao commonClassDao; - private PolicyController policyController; public PolicyController getPolicyController() { @@ -120,7 +122,8 @@ public class PolicyExportAndImportController extends RestrictedBaseController { * @param response HttpServletResponse * @throws IOException error out */ - @RequestMapping(value = {"/policy_download/exportPolicy.htm"}, + @RequestMapping( + value = {"/policy_download/exportPolicy.htm"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST}) public void exportPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException { try (HSSFWorkbook workBook2 = new HSSFWorkbook()) { @@ -134,9 +137,8 @@ public class PolicyExportAndImportController extends RestrictedBaseController { LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>) policyId; String policyWithScope = selected.get(policyName).toString() + "." + selected.get("activeVersion").toString() + ".xml"; - String scope = - policyWithScope.substring(0, policyWithScope.lastIndexOf(File.separator)).replace( - File.separator, "."); + String scope = policyWithScope.substring(0, policyWithScope.lastIndexOf(File.separator)) + .replace(File.separator, "."); String policyNamel = policyWithScope.substring(policyWithScope.lastIndexOf(File.separator) + 1); selectedPolicy.add(policyNamel + ":" + scope); } @@ -152,9 +154,8 @@ public class PolicyExportAndImportController extends RestrictedBaseController { headingRow.createCell(6).setCellValue(BODYSIZE); headingRow.createCell(7).setCellValue(configurationbody); - List<Object> entityData = - commonClassDao.getMultipleDataOnAddingConjunction(PolicyEntity.class, "policyName:scope", - selectedPolicy); + List<Object> entityData = commonClassDao.getMultipleDataOnAddingConjunction(PolicyEntity.class, + "policyName:scope", selectedPolicy); processEntityData(entityData, sheet, headingRow); // String tmp = System.getProperty("catalina.base") + File.separator + "webapps" + File.separator + "temp"; String deleteCheckPath = tmp + File.separator + "PolicyExport.xls"; @@ -233,8 +234,8 @@ public class PolicyExportAndImportController extends RestrictedBaseController { row.createCell(7).setCellValue(body.substring(index, Math.min(index + 30000, body.length()))); } else { headingRow.createCell(7 + arraySize).setCellValue(configurationbody + arraySize); - row.createCell(7 + arraySize).setCellValue( - body.substring(index, Math.min(index + 30000, body.length()))); + row.createCell(7 + arraySize) + .setCellValue(body.substring(index, Math.min(index + 30000, body.length()))); } index += 30000; arraySize += 1; @@ -247,8 +248,6 @@ public class PolicyExportAndImportController extends RestrictedBaseController { return row; } - - /** * This is to upload a policy and save it to database. * @@ -331,9 +330,8 @@ public class PolicyExportAndImportController extends RestrictedBaseController { } private void writeConfigurationFile(ConfigurationDataEntity configurationDataEntity) { - try (FileWriter fw = - new FileWriter(PolicyController.getConfigHome() + File.separator - + configurationDataEntity.getConfigurationName())) { + try (FileWriter fw = new FileWriter( + PolicyController.getConfigHome() + File.separator + configurationDataEntity.getConfigurationName())) { BufferedWriter bw = new BufferedWriter(fw); bw.write(configurationDataEntity.getConfigBody()); bw.close(); @@ -343,8 +341,8 @@ public class PolicyExportAndImportController extends RestrictedBaseController { } private void writeActionBodyFile(ActionBodyEntity actionBodyEntity) { - try (FileWriter fw = - new FileWriter(PolicyController.getActionHome() + File.separator + actionBodyEntity.getActionBodyName())) { + try (FileWriter fw = new FileWriter( + PolicyController.getActionHome() + File.separator + actionBodyEntity.getActionBodyName())) { BufferedWriter bw = new BufferedWriter(fw); bw.write(actionBodyEntity.getActionBody()); bw.close(); @@ -605,14 +603,12 @@ public class PolicyExportAndImportController extends RestrictedBaseController { private void savePolicyEntity(PolicyEntity policyEntity, String configName, String userId) { if (configName != null) { if (configName.contains(config) || configName.contains(DECISION_MS)) { - ConfigurationDataEntity configuration = - (ConfigurationDataEntity) commonClassDao.getEntityItem(ConfigurationDataEntity.class, - configurationName, configName); + ConfigurationDataEntity configuration = (ConfigurationDataEntity) commonClassDao + .getEntityItem(ConfigurationDataEntity.class, configurationName, configName); policyEntity.setConfigurationData(configuration); } else { - ActionBodyEntity actionBody = - (ActionBodyEntity) commonClassDao.getEntityItem(ActionBodyEntity.class, "actionBodyName", - configName); + ActionBodyEntity actionBody = (ActionBodyEntity) commonClassDao.getEntityItem(ActionBodyEntity.class, + "actionBodyName", configName); policyEntity.setActionBodyEntity(actionBody); } } @@ -639,8 +635,9 @@ public class PolicyExportAndImportController extends RestrictedBaseController { private int getSetBodySize(PolicyEntity policyEntity, Cell cell, int setBodySize) { int setBodySizel = setBodySize; if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell)) - && ((policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName() - .contains(DECISION_MS)) && (policyEntity.getPolicyName().contains("Config_BRMS_Param_")))) { + && ((policyEntity.getPolicyName().contains(config) + || policyEntity.getPolicyName().contains(DECISION_MS)) + && (policyEntity.getPolicyName().contains("Config_BRMS_Param_")))) { setBodySizel += 1; } return setBodySizel; @@ -664,29 +661,28 @@ public class PolicyExportAndImportController extends RestrictedBaseController { boolean configurationBodySet) { boolean configurationBodySetl = configurationBodySet; if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell)) - && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS)) - && (setBodySize == bodySize)) { + && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS)) + && (setBodySize == bodySize)) { configurationBodySetl = true; } if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell)) - && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS)) - && (setBodySize == 0)) { + && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS)) + && (setBodySize == 0)) { configurationBodySetl = true; } return configurationBodySetl; } - private boolean isConfigExists(PolicyEntity policyEntity, Cell cell, boolean configExists) { boolean configExistsl = configExists; if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell)) - && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS))) { + && (policyEntity.getPolicyName().contains(config) + || policyEntity.getPolicyName().contains(DECISION_MS))) { configExistsl = true; } return configExistsl; } - private boolean isActionExists(PolicyEntity policyEntity, Cell cell, boolean actionExists) { boolean actionExistsl = actionExists; if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell)) @@ -706,17 +702,18 @@ public class PolicyExportAndImportController extends RestrictedBaseController { private StringBuilder addCellValue(PolicyEntity policyEntity, Cell cell, StringBuilder body) { if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell)) - && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS))) { + && (policyEntity.getPolicyName().contains(config) + || policyEntity.getPolicyName().contains(DECISION_MS))) { body.append(cell.getStringCellValue()); } return body; } - private ActionBodyEntity setActionBodyObject(PolicyEntity policyEntity, ActionBodyEntity actionBodyEntity, + private ActionBodyEntity setActionBodyObject(PolicyEntity policyEntity, ActionBodyEntity actionBodyEntity, Cell cell) { if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell)) - && (policyEntity.getPolicyName().contains(ACTION))) { + && (policyEntity.getPolicyName().contains(ACTION))) { actionBodyEntity.setActionBody(cell.getStringCellValue()); } return actionBodyEntity; @@ -734,7 +731,8 @@ public class PolicyExportAndImportController extends RestrictedBaseController { private ConfigurationDataEntity populateConfigurationDataEntity(PolicyEntity policyEntity, ConfigurationDataEntity configurationDataEntity, Cell cell) { if (configurationName.equalsIgnoreCase(getCellHeaderName(cell)) - && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS))) { + && (policyEntity.getPolicyName().contains(config) + || policyEntity.getPolicyName().contains(DECISION_MS))) { configurationDataEntity.setConfigurationName(cell.getStringCellValue()); } return configurationDataEntity; diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java index 707bbac09..eeff137ef 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,10 +20,14 @@ package org.onap.policy.controller; - /* * * */ +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; + import java.io.File; import java.io.IOException; import java.io.PrintWriter; @@ -46,87 +50,82 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ArrayNode; - @Controller @RequestMapping({"/"}) public class PolicyNotificationController extends RestrictedBaseController { private static Logger logger = FlexLogger.getLogger(PolicyNotificationController.class); - @Autowired - CommonClassDao commonClassDao; - - @RequestMapping(value={"/watchPolicy"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView watchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{ - StringBuilder path = new StringBuilder(); - String responseValue = ""; - try { - String userId = UserUtils.getUserSession(request).getOrgUserId(); - logger.info("userid info: " + userId); - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - String name = root.get("watchData").get("name").toString(); - JsonNode pathList = root.get("watchData").get("path"); - String finalName; - if(pathList.isArray()){ - ArrayNode arrayNode = (ArrayNode) pathList; - for (int i = 0; i < arrayNode.size(); i++) { - JsonNode individualElement = arrayNode.get(i); - if(i == 0){ - path.append(individualElement.toString().replace("\"", "").trim()); - }else{ - path.append(File.separator + individualElement.toString().replace("\"", "").trim()); - } - } - } - - if(pathList.size() > 0){ - finalName = path + File.separator + name.replace("\"", "").trim(); - }else{ - finalName = name.replace("\"", "").trim(); - } - if(finalName.contains("\\")){ - finalName = finalName.replace("\\", "\\\\"); - } - String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId"; - SimpleBindings params = new SimpleBindings(); - params.put("finalName", finalName); - params.put("userId", userId); - List<Object> watchList = commonClassDao.getDataByQuery(query, params); - if(watchList.isEmpty()){ - if(finalName.contains("\\\\")){ - finalName = finalName.replace("\\\\", File.separator); - } - WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable(); - watch.setPolicyName(finalName); - watch.setLoginIds(userId); - commonClassDao.save(watch); - responseValue = "You have Subscribed Successfully"; - }else{ - commonClassDao.delete(watchList.get(0)); - responseValue = "You have UnSubscribed Successfully"; - } - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); + @Autowired + CommonClassDao commonClassDao; + + @RequestMapping(value = {"/watchPolicy"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView watchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException { + StringBuilder path = new StringBuilder(); + String responseValue = ""; + try { + String userId = UserUtils.getUserSession(request).getOrgUserId(); + logger.info("userid info: " + userId); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + String name = root.get("watchData").get("name").toString(); + JsonNode pathList = root.get("watchData").get("path"); + String finalName; + if (pathList.isArray()) { + ArrayNode arrayNode = (ArrayNode) pathList; + for (int i = 0; i < arrayNode.size(); i++) { + JsonNode individualElement = arrayNode.get(i); + if (i == 0) { + path.append(individualElement.toString().replace("\"", "").trim()); + } else { + path.append(File.separator + individualElement.toString().replace("\"", "").trim()); + } + } + } + + if (pathList.size() > 0) { + finalName = path + File.separator + name.replace("\"", "").trim(); + } else { + finalName = name.replace("\"", "").trim(); + } + if (finalName.contains("\\")) { + finalName = finalName.replace("\\", "\\\\"); + } + String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId"; + SimpleBindings params = new SimpleBindings(); + params.put("finalName", finalName); + params.put("userId", userId); + List<Object> watchList = commonClassDao.getDataByQuery(query, params); + if (watchList.isEmpty()) { + if (finalName.contains("\\\\")) { + finalName = finalName.replace("\\\\", File.separator); + } + WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable(); + watch.setPolicyName(finalName); + watch.setLoginIds(userId); + commonClassDao.save(watch); + responseValue = "You have Subscribed Successfully"; + } else { + commonClassDao.delete(watchList.get(0)); + responseValue = "You have UnSubscribed Successfully"; + } + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(responseValue); - JSONObject j = new JSONObject("{watchData: " + responseString + "}"); - out.write(j.toString()); - return null; - }catch(Exception e){ - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - logger.error("Error druing watchPolicy function " + e); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - } - return null; - } + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(responseValue); + JSONObject j = new JSONObject("{watchData: " + responseString + "}"); + out.write(j.toString()); + return null; + } catch (Exception e) { + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + logger.error("Error druing watchPolicy function " + e); + PrintWriter out = response.getWriter(); + out.write(PolicyUtils.CATCH_EXCEPTION); + } + return null; + } } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java index b02da1996..29fdecdaa 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java @@ -20,6 +20,12 @@ package org.onap.policy.controller; +import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; @@ -45,12 +51,6 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; -import com.fasterxml.jackson.annotation.PropertyAccessor; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - @Controller @RequestMapping("/") public class PolicyRolesController extends RestrictedBaseController { @@ -69,11 +69,13 @@ public class PolicyRolesController extends RestrictedBaseController { /** * Gets the policy roles entity data. * - * @param request the request + * @param request the request * @param response the response */ - @RequestMapping(value = { "/get_RolesData" }, method = { - org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) + @RequestMapping( + value = {"/get_RolesData"}, + method = {org.springframework.web.bind.annotation.RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) public void getPolicyRolesEntityData(HttpServletRequest request, HttpServletResponse response) { try { Map<String, Object> model = new HashMap<>(); @@ -90,12 +92,13 @@ public class PolicyRolesController extends RestrictedBaseController { /** * Save roles and Mechid entity data. * - * @param request the request + * @param request the request * @param response the response * @return the model and view */ - @RequestMapping(value = { "/save_NonSuperRolesData" }, method = { - org.springframework.web.bind.annotation.RequestMethod.POST }) + @RequestMapping( + value = {"/save_NonSuperRolesData"}, + method = {org.springframework.web.bind.annotation.RequestMethod.POST}) public ModelAndView SaveRolesEntityData(HttpServletRequest request, HttpServletResponse response) { try { StringBuilder scopeName = new StringBuilder(); @@ -164,11 +167,13 @@ public class PolicyRolesController extends RestrictedBaseController { /** * Gets the policy scopes entity data. * - * @param request the request + * @param request the request * @param response the response */ - @RequestMapping(value = { "/get_PolicyRolesScopeData" }, method = { - org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) + @RequestMapping( + value = {"/get_PolicyRolesScopeData"}, + method = {org.springframework.web.bind.annotation.RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) public void getPolicyScopesEntityData(HttpServletRequest request, HttpServletResponse response) { try { scopelist = new ArrayList<>(); @@ -186,6 +191,7 @@ public class PolicyRolesController extends RestrictedBaseController { } } + class ReadScopes { private int id; private UserInfo loginId; diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java index fca1096ff..fc94087fc 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,7 @@ package org.onap.policy.controller; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.io.PrintWriter; @@ -40,40 +41,39 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.databind.ObjectMapper; - @Controller @RequestMapping("/") public class PolicyValidationController extends RestrictedBaseController { - private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidationController.class); + private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidationController.class); + + @RequestMapping( + value = {"/policyController/validate_policy.htm"}, + method = {org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView validatePolicy(HttpServletRequest request, HttpServletResponse response) throws IOException { + try { + + PolicyValidation validation = new PolicyValidation(); + PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper(); + StringBuilder responseString; + ObjectMapper mapper = new ObjectMapper(); - @RequestMapping(value={"/policyController/validate_policy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView validatePolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{ - try{ - - PolicyValidation validation = new PolicyValidation(); - PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper(); - StringBuilder responseString; - ObjectMapper mapper = new ObjectMapper(); + PolicyRestAdapter policyData = wrapper.populateRequestParameters(request); + responseString = validation.validatePolicy(policyData); - PolicyRestAdapter policyData = wrapper.populateRequestParameters(request); - responseString = validation.validatePolicy(policyData); - - PrintWriter out = response.getWriter(); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(responseString.toString())); - JSONObject j = new JSONObject(msg); - out.write(j.toString()); + PrintWriter out = response.getWriter(); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(responseString.toString())); + JSONObject j = new JSONObject(msg); + out.write(j.toString()); - return null; - } - catch (Exception e){ - LOGGER.error("Exception Occured During Policy Validation" +e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - } - return null; - } -}
\ No newline at end of file + return null; + } catch (Exception e) { + LOGGER.error("Exception Occured During Policy Validation" + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(PolicyUtils.CATCH_EXCEPTION); + } + return null; + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/dao/SystemLogDbDao.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/dao/SystemLogDbDao.java index 9cc6314dd..3c3f4d397 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/dao/SystemLogDbDao.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/dao/SystemLogDbDao.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,14 +20,12 @@ package org.onap.policy.dao; - import java.util.List; import org.onap.policy.rest.jpa.SystemLogDB; - - public abstract interface SystemLogDbDao { - public abstract List<SystemLogDB> getLoggingData(); - public abstract List<SystemLogDB> getSystemAlertData(); + public abstract List<SystemLogDB> getLoggingData(); + + public abstract List<SystemLogDB> getSystemAlertData(); } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java index 170c30838..abd7f0e22 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,368 +48,356 @@ import org.springframework.stereotype.Service; @Service("CommonClassDao") @Primary -public class CommonClassDaoImpl implements CommonClassDao{ +public class CommonClassDaoImpl implements CommonClassDao { + + private static final Logger LOGGER = FlexLogger.getLogger(CommonClassDaoImpl.class); + private static SessionFactory sessionfactory; - private static final Logger LOGGER = FlexLogger.getLogger(CommonClassDaoImpl.class); - private static SessionFactory sessionfactory; - public static SessionFactory getSessionfactory() { - return sessionfactory; + return sessionfactory; } public static void setSessionfactory(SessionFactory sessionfactory) { - CommonClassDaoImpl.sessionfactory = sessionfactory; + CommonClassDaoImpl.sessionfactory = sessionfactory; } @Autowired - private CommonClassDaoImpl(SessionFactory sessionfactory){ - CommonClassDaoImpl.sessionfactory = sessionfactory; - } - - public CommonClassDaoImpl(){ - //Default Constructor + private CommonClassDaoImpl(SessionFactory sessionfactory) { + CommonClassDaoImpl.sessionfactory = sessionfactory; } - - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Override - public List<Object> getData(Class className) { - Session session = sessionfactory.openSession(); - List<Object> data = null; - try{ - Criteria cr = session.createCriteria(className); - data = cr.list(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e); - } - } - return data; - } - - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public List<Object> getDataById(Class className, String columnName, String key) { - Session session = sessionfactory.openSession(); - List<Object> data = null; - try { - Criteria cr = session.createCriteria(className); - if(columnName.contains(":") && key.contains(":")){ - String[] columns = columnName.split(":"); - String[] keys = key.split(":"); - for(int i=0; i < columns.length; i++){ - cr.add(Restrictions.eq(columns[i], keys[i])); - } - }else{ - cr.add(Restrictions.eq(columnName, key)); - } - data = cr.list(); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - return data; - } - - @Override - public void save(Object entity) { - Session session = sessionfactory.openSession(); - Transaction tx = session.beginTransaction(); - try { - session.persist(entity); - tx.commit(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving data to Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - - } - - @Override - public void delete(Object entity) { - Session session = sessionfactory.openSession(); - Transaction tx = session.beginTransaction(); - try { - session.delete(entity); - tx.commit(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting data from Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - - } - - - @Override - public void update(Object entity) { - Session session = sessionfactory.openSession(); - Transaction tx = session.beginTransaction(); - try { - session.update(entity); - tx.commit(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating data to Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - - } - + public CommonClassDaoImpl() { + // Default Constructor + } - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Override - public List<Object> checkDuplicateEntry(String value, String columnName, Class className) { - Session session = sessionfactory.openSession(); - Transaction tx = session.beginTransaction(); - List<Object> data = null; - String[] columnNames = null; - if(columnName != null && columnName.contains(":")){ - columnNames = columnName.split(":"); - } - String[] values = null; - if(value != null && value.contains(":")){ - values = value.split(":"); - } - try { - Criteria cr = session.createCriteria(className); - if(columnNames != null && values != null && columnNames.length == values.length){ - for (int i = 0; i < columnNames.length; i++){ - cr.add(Restrictions.eq(columnNames[i],values[i])); - } - }else{ - cr.add(Restrictions.eq(columnName,value)); - } - data = cr.list(); - tx.commit(); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying for Duplicate Entries for Table"+e + className); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - return data; - } + @SuppressWarnings({"unchecked", "rawtypes"}) + @Override + public List<Object> getData(Class className) { + Session session = sessionfactory.openSession(); + List<Object> data = null; + try { + Criteria cr = session.createCriteria(className); + data = cr.list(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table" + e); + } finally { + try { + session.close(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e); + } + } + return data; + } + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public List<Object> getDataById(Class className, String columnName, String key) { + Session session = sessionfactory.openSession(); + List<Object> data = null; + try { + Criteria cr = session.createCriteria(className); + if (columnName.contains(":") && key.contains(":")) { + String[] columns = columnName.split(":"); + String[] keys = key.split(":"); + for (int i = 0; i < columns.length; i++) { + cr.add(Restrictions.eq(columns[i], keys[i])); + } + } else { + cr.add(Restrictions.eq(columnName, key)); + } + data = cr.list(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table" + e); + } finally { + try { + session.close(); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); + } + } + return data; + } - @SuppressWarnings("unchecked") - @Override - public List<PolicyRoles> getUserRoles() { - Session session = sessionfactory.openSession(); - Transaction tx = session.beginTransaction(); - List<PolicyRoles> rolesData = null; - try { - Criteria cr = session.createCriteria(PolicyRoles.class); - Disjunction disjunction = Restrictions.disjunction(); - Conjunction conjunction1 = Restrictions.conjunction(); - conjunction1.add(Restrictions.eq("role", "admin")); - Conjunction conjunction2 = Restrictions.conjunction(); - conjunction2.add(Restrictions.eq("role", "editor")); - Conjunction conjunction3 = Restrictions.conjunction(); - conjunction3.add(Restrictions.eq("role", "guest")); - disjunction.add(conjunction1); - disjunction.add(conjunction2); - disjunction.add(conjunction3); - rolesData = cr.add(disjunction).list(); - tx.commit(); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PolicyRoles Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - return rolesData; - } + @Override + public void save(Object entity) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.persist(entity); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving data to Table" + e); + } finally { + try { + session.close(); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); + } + } + } - @Override - public List<Object> checkExistingGroupListforUpdate(String arg0, String arg1) { - return Collections.emptyList(); - } + @Override + public void delete(Object entity) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.delete(entity); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting data from Table" + e); + } finally { + try { + session.close(); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); + } + } + } - @Override - public void deleteAll() {} + @Override + public void update(Object entity) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.update(entity); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating data to Table" + e); + } finally { + try { + session.close(); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); + } + } - - @SuppressWarnings("unchecked") - @Override - public List<Object> getDataByQuery(String query, SimpleBindings params) { - Session session = sessionfactory.openSession(); - Transaction tx = session.beginTransaction(); - List<Object> data = null; - try { - Query hbquery = session.createQuery(query); - for (Map.Entry<String, Object> paramPair : params.entrySet()) { - if(paramPair.getValue() instanceof java.lang.Long){ - hbquery.setLong(paramPair.getKey(), (long) paramPair.getValue()); - } - else{ - hbquery.setParameter(paramPair.getKey(), paramPair.getValue()); - } - } - data = hbquery.list(); - tx.commit(); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table"+e); - throw e; - }finally{ - try{ - session.close(); - }catch(HibernateException e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - return data; - } + } + @SuppressWarnings({"unchecked", "rawtypes"}) + @Override + public List<Object> checkDuplicateEntry(String value, String columnName, Class className) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<Object> data = null; + String[] columnNames = null; + if (columnName != null && columnName.contains(":")) { + columnNames = columnName.split(":"); + } + String[] values = null; + if (value != null && value.contains(":")) { + values = value.split(":"); + } + try { + Criteria cr = session.createCriteria(className); + if (columnNames != null && values != null && columnNames.length == values.length) { + for (int i = 0; i < columnNames.length; i++) { + cr.add(Restrictions.eq(columnNames[i], values[i])); + } + } else { + cr.add(Restrictions.eq(columnName, value)); + } + data = cr.list(); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying for Duplicate Entries for Table" + + e + className); + } finally { + try { + session.close(); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); + } + } + return data; + } - @SuppressWarnings("rawtypes") - @Override - public Object getEntityItem(Class className, String columnName, String key) { - Session session = sessionfactory.openSession(); - Transaction tx = session.beginTransaction(); - Object data = null; - try { - Criteria cr = session.createCriteria(className); - if(columnName.contains(":") && key.contains(":")){ - String[] columns = columnName.split(":"); - String[] keys = key.split(":"); - for(int i=0; i < columns.length; i++){ - cr.add(Restrictions.eq(columns[i], keys[i])); - } - }else{ - cr.add(Restrictions.eq(columnName, key)); - } - data = cr.list().get(0); - tx.commit(); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - return data; - } + @SuppressWarnings("unchecked") + @Override + public List<PolicyRoles> getUserRoles() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<PolicyRoles> rolesData = null; + try { + Criteria cr = session.createCriteria(PolicyRoles.class); + Disjunction disjunction = Restrictions.disjunction(); + Conjunction conjunction1 = Restrictions.conjunction(); + conjunction1.add(Restrictions.eq("role", "admin")); + Conjunction conjunction2 = Restrictions.conjunction(); + conjunction2.add(Restrictions.eq("role", "editor")); + Conjunction conjunction3 = Restrictions.conjunction(); + conjunction3.add(Restrictions.eq("role", "guest")); + disjunction.add(conjunction1); + disjunction.add(conjunction2); + disjunction.add(conjunction3); + rolesData = cr.add(disjunction).list(); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PolicyRoles Table" + e); + } finally { + try { + session.close(); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); + } + } + return rolesData; + } + @Override + public List<Object> checkExistingGroupListforUpdate(String arg0, String arg1) { + return Collections.emptyList(); + } - @Override - public void updateClAlarms(String arg0, String arg1) {} + @Override + public void deleteAll() { + } + @SuppressWarnings("unchecked") + @Override + public List<Object> getDataByQuery(String query, SimpleBindings params) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<Object> data = null; + try { + Query hbquery = session.createQuery(query); + for (Map.Entry<String, Object> paramPair : params.entrySet()) { + if (paramPair.getValue() instanceof java.lang.Long) { + hbquery.setLong(paramPair.getKey(), (long) paramPair.getValue()); + } else { + hbquery.setParameter(paramPair.getKey(), paramPair.getValue()); + } + } + data = hbquery.list(); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table" + e); + throw e; + } finally { + try { + session.close(); + } catch (HibernateException e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); + } + } + return data; + } - @Override - public void updateClYaml(String arg0, String arg1) {} + @SuppressWarnings("rawtypes") + @Override + public Object getEntityItem(Class className, String columnName, String key) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + Object data = null; + try { + Criteria cr = session.createCriteria(className); + if (columnName.contains(":") && key.contains(":")) { + String[] columns = columnName.split(":"); + String[] keys = key.split(":"); + for (int i = 0; i < columns.length; i++) { + cr.add(Restrictions.eq(columns[i], keys[i])); + } + } else { + cr.add(Restrictions.eq(columnName, key)); + } + data = cr.list().get(0); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table" + e); + } finally { + try { + session.close(); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); + } + } + return data; + } + @Override + public void updateClAlarms(String arg0, String arg1) { + } - @Override - public void updateQuery(String query) { - Session session = sessionfactory.openSession(); - Transaction tx = session.beginTransaction(); - try { - Query hbquery = session.createQuery(query); - hbquery.executeUpdate(); - tx.commit(); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating Database Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - - } + @Override + public void updateClYaml(String arg0, String arg1) { + } + @Override + public void updateQuery(String query) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + Query hbquery = session.createQuery(query); + hbquery.executeUpdate(); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating Database Table" + e); + } finally { + try { + session.close(); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); + } + } - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public List<String> getDataByColumn(Class className, String columnName) { - Session session = sessionfactory.openSession(); - List<String> data = null; - try{ - Criteria cr = session.createCriteria(className); - cr.setProjection(Projections.property(columnName)); - data = cr.list(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e); - } - } - return data; - } + } + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public List<String> getDataByColumn(Class className, String columnName) { + Session session = sessionfactory.openSession(); + List<String> data = null; + try { + Criteria cr = session.createCriteria(className); + cr.setProjection(Projections.property(columnName)); + data = cr.list(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table" + e); + } finally { + try { + session.close(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e); + } + } + return data; + } - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public List<Object> getMultipleDataOnAddingConjunction(Class className, String columnName, List<String> data) { - Session session = sessionfactory.openSession(); - Transaction tx = session.beginTransaction(); - List<Object> entityData = null; - try { - Criteria cr = session.createCriteria(className); - Disjunction disjunction = Restrictions.disjunction(); - List<Conjunction> conjunctionList = new ArrayList<>(); - String[] columNames = columnName.split(":"); - for(int i =0; i < data.size(); i++){ - String[] entiySplit = data.get(i).split(":"); - Conjunction conjunction = Restrictions.conjunction(); - conjunction.add(Restrictions.eq(columNames[0], entiySplit[0])); - conjunction.add(Restrictions.eq(columNames[1], entiySplit[1])); - conjunctionList.add(conjunction); - } - for(int j =0 ; j < conjunctionList.size(); j++){ - disjunction.add(conjunctionList.get(j)); - } - entityData = cr.add(disjunction).list(); - tx.commit(); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table" +className +e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - return entityData; - } + @SuppressWarnings({"rawtypes", "unchecked"}) + @Override + public List<Object> getMultipleDataOnAddingConjunction(Class className, String columnName, List<String> data) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List<Object> entityData = null; + try { + Criteria cr = session.createCriteria(className); + Disjunction disjunction = Restrictions.disjunction(); + List<Conjunction> conjunctionList = new ArrayList<>(); + String[] columNames = columnName.split(":"); + for (int i = 0; i < data.size(); i++) { + String[] entiySplit = data.get(i).split(":"); + Conjunction conjunction = Restrictions.conjunction(); + conjunction.add(Restrictions.eq(columNames[0], entiySplit[0])); + conjunction.add(Restrictions.eq(columNames[1], entiySplit[1])); + conjunctionList.add(conjunction); + } + for (int j = 0; j < conjunctionList.size(); j++) { + disjunction.add(conjunctionList.get(j)); + } + entityData = cr.add(disjunction).list(); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table" + className + e); + } finally { + try { + session.close(); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); + } + } + return entityData; + } } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/SystemLogDbDaoImpl.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/SystemLogDbDaoImpl.java index 1727f47c0..768a7a41c 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/SystemLogDbDaoImpl.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/SystemLogDbDaoImpl.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,85 +20,83 @@ package org.onap.policy.daoImp; - import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; -import org.springframework.stereotype.Service; - -import org.onap.policy.xacml.api.XACMLErrorConstants; - import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.conf.HibernateSession; import org.onap.policy.controller.PolicyController; import org.onap.policy.dao.SystemLogDbDao; import org.onap.policy.rest.jpa.SystemLogDB; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; - +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.stereotype.Service; @Service("SystemLogDbDao") public class SystemLogDbDaoImpl implements SystemLogDbDao { - private static final Logger logger = FlexLogger.getLogger(SystemLogDbDaoImpl.class); - - @SuppressWarnings("unchecked") - @Override - public List<SystemLogDB> getLoggingData() { - Session session = HibernateSession.getSession(); - Transaction tx = session.beginTransaction(); - List<SystemLogDB> system = null; + private static final Logger logger = FlexLogger.getLogger(SystemLogDbDaoImpl.class); + + @SuppressWarnings("unchecked") + @Override + public List<SystemLogDB> getLoggingData() { + Session session = HibernateSession.getSession(); + Transaction tx = session.beginTransaction(); + List<SystemLogDB> system = null; try { - String sqlWhere = null; - if(PolicyController.isjUnit()){ - sqlWhere = ""; - }else{ - sqlWhere = "date > DATE_SUB(curdate(), INTERVAL 5 DAY) ORDER BY date DESC limit "+PolicyController.getLogTableLimit()+""; - } - Criteria cr = session.createCriteria(SystemLogDB.class); - cr.add(Restrictions.sqlRestriction(sqlWhere)); + String sqlWhere = null; + if (PolicyController.isjUnit()) { + sqlWhere = ""; + } else { + sqlWhere = "date > DATE_SUB(curdate(), INTERVAL 5 DAY) ORDER BY date DESC limit " + + PolicyController.getLogTableLimit() + ""; + } + Criteria cr = session.createCriteria(SystemLogDB.class); + cr.add(Restrictions.sqlRestriction(sqlWhere)); system = cr.list(); - tx.commit(); - } catch (Exception e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying SystemLogDB Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - return system; - } + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying SystemLogDB Table" + e); + } finally { + try { + session.close(); + } catch (Exception e1) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); + } + } + return system; + } - @SuppressWarnings("unchecked") - @Override - public List<SystemLogDB> getSystemAlertData() { - Session session = HibernateSession.getSession(); - Transaction tx = session.beginTransaction(); - List<SystemLogDB> system = null; + @SuppressWarnings("unchecked") + @Override + public List<SystemLogDB> getSystemAlertData() { + Session session = HibernateSession.getSession(); + Transaction tx = session.beginTransaction(); + List<SystemLogDB> system = null; try { - String sqlWhere = null; - if(PolicyController.isjUnit()){ - sqlWhere = ""; - }else{ - sqlWhere = "date > DATE_SUB(curdate(), INTERVAL 5 DAY) and logtype = 'error' ORDER BY date DESC limit "+PolicyController.getSystemAlertTableLimit()+""; - } - Criteria cr = session.createCriteria(SystemLogDB.class); - cr.add(Restrictions.sqlRestriction(sqlWhere)); + String sqlWhere = null; + if (PolicyController.isjUnit()) { + sqlWhere = ""; + } else { + sqlWhere = "date > DATE_SUB(curdate(), INTERVAL 5 DAY) and logtype = 'error' ORDER BY date DESC limit " + + PolicyController.getSystemAlertTableLimit() + ""; + } + Criteria cr = session.createCriteria(SystemLogDB.class); + cr.add(Restrictions.sqlRestriction(sqlWhere)); system = cr.list(); - tx.commit(); - } catch (Exception e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying SystemLogDB Table"+e); - }finally{ - try{ - session.close(); - }catch(Exception e1){ - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); - } - } - return system; - } + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying SystemLogDB Table" + e); + } finally { + try { + session.close(); + } catch (Exception e1) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); + } + } + return system; + } } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java index e6c375808..c02d3b1d6 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java @@ -20,8 +20,8 @@ package org.onap.policy.model; - import com.att.research.xacml.api.pap.PAPException; + import java.awt.Checkbox; import java.util.ArrayList; import java.util.Collection; @@ -29,6 +29,7 @@ import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Set; + import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.rest.util.PolicyContainer; diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/model/Roles.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/Roles.java index 2f051f7b4..baaecaee6 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/model/Roles.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/Roles.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,7 @@ package org.onap.policy.model; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.io.Serializable; @@ -31,69 +32,69 @@ import javax.persistence.Id; import javax.persistence.NamedQuery; import javax.persistence.Table; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - @Entity -@Table(name="Roles") -@NamedQuery(name="Roles.findAll", query="SELECT r FROM Roles r ") -@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) -public class Roles implements Serializable{ - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - - @Column(name="id") - private int id; - - @Column(name="loginId") - private String loginId; - - private String name; - private String scope; - private String role; - - public Roles(){ - // Empty constructor - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public String getLoginId() { - return this.loginId; - } - - public void setLoginId(String loginId) { - this.loginId = loginId; - - } - public String getScope() { - return this.scope; - } - - public void setScope(String scope) { - this.scope = scope; - - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - public String getRole() { - return this.role; - } - - public void setRole(String role) { - this.role = role; - } +@Table(name = "Roles") +@NamedQuery(name = "Roles.findAll", query = "SELECT r FROM Roles r ") +@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) +public class Roles implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + + @Column(name = "id") + private int id; + + @Column(name = "loginId") + private String loginId; + + private String name; + private String scope; + private String role; + + public Roles() { + // Empty constructor + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public String getLoginId() { + return this.loginId; + } + + public void setLoginId(String loginId) { + this.loginId = loginId; + + } + + public String getScope() { + return this.scope; + } + + public void setScope(String scope) { + this.scope = scope; + + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getRole() { + return this.role; + } + + public void setRole(String role) { + this.role = role; + } } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/UserUtils.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/UserUtils.java index 40c839676..22c44863b 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/UserUtils.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/UserUtils.java @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.utils; import java.util.ArrayList; @@ -95,7 +96,7 @@ public final class UserUtils { /** * Read non super role scopes and add to map. * - * @param userRole Role Object. + * @param userRole Role Object. * @param rolesList roleList Object. * @return return the map<scope, role>. */ |