diff options
author | Pamela Dragosh <pdragosh@research.att.com> | 2019-10-04 17:03:28 -0400 |
---|---|---|
committer | Pamela Dragosh <pdragosh@research.att.com> | 2019-10-07 09:46:23 -0400 |
commit | dfd9c0a09c35e4b5b4b61be08b8424e4a3d0d500 (patch) | |
tree | 6831a6f6deb3e9f7f9d503893927c1f9aa6201a8 | |
parent | ffd7241c7bfa8d8b68b504406fc6ed4cc299ffe6 (diff) |
Format java POLICY-SDK-APP
As a result of doing command maven reformat, these files are
now changed.
Updated licenses.
Issue-ID: POLICY-2133
Change-Id: I19a8dd70eb10c0d879b97635f7780ab7f92a1753
Signed-off-by: Pamela Dragosh <pdragosh@research.att.com>
58 files changed, 3250 insertions, 2924 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>. */ diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/CheckPDPTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/CheckPDPTest.java index a06afc997..358b69f1f 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/CheckPDPTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/CheckPDPTest.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 Samsung * ================================================================================ @@ -19,13 +19,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.admin; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; + import java.io.File; + import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; @@ -40,33 +43,26 @@ public class CheckPDPTest { assertFalse(CheckPDP.validateID("http://localhost:8082/pdp/")); System.setProperty("xacml.rest.pdp.idfile", - new File(".").getCanonicalPath() + File.separator + "src" + File.separator - + "test" + File.separator + "resources" + File.separator - + "idonotexist.properties"); + new File(".").getCanonicalPath() + File.separator + "src" + File.separator + "test" + File.separator + + "resources" + File.separator + "idonotexist.properties"); assertFalse(CheckPDP.validateID("http://localhost:8082/pdp/")); System.setProperty("xacml.rest.pdp.idfile", - new File(".").getCanonicalPath() + File.separator + "src" + File.separator - + "test" + File.separator + "resources" + File.separator - + "doesnothaveproperties.atall"); + new File(".").getCanonicalPath() + File.separator + "src" + File.separator + "test" + File.separator + + "resources" + File.separator + "doesnothaveproperties.atall"); assertFalse(CheckPDP.validateID("http://localhost:8082/pdp/")); - System.setProperty("xacml.rest.pdp.idfile", - new File(".").getCanonicalPath() + File.separator + "src" + File.separator - + "test" + File.separator + "resources" + File.separator - + "testbad.properties"); + System.setProperty("xacml.rest.pdp.idfile", new File(".").getCanonicalPath() + File.separator + "src" + + File.separator + "test" + File.separator + "resources" + File.separator + "testbad.properties"); assertFalse(CheckPDP.validateID("http://localhost:8082/pdp/")); - System.setProperty("xacml.rest.pdp.idfile", - new File(".").getCanonicalPath() + File.separator + "src" + File.separator - + "test" + File.separator + "resources" + File.separator - + "empty.properties"); + System.setProperty("xacml.rest.pdp.idfile", new File(".").getCanonicalPath() + File.separator + "src" + + File.separator + "test" + File.separator + "resources" + File.separator + "empty.properties"); assertFalse(CheckPDP.validateID("http://localhost:8082/pdp/")); System.setProperty("xacml.rest.pdp.idfile", - new File(".").getCanonicalPath() + File.separator + "src" + File.separator - + "test" + File.separator + "resources" + File.separator - + "testnotenoughvalues.properties"); + new File(".").getCanonicalPath() + File.separator + "src" + File.separator + "test" + File.separator + + "resources" + File.separator + "testnotenoughvalues.properties"); assertFalse(CheckPDP.validateID("http://localhost:8082/pdp/")); assertNull(CheckPDP.getPdpMap()); @@ -80,14 +76,11 @@ public class CheckPDPTest { @Test public final void test2CheckPDP() { try { - System.setProperty("xacml.rest.pdp.idfile", - new File(".").getCanonicalPath() + File.separator + "src" + File.separator - + "test" + File.separator + "resources" + File.separator - + "test.properties"); + System.setProperty("xacml.rest.pdp.idfile", new File(".").getCanonicalPath() + File.separator + "src" + + File.separator + "test" + File.separator + "resources" + File.separator + "test.properties"); assertTrue(CheckPDP.validateID("http://localhost:8082/pdp/")); assertTrue(CheckPDP.getPdpMap().containsKey("http://localhost:8082/pdp/")); - assertTrue(CheckPDP.getEncoding("http://localhost:8082/pdp/") - .equals("dGVzdHBkcDphbHBoYTQ1Ng==")); + assertTrue(CheckPDP.getEncoding("http://localhost:8082/pdp/").equals("dGVzdHBkcDphbHBoYTQ1Ng==")); } catch (Exception e) { fail("Error occured in CheckPDP test"); } diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyManagerServletTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyManagerServletTest.java index 7bd3be440..0325c8d8f 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyManagerServletTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyManagerServletTest.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 Samsung * ================================================================================ @@ -19,19 +19,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.admin; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; + import java.io.BufferedReader; import java.io.File; import java.io.StringReader; import java.util.ArrayList; import java.util.Collections; import java.util.List; + import javax.servlet.ServletConfig; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; + import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Test; @@ -98,8 +102,7 @@ public class PolicyManagerServletTest extends Mockito { String policyContent = ""; try { ClassLoader classLoader = getClass().getClassLoader(); - policyContent = IOUtils - .toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml")); + policyContent = IOUtils.toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml")); } catch (Exception e1) { logger.error("Exception Occured" + e1); } @@ -141,8 +144,7 @@ public class PolicyManagerServletTest extends Mockito { HttpSession mockSession = mock(HttpSession.class); User user = new User(); user.setOrgUserId("Test"); - Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))) - .thenReturn(user); + Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))).thenReturn(user); Mockito.when(request.getSession(false)).thenReturn(mockSession); commonClassDao = mock(CommonClassDao.class); @@ -153,14 +155,11 @@ public class PolicyManagerServletTest extends Mockito { PolicyManagerServlet servlet = new PolicyManagerServlet(); ServletConfig servletConfig = mock(ServletConfig.class); try { - when(servletConfig.getInitParameterNames()) - .thenReturn(Collections.enumeration(headers)); - when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")) - .thenReturn("xacml.admin.properties"); + when(servletConfig.getInitParameterNames()).thenReturn(Collections.enumeration(headers)); + when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")).thenReturn("xacml.admin.properties"); System.setProperty("xacml.rest.admin.closedLoopJSON", - new File(".").getCanonicalPath() + File.separator + "src" + File.separator - + "test" + File.separator + "resources" + File.separator - + "JSONConfig.json"); + new File(".").getCanonicalPath() + File.separator + "src" + File.separator + "test" + File.separator + + "resources" + File.separator + "JSONConfig.json"); servlet.init(servletConfig); assertTrue(PolicyManagerServlet.getServiceTypeNamesList().size() > 0); @@ -177,14 +176,11 @@ public class PolicyManagerServletTest extends Mockito { PolicyManagerServlet servlet = new PolicyManagerServlet(); ServletConfig servletConfig = mock(ServletConfig.class); try { - when(servletConfig.getInitParameterNames()) - .thenReturn(Collections.enumeration(headers)); - when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")) - .thenReturn("xacml.admin.properties"); + when(servletConfig.getInitParameterNames()).thenReturn(Collections.enumeration(headers)); + when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")).thenReturn("xacml.admin.properties"); System.setProperty("xacml.rest.admin.closedLoopJSON", - new File(".").getCanonicalPath() + File.separator + "src" + File.separator - + "test" + File.separator + "resources" + File.separator - + "JSONConfig.foo"); + new File(".").getCanonicalPath() + File.separator + "src" + File.separator + "test" + File.separator + + "resources" + File.separator + "JSONConfig.foo"); servlet.init(servletConfig); } catch (Exception e1) { logger.error("Exception Occured" + e1); @@ -197,14 +193,11 @@ public class PolicyManagerServletTest extends Mockito { PolicyManagerServlet servlet = new PolicyManagerServlet(); ServletConfig servletConfig = mock(ServletConfig.class); try { - when(servletConfig.getInitParameterNames()) - .thenReturn(Collections.enumeration(headers)); - when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")) - .thenReturn("xacml.admin.properties"); + when(servletConfig.getInitParameterNames()).thenReturn(Collections.enumeration(headers)); + when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")).thenReturn("xacml.admin.properties"); System.setProperty("xacml.rest.admin.closedLoopJSON", - new File(".").getCanonicalPath() + File.separator + "src" + File.separator - + "test" + File.separator + "resources" + File.separator - + "IDonotExist.json"); + new File(".").getCanonicalPath() + File.separator + "src" + File.separator + "test" + File.separator + + "resources" + File.separator + "IDonotExist.json"); servlet.init(servletConfig); } catch (Exception e1) { logger.error("Exception Occured" + e1); @@ -217,8 +210,8 @@ public class PolicyManagerServletTest extends Mockito { public void testDescribePolicy() { PolicyManagerServlet servlet = new PolicyManagerServlet(); PolicyController controller = mock(PolicyController.class); - BufferedReader reader = new BufferedReader(new StringReader( - "{params: { mode: 'DESCRIBEPOLICYFILE', path: 'com.Config_SampleTest1206.1.xml'}}")); + BufferedReader reader = new BufferedReader( + new StringReader("{params: { mode: 'DESCRIBEPOLICYFILE', path: 'com.Config_SampleTest1206.1.xml'}}")); try { when(request.getReader()).thenReturn(reader); String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0"; @@ -231,7 +224,6 @@ public class PolicyManagerServletTest extends Mockito { } } - @SuppressWarnings("static-access") @Test public void testPolicyScopeList() { @@ -245,14 +237,11 @@ public class PolicyManagerServletTest extends Mockito { try { when(request.getReader()).thenReturn(reader); when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery("from PolicyEditorScopes", null)) + when(controller.getDataByQuery("from PolicyEditorScopes", null)).thenReturn(policyEditorScopes); + when(controller.getDataByQuery("from PolicyEditorScopes where SCOPENAME like :scopeName", null)) .thenReturn(policyEditorScopes); - when(controller.getDataByQuery( - "from PolicyEditorScopes where SCOPENAME like :scopeName", null)) - .thenReturn(policyEditorScopes); - when(controller.getDataByQuery( - "from PolicyVersion where POLICY_NAME like :scopeName", null)) - .thenReturn(policyVersion); + when(controller.getDataByQuery("from PolicyVersion where POLICY_NAME like :scopeName", null)) + .thenReturn(policyVersion); servlet.setPolicyController(controller); servlet.setTestUserId("Test"); servlet.doPost(request, response); @@ -269,16 +258,14 @@ public class PolicyManagerServletTest extends Mockito { PolicyManagerServlet servlet = new PolicyManagerServlet(); PolicyController controller = mock(PolicyController.class); List<String> list = new ArrayList<>(); - list.add( - "{params: { mode: 'EDITFILE', path: '/com/Config_SampleTest1206.1.xml', onlyFolders: false}}"); + list.add("{params: { mode: 'EDITFILE', path: '/com/Config_SampleTest1206.1.xml', onlyFolders: false}}"); for (int i = 0; i < list.size(); i++) { BufferedReader reader = new BufferedReader(new StringReader(list.get(i))); try { when(request.getReader()).thenReturn(reader); when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery( - "FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null)) - .thenReturn(basePolicyData); + when(controller.getDataByQuery("FROM PolicyEntity where policyName = :split_1 and scope = :split_0", + null)).thenReturn(basePolicyData); servlet.setPolicyController(controller); servlet.setTestUserId("Test"); servlet.doPost(request, response); @@ -297,10 +284,10 @@ public class PolicyManagerServletTest extends Mockito { String configData = ""; try { ClassLoader classLoader = getClass().getClassLoader(); - policyContent = IOUtils.toString(classLoader - .getResourceAsStream("Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml")); - configData = IOUtils.toString(classLoader - .getResourceAsStream("com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt")); + policyContent = + IOUtils.toString(classLoader.getResourceAsStream("Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml")); + configData = IOUtils + .toString(classLoader.getResourceAsStream("com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt")); } catch (Exception e1) { logger.error("Exception Occured" + e1); } @@ -311,25 +298,22 @@ public class PolicyManagerServletTest extends Mockito { ConfigurationDataEntity configurationEntity = new ConfigurationDataEntity(); configurationEntity.setConfigBody(configData); configurationEntity.setConfigType("OTHER"); - configurationEntity - .setConfigurationName("com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt"); + configurationEntity.setConfigurationName("com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt"); configurationEntity.setDescription("test"); entity.setConfigurationData(configurationEntity); policyData.add(entity); PolicyManagerServlet servlet = new PolicyManagerServlet(); PolicyController controller = mock(PolicyController.class); List<String> list = new ArrayList<>(); - list.add( - "{params: { mode: 'EDITFILE', path: '/com/Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml'," - + " onlyFolders: false}}"); + list.add("{params: { mode: 'EDITFILE', path: '/com/Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml'," + + " onlyFolders: false}}"); for (int i = 0; i < list.size(); i++) { BufferedReader reader = new BufferedReader(new StringReader(list.get(i))); try { when(request.getReader()).thenReturn(reader); when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery( - "FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null)) - .thenReturn(policyData); + when(controller.getDataByQuery("FROM PolicyEntity where policyName = :split_1 and scope = :split_0", + null)).thenReturn(policyData); servlet.setPolicyController(controller); servlet.setTestUserId("Test"); servlet.doPost(request, response); @@ -348,10 +332,10 @@ public class PolicyManagerServletTest extends Mockito { String configData = ""; try { ClassLoader classLoader = getClass().getClassLoader(); - policyContent = IOUtils.toString( - classLoader.getResourceAsStream("Config_BRMS_Raw_TestBRMSRawPolicy.1.xml")); - configData = IOUtils.toString( - classLoader.getResourceAsStream("com.Config_BRMS_Raw_TestBRMSRawPolicy.1.txt")); + policyContent = + IOUtils.toString(classLoader.getResourceAsStream("Config_BRMS_Raw_TestBRMSRawPolicy.1.xml")); + configData = + IOUtils.toString(classLoader.getResourceAsStream("com.Config_BRMS_Raw_TestBRMSRawPolicy.1.txt")); } catch (Exception e1) { logger.error("Exception Occured" + e1); } @@ -369,17 +353,15 @@ public class PolicyManagerServletTest extends Mockito { PolicyManagerServlet servlet = new PolicyManagerServlet(); PolicyController controller = mock(PolicyController.class); List<String> list = new ArrayList<>(); - list.add( - "{params: { mode: 'EDITFILE', path: '/com/Config_BRMS_Raw_TestBRMSRawPolicy.1.xml'," - + " onlyFolders: false}}"); + list.add("{params: { mode: 'EDITFILE', path: '/com/Config_BRMS_Raw_TestBRMSRawPolicy.1.xml'," + + " onlyFolders: false}}"); for (int i = 0; i < list.size(); i++) { BufferedReader reader = new BufferedReader(new StringReader(list.get(i))); try { when(request.getReader()).thenReturn(reader); when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery( - "FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null)) - .thenReturn(policyData); + when(controller.getDataByQuery("FROM PolicyEntity where policyName = :split_1 and scope = :split_0", + null)).thenReturn(policyData); servlet.setPolicyController(controller); servlet.setTestUserId("Test"); servlet.doPost(request, response); @@ -398,10 +380,10 @@ public class PolicyManagerServletTest extends Mockito { String configData = ""; try { ClassLoader classLoader = getClass().getClassLoader(); - policyContent = IOUtils.toString( - classLoader.getResourceAsStream("Config_Fault_TestClosedLoopPolicy.1.xml")); - configData = IOUtils.toString(classLoader - .getResourceAsStream("com.Config_Fault_TestClosedLoopPolicy.1.json")); + policyContent = + IOUtils.toString(classLoader.getResourceAsStream("Config_Fault_TestClosedLoopPolicy.1.xml")); + configData = + IOUtils.toString(classLoader.getResourceAsStream("com.Config_Fault_TestClosedLoopPolicy.1.json")); } catch (Exception e1) { logger.error("Exception Occured" + e1); } @@ -419,17 +401,15 @@ public class PolicyManagerServletTest extends Mockito { PolicyManagerServlet servlet = new PolicyManagerServlet(); PolicyController controller = mock(PolicyController.class); List<String> list = new ArrayList<>(); - list.add( - "{params: { mode: 'EDITFILE', path: '/com/Config_Fault_TestClosedLoopPolicy.1.xml'," - + " onlyFolders: false}}"); + list.add("{params: { mode: 'EDITFILE', path: '/com/Config_Fault_TestClosedLoopPolicy.1.xml'," + + " onlyFolders: false}}"); for (int i = 0; i < list.size(); i++) { BufferedReader reader = new BufferedReader(new StringReader(list.get(i))); try { when(request.getReader()).thenReturn(reader); when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery( - "FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null)) - .thenReturn(policyData); + when(controller.getDataByQuery("FROM PolicyEntity where policyName = :split_1 and scope = :split_0", + null)).thenReturn(policyData); servlet.setPolicyController(controller); servlet.setTestUserId("Test"); servlet.doPost(request, response); @@ -448,10 +428,9 @@ public class PolicyManagerServletTest extends Mockito { String configData = ""; try { ClassLoader classLoader = getClass().getClassLoader(); - policyContent = IOUtils.toString( - classLoader.getResourceAsStream("Config_PM_TestClosedLoopPMPolicy.1.xml")); - configData = IOUtils.toString( - classLoader.getResourceAsStream("com.Config_PM_TestClosedLoopPMPolicy.1.json")); + policyContent = IOUtils.toString(classLoader.getResourceAsStream("Config_PM_TestClosedLoopPMPolicy.1.xml")); + configData = + IOUtils.toString(classLoader.getResourceAsStream("com.Config_PM_TestClosedLoopPMPolicy.1.json")); } catch (Exception e1) { logger.error("Exception Occured" + e1); } @@ -476,9 +455,8 @@ public class PolicyManagerServletTest extends Mockito { try { when(request.getReader()).thenReturn(reader); when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery( - "FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null)) - .thenReturn(policyData); + when(controller.getDataByQuery("FROM PolicyEntity where policyName = :split_1 and scope = :split_0", + null)).thenReturn(policyData); servlet.setPolicyController(controller); servlet.setTestUserId("Test"); servlet.doPost(request, response); @@ -505,10 +483,8 @@ public class PolicyManagerServletTest extends Mockito { String configData = ""; try { ClassLoader classLoader = getClass().getClassLoader(); - policyContent = - IOUtils.toString(classLoader.getResourceAsStream("Config_MS_vFirewall.1.xml")); - configData = IOUtils - .toString(classLoader.getResourceAsStream("com.Config_MS_vFirewall.1.json")); + policyContent = IOUtils.toString(classLoader.getResourceAsStream("Config_MS_vFirewall.1.xml")); + configData = IOUtils.toString(classLoader.getResourceAsStream("com.Config_MS_vFirewall.1.json")); } catch (Exception e1) { logger.error("Exception Occured" + e1); } @@ -526,20 +502,17 @@ public class PolicyManagerServletTest extends Mockito { PolicyManagerServlet servlet = new PolicyManagerServlet(); PolicyController controller = mock(PolicyController.class); List<String> list = new ArrayList<>(); - list.add( - "{params: { mode: 'EDITFILE', path: '/com/Config_MS_vFirewall.1.xml', onlyFolders: false}}"); + list.add("{params: { mode: 'EDITFILE', path: '/com/Config_MS_vFirewall.1.xml', onlyFolders: false}}"); for (int i = 0; i < list.size(); i++) { BufferedReader reader = new BufferedReader(new StringReader(list.get(i))); try { when(request.getReader()).thenReturn(reader); when(commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", "resource=SampleResource,service=SampleService,type=SampleType," - + "closedLoopControlName=SampleClosedLoop")) - .thenReturn(groupListData); + + "closedLoopControlName=SampleClosedLoop")).thenReturn(groupListData); when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery( - "FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null)) - .thenReturn(policyData); + when(controller.getDataByQuery("FROM PolicyEntity where policyName = :split_1 and scope = :split_0", + null)).thenReturn(policyData); servlet.setPolicyController(controller); servlet.setTestUserId("Test"); servlet.doPost(request, response); @@ -558,10 +531,8 @@ public class PolicyManagerServletTest extends Mockito { String configData = ""; try { ClassLoader classLoader = getClass().getClassLoader(); - policyContent = IOUtils.toString( - classLoader.getResourceAsStream("Config_FW_TestFireWallPolicy.1.xml")); - configData = IOUtils.toString( - classLoader.getResourceAsStream("com.Config_FW_TestFireWallPolicy.1.json")); + policyContent = IOUtils.toString(classLoader.getResourceAsStream("Config_FW_TestFireWallPolicy.1.xml")); + configData = IOUtils.toString(classLoader.getResourceAsStream("com.Config_FW_TestFireWallPolicy.1.json")); } catch (Exception e1) { logger.error("Exception Occured" + e1); } @@ -586,9 +557,8 @@ public class PolicyManagerServletTest extends Mockito { try { when(request.getReader()).thenReturn(reader); when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery( - "FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null)) - .thenReturn(policyData); + when(controller.getDataByQuery("FROM PolicyEntity where policyName = :split_1 and scope = :split_0", + null)).thenReturn(policyData); servlet.setPolicyController(controller); servlet.setTestUserId("Test"); servlet.doPost(request, response); @@ -607,10 +577,8 @@ public class PolicyManagerServletTest extends Mockito { String configData = ""; try { ClassLoader classLoader = getClass().getClassLoader(); - policyContent = IOUtils - .toString(classLoader.getResourceAsStream("Action_TestActionPolicy.1.xml")); - configData = IOUtils.toString( - classLoader.getResourceAsStream("com.Action_TestActionPolicy.1.json")); + policyContent = IOUtils.toString(classLoader.getResourceAsStream("Action_TestActionPolicy.1.xml")); + configData = IOUtils.toString(classLoader.getResourceAsStream("com.Action_TestActionPolicy.1.json")); } catch (Exception e1) { logger.error("Exception Occured" + e1); } @@ -626,16 +594,14 @@ public class PolicyManagerServletTest extends Mockito { PolicyManagerServlet servlet = new PolicyManagerServlet(); PolicyController controller = mock(PolicyController.class); List<String> list = new ArrayList<>(); - list.add("{params: { mode: 'EDITFILE', path: '/com/Action_TestActionPolicy.1.xml'," - + " onlyFolders: false}}"); + list.add("{params: { mode: 'EDITFILE', path: '/com/Action_TestActionPolicy.1.xml'," + " onlyFolders: false}}"); for (int i = 0; i < list.size(); i++) { BufferedReader reader = new BufferedReader(new StringReader(list.get(i))); try { when(request.getReader()).thenReturn(reader); when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery( - "FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null)) - .thenReturn(policyData); + when(controller.getDataByQuery("FROM PolicyEntity where policyName = :split_1 and scope = :split_0", + null)).thenReturn(policyData); servlet.setPolicyController(controller); servlet.setTestUserId("Test"); servlet.doPost(request, response); @@ -653,8 +619,8 @@ public class PolicyManagerServletTest extends Mockito { String policyContent = ""; try { ClassLoader classLoader = getClass().getClassLoader(); - policyContent = IOUtils.toString(classLoader - .getResourceAsStream("Decision_TestDecisionPolicyWithRuleAlgorithms.1.xml")); + policyContent = IOUtils + .toString(classLoader.getResourceAsStream("Decision_TestDecisionPolicyWithRuleAlgorithms.1.xml")); } catch (Exception e1) { logger.error("Exception Occured" + e1); } @@ -666,17 +632,15 @@ public class PolicyManagerServletTest extends Mockito { PolicyManagerServlet servlet = new PolicyManagerServlet(); PolicyController controller = mock(PolicyController.class); List<String> list = new ArrayList<>(); - list.add( - "{params: { mode: 'EDITFILE', path: '/com/Decision_TestDecisionPolicyWithRuleAlgorithms.1.xml'," - + " onlyFolders: false}}"); + list.add("{params: { mode: 'EDITFILE', path: '/com/Decision_TestDecisionPolicyWithRuleAlgorithms.1.xml'," + + " onlyFolders: false}}"); for (int i = 0; i < list.size(); i++) { BufferedReader reader = new BufferedReader(new StringReader(list.get(i))); try { when(request.getReader()).thenReturn(reader); when(controller.getRoles("Test")).thenReturn(rolesdata); - when(controller.getDataByQuery( - "FROM PolicyEntity where policyName = :split_1 and scope = :split_0", null)) - .thenReturn(policyData); + when(controller.getDataByQuery("FROM PolicyEntity where policyName = :split_1 and scope = :split_0", + null)).thenReturn(policyData); servlet.setPolicyController(controller); servlet.setTestUserId("Test"); servlet.doPost(request, response); @@ -692,19 +656,16 @@ public class PolicyManagerServletTest extends Mockito { PolicyManagerServlet servlet = new PolicyManagerServlet(); PolicyController controller = mock(PolicyController.class); List<BufferedReader> readers = new ArrayList<>(); + readers.add(new BufferedReader(new StringReader("{params: { mode: 'ADDFOLDER', path: '/', name: 'Test'}}"))); + readers.add(new BufferedReader(new StringReader("{params: { mode: 'ADDFOLDER', path: '/', name: 'Test*&'}}"))); readers.add(new BufferedReader( - new StringReader("{params: { mode: 'ADDFOLDER', path: '/', name: 'Test'}}"))); - readers.add(new BufferedReader( - new StringReader("{params: { mode: 'ADDFOLDER', path: '/', name: 'Test*&'}}"))); - readers.add(new BufferedReader(new StringReader( - "{params: { mode: 'ADDFOLDER', path: '/Test', subScopename: 'Test1'}}"))); + new StringReader("{params: { mode: 'ADDFOLDER', path: '/Test', subScopename: 'Test1'}}"))); for (int i = 0; i < readers.size(); i++) { try { when(request.getReader()).thenReturn(readers.get(i)); PolicyManagerServlet.setPolicyController(controller); servlet.doPost(request, response); - assertTrue(response.getContentAsString() != null - && response.getContentAsString().contains("success")); + assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("success")); } catch (Exception e1) { logger.error("Exception Occured" + e1); fail(); @@ -720,18 +681,16 @@ public class PolicyManagerServletTest extends Mockito { when(controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", "com.Config_SampleTest1206.1.txt")).thenReturn(configurationEntity); when(controller.getDataByQuery( - "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0", - null)).thenReturn(basePolicyData); - readers.add(new BufferedReader( - new StringReader("{params: { mode: 'COPY', path: 'com.Config_test.1.xml'," - + " newPath: 'com.Config_testClone.1.xml'}}"))); + "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0", null)) + .thenReturn(basePolicyData); + readers.add(new BufferedReader(new StringReader("{params: { mode: 'COPY', path: 'com.Config_test.1.xml'," + + " newPath: 'com.Config_testClone.1.xml'}}"))); for (int i = 0; i < readers.size(); i++) { try { when(request.getReader()).thenReturn(readers.get(i)); PolicyManagerServlet.setPolicyController(controller); servlet.doPost(request, response); - assertTrue(response.getContentAsString() != null - && response.getContentAsString().contains("success")); + assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("success")); } catch (Exception e1) { logger.error("Exception Occured" + e1); fail(); @@ -747,18 +706,16 @@ public class PolicyManagerServletTest extends Mockito { when(controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", "com.Config_SampleTest1206.1.txt")).thenReturn(configurationEntity); when(controller.getDataByQuery( - "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0", - null)).thenReturn(basePolicyData); - readers.add(new BufferedReader( - new StringReader("{params: { mode: 'RENAME', path: 'com.Config_test.1.xml'," - + " newPath: 'com.Config_testClone.1.xml'}}"))); + "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0", null)) + .thenReturn(basePolicyData); + readers.add(new BufferedReader(new StringReader("{params: { mode: 'RENAME', path: 'com.Config_test.1.xml'," + + " newPath: 'com.Config_testClone.1.xml'}}"))); for (int i = 0; i < readers.size(); i++) { try { when(request.getReader()).thenReturn(readers.get(i)); PolicyManagerServlet.setPolicyController(controller); servlet.doPost(request, response); - assertTrue(response.getContentAsString() != null - && response.getContentAsString().contains("success")); + assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("success")); } catch (Exception e1) { logger.error("Exception Occured" + e1); fail(); @@ -771,15 +728,13 @@ public class PolicyManagerServletTest extends Mockito { PolicyManagerServlet servlet = new PolicyManagerServlet(); PolicyController controller = mock(PolicyController.class); List<BufferedReader> readers = new ArrayList<>(); - readers.add(new BufferedReader( - new StringReader("{params: { mode: 'RENAME', path: 'com', newPath: 'Test'}}"))); + readers.add(new BufferedReader(new StringReader("{params: { mode: 'RENAME', path: 'com', newPath: 'Test'}}"))); for (int i = 0; i < readers.size(); i++) { try { when(request.getReader()).thenReturn(readers.get(i)); PolicyManagerServlet.setPolicyController(controller); servlet.doPost(request, response); - assertTrue(response.getContentAsString() != null - && response.getContentAsString().contains("success")); + assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("success")); } catch (Exception e1) { logger.error("Exception Occured" + e1); fail(); diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyNotificationMailTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyNotificationMailTest.java index f5162a695..4449676d3 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyNotificationMailTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyNotificationMailTest.java @@ -19,16 +19,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.admin; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import java.util.ArrayList; import java.util.List; + import org.junit.Before; import org.junit.Test; -import static org.mockito.Mockito.when; import org.onap.policy.common.utils.network.NetworkUtil; import org.onap.policy.controller.PolicyController; import org.onap.policy.rest.dao.CommonClassDao; @@ -69,9 +72,8 @@ public class PolicyNotificationMailTest { commonClassDao = mock(CommonClassDao.class); PolicyController.setCommonClassDao(commonClassDao); - when(commonClassDao.getDataByQuery( - "from WatchPolicyNotificationTable where policyName like:policyFileName", null)) - .thenReturn(data); + when(commonClassDao.getDataByQuery("from WatchPolicyNotificationTable where policyName like:policyFileName", + null)).thenReturn(data); } @Test diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyRestControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyRestControllerTest.java index ce38f236f..912f4d9ce 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyRestControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyRestControllerTest.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 Samsung * ================================================================================ @@ -19,18 +19,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.admin; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; + import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.List; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; + import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -73,69 +77,65 @@ public class PolicyRestControllerTest { response = new MockHttpServletResponse(); User user = new User(); user.setOrgUserId("Test"); - Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))) - .thenReturn(user); + Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))).thenReturn(user); Mockito.when(request.getSession(false)).thenReturn(mockSession); - clRequestString = - "{\"policyData\":{\"error\":\"\",\"inprocess\":false,\"model\":{\"name\":\"com\"," - + "\"subScopename\":\"\",\"path\":[],\"type\":\"dir\",\"size\":0," - + "\"date\":\"2017-06-01T15:45:36.000Z\",\"version\":\"\",\"createdBy\":\"Demo\"," - + "\"modifiedBy\":\"Demo\",\"content\":\"\",\"recursive\":false}," - + "\"tempModel\":{\"name\":\"com\",\"subScopename\":\"\",\"path\":[],\"type\":\"dir\"," - + "\"size\":0,\"date\":\"2017-06-01T15:45:36.000Z\",\"version\":\"\",\"createdBy\":\"Demo\"," - + "\"modifiedBy\":\"Demo\",\"content\":\"\",\"recursive\":false}," - + "\"$$hashKey\":\"object:1439\",\"policy\":{\"policyType\":\"Config\"," - + "\"configPolicyType\":\"ClosedLoop_Fault\",\"triggerTrapSignatures\":[1,1,2,3]," - + "\"triggerfaultSignatures\":[1,1,2,3],\"traptriggerSignatures\":[{\"id\":\"Trap1\"," - + "\"$$hashKey\":\"object:1526\"},{\"id\":\"Trap2\",\"$$hashKey\":\"object:1534\"}]," - + "\"connecttriggerSignatures\":[{\"id\":\"C1\",\"$$hashKey\":\"object:1554\"," - + "\"notBox\":\"NOT\",\"connectTrap1\":\"Trap1\",\"trapCount1\":\"12\"," - + "\"operatorBox\":\"AND\",\"connectTrap2\":\"Trap2\",\"trapCount2\":\"14\"}]," - + "\"faulttriggerSignatures\":[{\"id\":\"Fault1\",\"$$hashKey\":\"object:1566\"}," - + "{\"id\":\"Fault2\",\"$$hashKey\":\"object:1575\"}],\"connectVerificationSignatures\":" - + "[{\"id\":\"C1\",\"$$hashKey\":\"object:1595\",\"notBox\":\"NOT\"," - + "\"connectTrap1\":\"Fault1\",\"trapCount1\":\"11\",\"operatorBox\":\"AND\"," - + "\"connectTrap2\":\"Fault2\",\"trapCount2\":\"12\"}],\"jsonBodyData\":" - + "{\"trapMaxAge\":\"300\",\"vnfType\":\"Test\",\"closedLoopPolicyStatus\":\"Active\"," - + "\"vUSP\":true,\"trinity\":true,\"vDNS\":true,\"mcr\":true,\"gamma\":true," - + "\"actions\":\"Test\",\"timeInterval\":\"11\",\"timeOutvPRO\":\"11\",\"timeOutRuby\":\"11\"," - + "\"retrys\":\"1\",\"agingWindow\":\"12\",\"geoLink\":\"test\"," - + "\"emailAddress\":\"aa@test.com\",\"pepName\":\"Test\",\"pepAction\":\"test\"," - + "\"conditions\":\"SEND\"},\"policyName\":\"SampleTest\"," - + "\"policyDescription\":\"SampleTest\",\"riskType\":\"SampleRiskType\",\"riskLevel\":\"1\"," - + "\"guard\":\"True\",\"onapName\":\"SampleDemo\",\"ttlDate\":\"14/09/2017\"," - + "\"clearTimeOut\":\"123\",\"trapMaxAge\":\"11\",\"verificationclearTimeOut\":\"13\"}}," - + "\"trapData\":{\"trap1\":[{\"id\":\"A1\",\"$$hashKey\":\"object:1528\"," - + "\"notBox\":\"NOT\",\"trigger1\":\"Test\",\"operatorBox\":\"AND\",\"trigger2\":\"Test\"}]," - + "\"trap2\":[{\"id\":\"A1\",\"$$hashKey\":\"object:1536\",\"notBox\":\"NOT\"," - + "\"trigger1\":\"Test\",\"operatorBox\":\"AND\",\"trigger2\":\"Test\"},{\"id\":\"A2\"," - + "\"$$hashKey\":\"object:1542\",\"notBox\":\"NOT\",\"trigger1\":\"A1\"," - + "\"operatorBox\":\"AND\",\"trigger2\":\"Test\"},{\"id\":\"A3\"," - + "\"$$hashKey\":\"object:1548\",\"notBox\":\"NOT\",\"trigger1\":\"A1\"," - + "\"operatorBox\":\"OR\",\"trigger2\":\"A2\"}]},\"faultData\":{\"trap1\":[{\"id\":\"A1\"," - + "\"$$hashKey\":\"object:1568\",\"notBox\":\"NOT\",\"trigger1\":\"Test\"," - + "\"operatorBox\":\"AND\",\"trigger2\":\"Test\"}],\"trap2\":[{\"id\":\"A1\"," - + "\"$$hashKey\":\"object:1577\",\"notBox\":\"NOT\",\"trigger1\":\"Test\"," - + "\"operatorBox\":\"AND\",\"trigger2\":\"Test\"},{\"id\":\"A2\",\"$$hashKey\":" - + "\"object:1583\",\"notBox\":\"NOT\",\"trigger1\":\"Test\",\"operatorBox\":\"OR\"," - + "\"trigger2\":\"Test\"},{\"id\":\"A3\",\"$$hashKey\":\"object:1589\",\"notBox\":\"NOT\"," - + "\"trigger1\":\"A1\",\"operatorBox\":\"AND\",\"trigger2\":\"A2\"}]}}"; - - - fwRequestString = - "{\"policyData\":{\"error\":\"\",\"inprocess\":false,\"model\":{\"name\":\"com\"," - + "\"subScopename\":\"\",\"path\":[],\"type\":\"dir\",\"size\":0," - + "\"date\":\"2017-06-01T15:45:36.000Z\",\"version\":\"\",\"createdBy\":\"Demo\"," - + "\"modifiedBy\":\"Demo\",\"content\":\"\",\"recursive\":false},\"tempModel\":" - + "{\"name\":\"com\",\"subScopename\":\"\",\"path\":[],\"type\":\"dir\",\"size\":0," - + "\"date\":\"2017-06-01T15:45:36.000Z\",\"version\":\"\",\"createdBy\":\"Demo\"," - + "\"modifiedBy\":\"Demo\",\"content\":\"\",\"recursive\":false},\"$$hashKey\":\"object:260\"," - + "\"policy\":{\"policyType\":\"Config\",\"configPolicyType\":\"Firewall Config\"," - + "\"attributes\":[{\"id\":\"choice1\",\"$$hashKey\":\"object:338\",\"key\":\"Test\"," - + "\"value\":\"Test\"}],\"fwattributes\":[],\"policyName\":\"SampleTest\"," - + "\"policyDescription\":\"SampleTest\",\"riskType\":\"SampleRiskType\",\"riskLevel\":\"1\"," - + "\"guard\":\"True\",\"configName\":\"SampleTest\",\"ttlDate\":\"14/09/2017\"," - + "\"securityZone\":\"Test\"}}}"; + clRequestString = "{\"policyData\":{\"error\":\"\",\"inprocess\":false,\"model\":{\"name\":\"com\"," + + "\"subScopename\":\"\",\"path\":[],\"type\":\"dir\",\"size\":0," + + "\"date\":\"2017-06-01T15:45:36.000Z\",\"version\":\"\",\"createdBy\":\"Demo\"," + + "\"modifiedBy\":\"Demo\",\"content\":\"\",\"recursive\":false}," + + "\"tempModel\":{\"name\":\"com\",\"subScopename\":\"\",\"path\":[],\"type\":\"dir\"," + + "\"size\":0,\"date\":\"2017-06-01T15:45:36.000Z\",\"version\":\"\",\"createdBy\":\"Demo\"," + + "\"modifiedBy\":\"Demo\",\"content\":\"\",\"recursive\":false}," + + "\"$$hashKey\":\"object:1439\",\"policy\":{\"policyType\":\"Config\"," + + "\"configPolicyType\":\"ClosedLoop_Fault\",\"triggerTrapSignatures\":[1,1,2,3]," + + "\"triggerfaultSignatures\":[1,1,2,3],\"traptriggerSignatures\":[{\"id\":\"Trap1\"," + + "\"$$hashKey\":\"object:1526\"},{\"id\":\"Trap2\",\"$$hashKey\":\"object:1534\"}]," + + "\"connecttriggerSignatures\":[{\"id\":\"C1\",\"$$hashKey\":\"object:1554\"," + + "\"notBox\":\"NOT\",\"connectTrap1\":\"Trap1\",\"trapCount1\":\"12\"," + + "\"operatorBox\":\"AND\",\"connectTrap2\":\"Trap2\",\"trapCount2\":\"14\"}]," + + "\"faulttriggerSignatures\":[{\"id\":\"Fault1\",\"$$hashKey\":\"object:1566\"}," + + "{\"id\":\"Fault2\",\"$$hashKey\":\"object:1575\"}],\"connectVerificationSignatures\":" + + "[{\"id\":\"C1\",\"$$hashKey\":\"object:1595\",\"notBox\":\"NOT\"," + + "\"connectTrap1\":\"Fault1\",\"trapCount1\":\"11\",\"operatorBox\":\"AND\"," + + "\"connectTrap2\":\"Fault2\",\"trapCount2\":\"12\"}],\"jsonBodyData\":" + + "{\"trapMaxAge\":\"300\",\"vnfType\":\"Test\",\"closedLoopPolicyStatus\":\"Active\"," + + "\"vUSP\":true,\"trinity\":true,\"vDNS\":true,\"mcr\":true,\"gamma\":true," + + "\"actions\":\"Test\",\"timeInterval\":\"11\",\"timeOutvPRO\":\"11\",\"timeOutRuby\":\"11\"," + + "\"retrys\":\"1\",\"agingWindow\":\"12\",\"geoLink\":\"test\"," + + "\"emailAddress\":\"aa@test.com\",\"pepName\":\"Test\",\"pepAction\":\"test\"," + + "\"conditions\":\"SEND\"},\"policyName\":\"SampleTest\"," + + "\"policyDescription\":\"SampleTest\",\"riskType\":\"SampleRiskType\",\"riskLevel\":\"1\"," + + "\"guard\":\"True\",\"onapName\":\"SampleDemo\",\"ttlDate\":\"14/09/2017\"," + + "\"clearTimeOut\":\"123\",\"trapMaxAge\":\"11\",\"verificationclearTimeOut\":\"13\"}}," + + "\"trapData\":{\"trap1\":[{\"id\":\"A1\",\"$$hashKey\":\"object:1528\"," + + "\"notBox\":\"NOT\",\"trigger1\":\"Test\",\"operatorBox\":\"AND\",\"trigger2\":\"Test\"}]," + + "\"trap2\":[{\"id\":\"A1\",\"$$hashKey\":\"object:1536\",\"notBox\":\"NOT\"," + + "\"trigger1\":\"Test\",\"operatorBox\":\"AND\",\"trigger2\":\"Test\"},{\"id\":\"A2\"," + + "\"$$hashKey\":\"object:1542\",\"notBox\":\"NOT\",\"trigger1\":\"A1\"," + + "\"operatorBox\":\"AND\",\"trigger2\":\"Test\"},{\"id\":\"A3\"," + + "\"$$hashKey\":\"object:1548\",\"notBox\":\"NOT\",\"trigger1\":\"A1\"," + + "\"operatorBox\":\"OR\",\"trigger2\":\"A2\"}]},\"faultData\":{\"trap1\":[{\"id\":\"A1\"," + + "\"$$hashKey\":\"object:1568\",\"notBox\":\"NOT\",\"trigger1\":\"Test\"," + + "\"operatorBox\":\"AND\",\"trigger2\":\"Test\"}],\"trap2\":[{\"id\":\"A1\"," + + "\"$$hashKey\":\"object:1577\",\"notBox\":\"NOT\",\"trigger1\":\"Test\"," + + "\"operatorBox\":\"AND\",\"trigger2\":\"Test\"},{\"id\":\"A2\",\"$$hashKey\":" + + "\"object:1583\",\"notBox\":\"NOT\",\"trigger1\":\"Test\",\"operatorBox\":\"OR\"," + + "\"trigger2\":\"Test\"},{\"id\":\"A3\",\"$$hashKey\":\"object:1589\",\"notBox\":\"NOT\"," + + "\"trigger1\":\"A1\",\"operatorBox\":\"AND\",\"trigger2\":\"A2\"}]}}"; + + fwRequestString = "{\"policyData\":{\"error\":\"\",\"inprocess\":false,\"model\":{\"name\":\"com\"," + + "\"subScopename\":\"\",\"path\":[],\"type\":\"dir\",\"size\":0," + + "\"date\":\"2017-06-01T15:45:36.000Z\",\"version\":\"\",\"createdBy\":\"Demo\"," + + "\"modifiedBy\":\"Demo\",\"content\":\"\",\"recursive\":false},\"tempModel\":" + + "{\"name\":\"com\",\"subScopename\":\"\",\"path\":[],\"type\":\"dir\",\"size\":0," + + "\"date\":\"2017-06-01T15:45:36.000Z\",\"version\":\"\",\"createdBy\":\"Demo\"," + + "\"modifiedBy\":\"Demo\",\"content\":\"\",\"recursive\":false},\"$$hashKey\":\"object:260\"," + + "\"policy\":{\"policyType\":\"Config\",\"configPolicyType\":\"Firewall Config\"," + + "\"attributes\":[{\"id\":\"choice1\",\"$$hashKey\":\"object:338\",\"key\":\"Test\"," + + "\"value\":\"Test\"}],\"fwattributes\":[],\"policyName\":\"SampleTest\"," + + "\"policyDescription\":\"SampleTest\",\"riskType\":\"SampleRiskType\",\"riskLevel\":\"1\"," + + "\"guard\":\"True\",\"configName\":\"SampleTest\",\"ttlDate\":\"14/09/2017\"," + + "\"securityZone\":\"Test\"}}}"; fwViewRequestString = "{\"policyData\":{\"policyType\":\"Config\",\"configPolicyType\":\"Firewall Config\",\"attributes\":" @@ -144,8 +144,6 @@ public class PolicyRestControllerTest { + "\"riskType\":\"SampleRiskType\",\"riskLevel\":\"1\",\"guard\":\"True\"," + "\"configName\":\"SampleTest\",\"ttlDate\":\"14/09/2017\",\"securityZone\":\"Test\"}}"; - - prefixListData = new ArrayList<>(); PrefixList prefixList = new PrefixList(); prefixList.setPrefixListName("Test"); @@ -209,8 +207,7 @@ public class PolicyRestControllerTest { termList.setAction("Test"); termListData.add(termList); when(commonClassDao.getData(TermList.class)).thenReturn(termListData); - when(commonClassDao.getDataById(TermList.class, "termName", "Test")) - .thenReturn(termListData); + when(commonClassDao.getDataById(TermList.class, "termName", "Test")).thenReturn(termListData); } @Test diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyUserInfoControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyUserInfoControllerTest.java index d05b7933d..bf4b67683 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyUserInfoControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyUserInfoControllerTest.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 Samsung * ================================================================================ @@ -19,13 +19,16 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.admin; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; + import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -45,8 +48,7 @@ public class PolicyUserInfoControllerTest { response = new MockHttpServletResponse(); User user = new User(); user.setOrgUserId("Test"); - Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))) - .thenReturn(user); + Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))).thenReturn(user); Mockito.when(request.getSession(false)).thenReturn(mockSession); } diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/RESTfulPAPEngineTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/RESTfulPAPEngineTest.java index be248598f..e28ca1281 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/RESTfulPAPEngineTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/RESTfulPAPEngineTest.java @@ -19,17 +19,24 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.admin; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.att.research.xacml.util.XACMLProperties; + import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URLConnection; + import javax.servlet.http.HttpServletResponse; + import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; @@ -40,9 +47,6 @@ import org.mockito.Mockito; import org.onap.policy.rest.adapter.PolicyRestAdapter; import org.onap.policy.xacml.api.pap.OnapPDP; import org.onap.policy.xacml.api.pap.OnapPDPGroup; -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.api.pap.PDPPolicy; -import com.att.research.xacml.util.XACMLProperties; public class RESTfulPAPEngineTest { @Rule diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/conf/HibernateSessionTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/conf/HibernateSessionTest.java index dab2cba53..3bd48d67a 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/conf/HibernateSessionTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/conf/HibernateSessionTest.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. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -23,6 +23,7 @@ package org.onap.policy.conf; import static org.junit.Assert.assertNull; + import org.hibernate.SessionFactory; import org.junit.Before; import org.junit.Test; diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AdminTabControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AdminTabControllerTest.java index a4999ff42..68da8e714 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AdminTabControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AdminTabControllerTest.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 Samsung * ================================================================================ @@ -19,19 +19,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.controller; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; + import java.io.BufferedReader; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; + import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -62,8 +66,7 @@ public class AdminTabControllerTest { HttpSession mockSession = mock(HttpSession.class); User user = new User(); user.setOrgUserId("Test"); - Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))) - .thenReturn(user); + Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))).thenReturn(user); Mockito.when(request.getSession(false)).thenReturn(mockSession); AdminTabController.setCommonClassDao(commonClassDao); @@ -81,8 +84,7 @@ public class AdminTabControllerTest { AdminTabController admin = new AdminTabController(); try { admin.getAdminTabEntityData(request, response); - assertTrue(response.getContentAsString() != null - && response.getContentAsString().contains("lockdowndata")); + assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("lockdowndata")); } catch (UnsupportedEncodingException e) { logger.error("Exception Occured" + e); fail(); diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AutoPushControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AutoPushControllerTest.java index 5dd5d7ee3..7d2d5f8c2 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AutoPushControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/AutoPushControllerTest.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. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -19,12 +19,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.controller; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; + +import com.mockrunner.mock.web.MockHttpServletRequest; +import com.mockrunner.mock.web.MockHttpServletResponse; + import java.io.IOException; + import javax.servlet.http.HttpServletResponse; + import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -35,8 +42,6 @@ import org.onap.portalsdk.core.web.support.UserUtils; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import com.mockrunner.mock.web.MockHttpServletRequest; -import com.mockrunner.mock.web.MockHttpServletResponse; @RunWith(PowerMockRunner.class) public class AutoPushControllerTest { diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateDcaeMicroServiceControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateDcaeMicroServiceControllerTest.java index e4ededa1f..96320e7bc 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateDcaeMicroServiceControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateDcaeMicroServiceControllerTest.java @@ -22,7 +22,6 @@ package org.onap.policy.controller; - import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; @@ -31,10 +30,12 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; + import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.fge.jackson.JsonLoader; + import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; @@ -46,9 +47,11 @@ import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; + import javax.servlet.ReadListener; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; + 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; @@ -56,6 +59,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.junit.Before; import org.junit.Test; import org.onap.policy.common.logging.flexlogger.FlexLogger; diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateOptimizationControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateOptimizationControllerTest.java index 6747e9669..6a5e83f4e 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateOptimizationControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateOptimizationControllerTest.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. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -22,7 +22,6 @@ package org.onap.policy.controller; - import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; @@ -31,6 +30,12 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.fge.jackson.JsonLoader; + import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; @@ -39,9 +44,19 @@ import java.io.InputStream; import java.io.StringReader; import java.util.ArrayList; import java.util.List; + import javax.servlet.ReadListener; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; + +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.junit.Before; import org.junit.Test; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -53,17 +68,6 @@ import org.onap.policy.rest.jpa.OptimizationModels; import org.onap.policy.rest.jpa.PolicyEntity; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.github.fge.jackson.JsonLoader; -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; /** * The class <code>CreateOptimizationControllerTest</code> contains tests for the class @@ -94,26 +98,24 @@ public class CreateOptimizationControllerTest { when(commonClassDao.getDataById(OptimizationModels.class, "modelName", "test")) .thenReturn(optimizationModelsData); - jsonString = - "{\"policyData\": {\"error\": \"\",\"inprocess\": false,\"model\": {\"name\": \"testingdata\", " - + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0," - + "\"date\": \"2017-04-12T21:26:57.000Z\",\"version\": \"\",\"createdBy\": \"someone\"," - + "\"modifiedBy\": \"someone\",\"content\": \"\",\"recursive\": false}," - + "\"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\"}," - + "\"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"OOF\"," - + "\"policyName\": \"testPolicy\",\"policyDescription\": \"testing input\"," - + "\"onapName\": \"test\",\"guard\": \"False\",\"riskType\": \"Risk12345\"," - + "\"riskLevel\": \"2\",\"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\"," - + "\"version\": \"1707.41.02\",\"ruleGridData\": [[\"fileId\"]],\"ttlDate\": null}}," - + "\"policyJSON\": {\"pmTableName\": \"test\",\"dmdTopic\": \"1\",\"fileId\": \"56\"}}"; - - configBodyString = - "{\"service\":\"PolicyEntityTest\",\"policyName\":\"someone\",\"description\":\"test\"," - + "\"templateVersion\":\"1607\",\"version\":\"HD\",\"priority\":\"2\"," - + "\"content\":{\"lastPolled\":\"1\",\"boolen-test\":\"true\",\"created\":\"test\"," - + "\"retiredDate\":\"test\",\"scope\":\"TEST_PLACEMENT_VDHV\",\"name\":\"test\"," - + "\"lastModified\":\"test\",\"state\":\"CREATED\",\"type\":\"CONFIG\",\"intent\":\"test\"," - + "\"target\":\"TEST\"}}"; + jsonString = "{\"policyData\": {\"error\": \"\",\"inprocess\": false,\"model\": {\"name\": \"testingdata\", " + + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0," + + "\"date\": \"2017-04-12T21:26:57.000Z\",\"version\": \"\",\"createdBy\": \"someone\"," + + "\"modifiedBy\": \"someone\",\"content\": \"\",\"recursive\": false}," + + "\"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\"}," + + "\"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"OOF\"," + + "\"policyName\": \"testPolicy\",\"policyDescription\": \"testing input\"," + + "\"onapName\": \"test\",\"guard\": \"False\",\"riskType\": \"Risk12345\"," + + "\"riskLevel\": \"2\",\"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\"," + + "\"version\": \"1707.41.02\",\"ruleGridData\": [[\"fileId\"]],\"ttlDate\": null}}," + + "\"policyJSON\": {\"pmTableName\": \"test\",\"dmdTopic\": \"1\",\"fileId\": \"56\"}}"; + + configBodyString = "{\"service\":\"PolicyEntityTest\",\"policyName\":\"someone\",\"description\":\"test\"," + + "\"templateVersion\":\"1607\",\"version\":\"HD\",\"priority\":\"2\"," + + "\"content\":{\"lastPolled\":\"1\",\"boolen-test\":\"true\",\"created\":\"test\"," + + "\"retiredDate\":\"test\",\"scope\":\"TEST_PLACEMENT_VDHV\",\"name\":\"test\"," + + "\"lastModified\":\"test\",\"state\":\"CREATED\",\"type\":\"CONFIG\",\"intent\":\"test\"," + + "\"target\":\"TEST\"}}"; request = mock(HttpServletRequest.class); BufferedReader br = new BufferedReader(new StringReader(jsonString)); @@ -141,15 +143,14 @@ public class CreateOptimizationControllerTest { PolicyRestAdapter policyData = null; try { root = JsonLoader.fromString(jsonString); - policyData = (PolicyRestAdapter) mapper.readValue( - root.get("policyData").get("policy").toString(), PolicyRestAdapter.class); + policyData = (PolicyRestAdapter) mapper.readValue(root.get("policyData").get("policy").toString(), + PolicyRestAdapter.class); } catch (Exception e) { logger.error("testSetDataToPolicyRestAdapter", e); } PolicyRestAdapter result = controller.setDataToPolicyRestAdapter(policyData, root); - assertTrue( - result != null && result.getJsonBody() != null && !result.getJsonBody().isEmpty()); + assertTrue(result != null && result.getJsonBody() != null && !result.getJsonBody().isEmpty()); logger.debug("result.getJsonBody() : " + result.getJsonBody()); logger.debug("testSetDataToPolicyRestAdapter: exit"); @@ -181,8 +182,8 @@ public class CreateOptimizationControllerTest { testData.setVersion("1707.4.1.2-Junit"); optimizationModelsData.add(testData); // mock the getDataById() call with the same MS model name - when(commonClassDao.getDataById(OptimizationModels.class, "modelName", - "testPolicyBody")).thenReturn(optimizationModelsData); + when(commonClassDao.getDataById(OptimizationModels.class, "modelName", "testPolicyBody")) + .thenReturn(optimizationModelsData); controller.getOptimizationTemplateData(request, response); @@ -225,8 +226,8 @@ public class CreateOptimizationControllerTest { optimizationModelsData.add(testData); // mock the getDataById() call with the same MS model name - when(commonClassDao.getDataById(OptimizationModels.class, "modelName", - "TestPolicyBody")).thenReturn(optimizationModelsData); + when(commonClassDao.getDataById(OptimizationModels.class, "modelName", "TestPolicyBody")) + .thenReturn(optimizationModelsData); controller.getModelServiceVersionData(request, response); assertTrue(response.getContentAsString() != null @@ -266,8 +267,8 @@ public class CreateOptimizationControllerTest { try { root = JsonLoader.fromString(jsonString); - restAdapter = (PolicyRestAdapter) mapper.readValue( - root.get("policyData").get("policy").toString(), PolicyRestAdapter.class); + restAdapter = (PolicyRestAdapter) mapper.readValue(root.get("policyData").get("policy").toString(), + PolicyRestAdapter.class); PolicyType policyType = new PolicyType(); TargetType target = new TargetType(); @@ -409,9 +410,7 @@ public class CreateOptimizationControllerTest { String fileName = ""; try { ClassLoader classLoader = getClass().getClassLoader(); - fileName = - new File(classLoader.getResource("schedulerPolicies-v1707.xmi").getFile()) - .getAbsolutePath(); + fileName = new File(classLoader.getResource("schedulerPolicies-v1707.xmi").getFile()).getAbsolutePath(); } catch (Exception e1) { logger.error("Exception Occured while loading file" + e1); } diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/DashboardControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/DashboardControllerTest.java index f2ecea504..f86f3532c 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/DashboardControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/DashboardControllerTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * POLICY-SDK-APP * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -19,15 +19,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.controller; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; + import java.io.UnsupportedEncodingException; import java.nio.file.Path; import java.nio.file.Paths; + import javax.servlet.http.HttpServletRequest; + import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -84,8 +88,8 @@ public class DashboardControllerTest { public void testGetPAPStatusData() { try { controller.getPAPStatusData(request, response); - assertTrue(response.getContentAsString() != null - && response.getContentAsString().contains("papTableDatas")); + assertTrue( + response.getContentAsString() != null && response.getContentAsString().contains("papTableDatas")); } catch (UnsupportedEncodingException e) { logger.error("Exception Occured" + e); fail(); @@ -96,8 +100,8 @@ public class DashboardControllerTest { public void testGetPDPStatusData() { try { controller.getPDPStatusData(request, response); - assertTrue(response.getContentAsString() != null - && response.getContentAsString().contains("pdpTableDatas")); + assertTrue( + response.getContentAsString() != null && response.getContentAsString().contains("pdpTableDatas")); } catch (UnsupportedEncodingException e) { logger.error("Exception Occured" + e); fail(); diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntriesTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntriesTest.java index e9f953b87..1c744278a 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntriesTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntriesTest.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. @@ -27,7 +27,9 @@ import static org.mockito.Mockito.mock; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; + import javax.servlet.http.HttpServletRequest; + import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.ArrayUtils; import org.junit.Before; diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PDPControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PDPControllerTest.java index 1c1c0fbbd..0d5a09754 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PDPControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PDPControllerTest.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 Samsung * ================================================================================ @@ -19,15 +19,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.controller; import static org.junit.Assert.assertTrue; + import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; + import javax.servlet.http.HttpServletRequest; + import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -86,8 +90,7 @@ public class PDPControllerTest extends Mockito { when(controller.getRoles("Test")).thenReturn(rolesdata); pdpController.getPDPGroupEntityData(request, response); try { - assertTrue(response.getContentAsString() != null - && response.getContentAsString().contains("data")); + assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("data")); } catch (UnsupportedEncodingException e) { logger.error("Exception Occured" + e); } diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyControllerTest.java index 65077ae01..af3c88257 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyControllerTest.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 Samsung * ================================================================================ @@ -19,15 +19,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.controller; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; + import java.util.ArrayList; import java.util.List; + import javax.script.SimpleBindings; + import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Test; @@ -52,8 +56,7 @@ public class PolicyControllerTest { String policyData = ""; try { ClassLoader classLoader = getClass().getClassLoader(); - policyData = IOUtils - .toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml")); + policyData = IOUtils.toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml")); } catch (Exception e1) { e1.printStackTrace(); } diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyExportAndImportControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyExportAndImportControllerTest.java index 1e4e62da1..84e9ccf84 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyExportAndImportControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyExportAndImportControllerTest.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. @@ -17,19 +17,26 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.controller; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.when; + +import com.mockrunner.mock.web.MockHttpServletRequest; +import com.mockrunner.mock.web.MockHttpServletResponse; + import java.io.File; import java.io.IOException; import java.util.Collections; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; @@ -43,8 +50,6 @@ import org.onap.portalsdk.core.web.support.UserUtils; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import com.mockrunner.mock.web.MockHttpServletRequest; -import com.mockrunner.mock.web.MockHttpServletResponse; @RunWith(PowerMockRunner.class) public class PolicyExportAndImportControllerTest { @@ -97,9 +102,8 @@ public class PolicyExportAndImportControllerTest { ClassLoader classLoader = getClass().getClassLoader(); // Test negative case - String file = - new File(classLoader.getResource("Config_BRMS_Raw_TestBRMSRawPolicy.1.xml").getFile()) - .getAbsolutePath(); + String file = new File(classLoader.getResource("Config_BRMS_Raw_TestBRMSRawPolicy.1.xml").getFile()) + .getAbsolutePath(); JSONObject json = controller.importRepositoryFile(file, request); assertNull(json); diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyNotificationControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyNotificationControllerTest.java index 476eb6728..509f4a692 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyNotificationControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyNotificationControllerTest.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. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -19,15 +19,22 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.controller; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.Matchers.any; import static org.mockito.Mockito.when; + +import com.mockrunner.mock.web.MockHttpServletRequest; +import com.mockrunner.mock.web.MockHttpServletResponse; + import java.io.IOException; import java.util.Collections; + import javax.servlet.http.HttpServletResponse; + import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; @@ -38,8 +45,6 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.web.servlet.ModelAndView; -import com.mockrunner.mock.web.MockHttpServletRequest; -import com.mockrunner.mock.web.MockHttpServletResponse; @RunWith(PowerMockRunner.class) public class PolicyNotificationControllerTest { @@ -60,16 +65,14 @@ public class PolicyNotificationControllerTest { PolicyNotificationController controller = new PolicyNotificationController(); controller.commonClassDao = dao; MockHttpServletRequest request = new MockHttpServletRequest(); - request.setBodyContent( - "{\n\"watchData\": {\"name\": \"testVal\",\"path\": \"testPath\"\n}}\n"); + request.setBodyContent("{\n\"watchData\": {\"name\": \"testVal\",\"path\": \"testPath\"\n}}\n"); MockHttpServletResponse response = new MockHttpServletResponse(); ModelAndView model = controller.watchPolicy(request, response); assertNull(model); assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); // Negative test watch - request.setBodyContent( - "{\n\"watchData\": {\"name\": \"testVal\",\"nopath\": \"testPath\"\n}}\n"); + request.setBodyContent("{\n\"watchData\": {\"name\": \"testVal\",\"nopath\": \"testPath\"\n}}\n"); response = new MockHttpServletResponse(); model = controller.watchPolicy(request, response); assertNull(model); diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyRolesControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyRolesControllerTest.java index d665aae5e..720f6ca76 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyRolesControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyRolesControllerTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * POLICY-SDK-APP * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -19,17 +19,21 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.controller; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; + import java.io.BufferedReader; import java.io.StringReader; import java.io.UnsupportedEncodingException; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; + import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -59,8 +63,7 @@ public class PolicyRolesControllerTest { HttpSession mockSession = mock(HttpSession.class); User user = new User(); user.setOrgUserId("Test"); - Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))) - .thenReturn(user); + Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))).thenReturn(user); Mockito.when(request.getSession(false)).thenReturn(mockSession); logger.info("setUp: exit"); @@ -70,8 +73,7 @@ public class PolicyRolesControllerTest { public void testGetPolicyRolesEntityData() { try { controller.getPolicyRolesEntityData(request, response); - assertTrue(response.getContentAsString() != null - && response.getContentAsString().contains("rolesDatas")); + assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("rolesDatas")); } catch (UnsupportedEncodingException e) { logger.error("Exception Occured" + e); fail(); @@ -82,8 +84,7 @@ public class PolicyRolesControllerTest { public void testGetPolicyScopesEntityData() { try { controller.getPolicyScopesEntityData(request, response); - assertTrue(response.getContentAsString() != null - && response.getContentAsString().contains("scopeDatas")); + assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("scopeDatas")); } catch (UnsupportedEncodingException e) { logger.error("Exception Occured" + e); fail(); @@ -100,8 +101,7 @@ public class PolicyRolesControllerTest { when(request.getReader()).thenReturn(br); controller.SaveRolesEntityData(request, response); logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue(response.getContentAsString() != null - && response.getContentAsString().contains("rolesDatas")); + assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("rolesDatas")); } catch (Exception e) { fail("Exception: " + e); } diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyValidationControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyValidationControllerTest.java index 2ad6d6a7e..56b2d1030 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyValidationControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyValidationControllerTest.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. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -19,16 +19,21 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.controller; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; + +import com.mockrunner.mock.web.MockHttpServletRequest; +import com.mockrunner.mock.web.MockHttpServletResponse; + import java.io.IOException; + import javax.servlet.http.HttpServletResponse; + import org.junit.Test; import org.springframework.web.servlet.ModelAndView; -import com.mockrunner.mock.web.MockHttpServletRequest; -import com.mockrunner.mock.web.MockHttpServletResponse; public class PolicyValidationControllerTest { @Test diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/CommonClassDaoImplTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/CommonClassDaoImplTest.java index e7212f109..3bc89c9d0 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/CommonClassDaoImplTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/daoImp/CommonClassDaoImplTest.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 Samsung * ================================================================================ @@ -26,12 +26,15 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; + import java.io.File; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Properties; + import javax.script.SimpleBindings; + import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; import org.h2.tools.Server; import org.hibernate.SessionFactory; @@ -150,8 +153,7 @@ public class CommonClassDaoImplTest { userinfo.setUserName(loginId_userName); commonClassDao.save(userinfo); - List<Object> dataCur = - commonClassDao.getDataByQuery("from UserInfo", new SimpleBindings()); + List<Object> dataCur = commonClassDao.getDataByQuery("from UserInfo", new SimpleBindings()); assertEquals(1, dataCur.size()); UserInfo cur = (UserInfo) dataCur.get(0); @@ -183,8 +185,7 @@ public class CommonClassDaoImplTest { pe.setCreatedBy("Test"); commonClassDao.save(pe); - List<Object> dataCur = - commonClassDao.getDataByQuery("from PolicyEntity", new SimpleBindings()); + List<Object> dataCur = commonClassDao.getDataByQuery("from PolicyEntity", new SimpleBindings()); assertTrue(1 == dataCur.size()); assertTrue(dataCur.get(0) instanceof PolicyEntity); @@ -296,8 +297,7 @@ public class CommonClassDaoImplTest { String[] splitDBCheckName = dbCheckName.split(":"); // Current Implementation - 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]); @@ -328,8 +328,7 @@ public class CommonClassDaoImplTest { commonClassDao.save(watch); // Current Implementation - String query = - "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId"; + String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId"; SimpleBindings params = new SimpleBindings(); params.put("finalName", finalName); params.put("userId", userId); @@ -371,8 +370,7 @@ public class CommonClassDaoImplTest { String finalName = "banana' OR '1'='1"; // Current Implementation - String query = - "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId"; + String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId"; SimpleBindings params = new SimpleBindings(); params.put("finalName", finalName); params.put("userId", userId); @@ -399,19 +397,18 @@ public class CommonClassDaoImplTest { userInfo.setUserLoginId("TestID"); userInfo.setUserName("Test"); commonClassDao.save(userInfo); - List<Object> data = commonClassDao.getDataById(UserInfo.class, "userLoginId:userName", - "TestID:Test"); + List<Object> data = commonClassDao.getDataById(UserInfo.class, "userLoginId:userName", "TestID:Test"); assertTrue(data.size() == 1); UserInfo userInfoUpdate = (UserInfo) data.get(0); userInfoUpdate.setUserName("Test1"); commonClassDao.update(userInfoUpdate); List<String> data1 = commonClassDao.getDataByColumn(UserInfo.class, "userLoginId"); assertTrue(data1.size() == 1); - UserInfo data2 = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, - "userLoginId:userName", "TestID:Test1"); + UserInfo data2 = + (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId:userName", "TestID:Test1"); assertTrue("TestID".equals(data2.getUserLoginId())); - List<Object> data3 = commonClassDao.checkDuplicateEntry("TestID:Test1", - "userLoginId:userName", UserInfo.class); + List<Object> data3 = + commonClassDao.checkDuplicateEntry("TestID:Test1", "userLoginId:userName", UserInfo.class); assertTrue(data3.size() == 1); PolicyRoles roles = new PolicyRoles(); roles.setRole("admin"); diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/model/PDPGroupContainerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/model/PDPGroupContainerTest.java index 5117a05da..0cfba2cc1 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/model/PDPGroupContainerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/model/PDPGroupContainerTest.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. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -24,13 +24,15 @@ package org.onap.policy.model; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; + +import com.att.research.xacml.api.pap.PAPException; + import org.junit.Test; import org.mockito.Mockito; import org.onap.policy.rest.util.PolicyContainer.ItemSetChangeListener; import org.onap.policy.xacml.api.pap.OnapPDP; import org.onap.policy.xacml.api.pap.OnapPDPGroup; import org.onap.policy.xacml.api.pap.PAPPolicyEngine; -import com.att.research.xacml.api.pap.PAPException; public class PDPGroupContainerTest { private PAPPolicyEngine engine = Mockito.mock(PAPPolicyEngine.class); diff --git a/onap-java-formatter.xml b/onap-java-formatter.xml new file mode 100644 index 000000000..1dd9de63c --- /dev/null +++ b/onap-java-formatter.xml @@ -0,0 +1,295 @@ +<?xml version="1.0" encoding="UTF-8" standalone="no"?> +<profiles version="12"> +<profile kind="CodeFormatterProfile" name="onap-java-formatter" version="12"> +<setting id="org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode" value="enabled"/> +<setting id="org.eclipse.jdt.core.compiler.codegen.targetPlatform" value="1.8"/> +<setting id="org.eclipse.jdt.core.compiler.compliance" value="1.8"/> +<setting id="org.eclipse.jdt.core.compiler.problem.assertIdentifier" value="error"/> +<setting id="org.eclipse.jdt.core.compiler.problem.enumIdentifier" value="error"/> +<setting id="org.eclipse.jdt.core.compiler.source" value="1.8"/> +<setting id="org.eclipse.jdt.core.formatter.align_type_members_on_columns" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation" value="48"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_assignment" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_binary_expression" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_compact_if" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_conditional_expression" value="80"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_enum_constants" value="0"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_method_declaration" value="0"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_multiple_fields" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_resources_in_try" value="80"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch" value="16"/> +<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_imports" value="1"/> +<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_package" value="1"/> +<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_field" value="0"/> +<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration" value="0"/> +<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_imports" value="0"/> +<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_member_type" value="0"/> +<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_method" value="1"/> +<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk" value="1"/> +<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_package" value="1"/> +<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_import_groups" value="1"/> +<setting id="org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations" value="2"/> +<setting id="org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration" value="end_of_line"/> +<setting id="org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration" value="end_of_line"/> +<setting id="org.eclipse.jdt.core.formatter.brace_position_for_array_initializer" value="end_of_line"/> +<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block" value="end_of_line"/> +<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block_in_case" value="end_of_line"/> +<setting id="org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration" value="end_of_line"/> +<setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_constant" value="end_of_line"/> +<setting id="org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration" value="end_of_line"/> +<setting id="org.eclipse.jdt.core.formatter.brace_position_for_lambda_body" value="end_of_line"/> +<setting id="org.eclipse.jdt.core.formatter.brace_position_for_method_declaration" value="end_of_line"/> +<setting id="org.eclipse.jdt.core.formatter.brace_position_for_switch" value="end_of_line"/> +<setting id="org.eclipse.jdt.core.formatter.brace_position_for_type_declaration" value="end_of_line"/> +<setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.comment.format_block_comments" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.comment.format_header" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.comment.format_html" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.comment.format_javadoc_comments" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.comment.format_line_comments" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.comment.format_source_code" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.comment.indent_parameter_description" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.comment.indent_root_tags" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.comment.line_length" value="120"/> +<setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.compact_else_if" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.continuation_indentation" value="2"/> +<setting id="org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer" value="2"/> +<setting id="org.eclipse.jdt.core.formatter.disabling_tag" value="@formatter:off"/> +<setting id="org.eclipse.jdt.core.formatter.enabling_tag" value="@formatter:on"/> +<setting id="org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.indent_empty_lines" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_block" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_body" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.indentation.size" value="4"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_label" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_type_annotation" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_binary_operator" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_ellipsis" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_lambda_arrow" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_after_unary_operator" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_binary_operator" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_ellipsis" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_lambda_arrow" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional" value="insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_before_unary_operator" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation" value="do not insert"/> +<setting id="org.eclipse.jdt.core.formatter.join_lines_in_comments" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.join_wrapped_lines" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.lineSplit" value="120"/> +<setting id="org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body" value="0"/> +<setting id="org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve" value="1"/> +<setting id="org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.tabulation.char" value="space"/> +<setting id="org.eclipse.jdt.core.formatter.tabulation.size" value="4"/> +<setting id="org.eclipse.jdt.core.formatter.use_on_off_tags" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations" value="false"/> +<setting id="org.eclipse.jdt.core.formatter.wrap_before_binary_operator" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch" value="true"/> +<setting id="org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested" value="true"/> +</profile> +</profiles> @@ -23,7 +23,7 @@ <parent> <groupId>org.onap.policy.parent</groupId> <artifactId>integration</artifactId> - <version>3.0.1</version> + <version>3.1.0-SNAPSHOT</version> <relativePath /> </parent> <groupId>org.onap.policy.engine</groupId> |