diff options
Diffstat (limited to 'POLICY-SDK-APP/src/main/java/org/onap')
35 files changed, 4462 insertions, 4529 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/CheckPdpProperties.java index 26b9798ac..925344191 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/CheckPdpProperties.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,9 +39,10 @@ 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; +import org.onap.policy.rest.XacmlRestProperties; import org.onap.policy.utils.PeCryptoUtils; import org.onap.policy.xacml.api.XACMLErrorConstants; @@ -50,20 +51,20 @@ import org.onap.policy.xacml.api.XACMLErrorConstants; * may be ok for a highly controlled production environment in which nothing changes, but not a very good * implementation. * - * The reset() method has been added to assist with the above problem in order to acquire >80% JUnit code coverage. + * <p>The reset() method has been added to assist with the above problem in order to acquire >80% JUnit code coverage. * - * This static class doesn't really check a PDP, it simply loads a properties file and tried to ensure that a valid URL - * exists for a PDP along with user/password. + * <p>This static class doesn't really check a PDP, it simply loads a properties file and tried to ensure + * that a valid URL exists for a PDP along with user/password. */ -public class CheckPDP { +public class CheckPdpProperties { private static Path pdpPath = null; private static Long oldModified = null; private static HashMap<String, String> pdpMap = null; - private static final Logger LOGGER = FlexLogger.getLogger(CheckPDP.class); + private static final Logger LOGGER = FlexLogger.getLogger(CheckPdpProperties.class); - private CheckPDP() { - //default constructor + private CheckPdpProperties() { + // default constructor } public static Map<String, String> getPdpMap() { @@ -76,7 +77,13 @@ public class CheckPDP { pdpMap = null; } - public static boolean validateID(String id) { + /** + * validateId - validates that the ID is in the properties. + * + * @param id Input ID + * @return true it is in the properties + */ + public static boolean validateId(String id) { // ReadFile try { readFile(); @@ -94,7 +101,7 @@ public class CheckPDP { private static void readFile() { String pdpFile; try { - pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE); + pdpFile = XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_IDFILE); } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot read the PDP ID File" + e); return; @@ -104,10 +111,9 @@ 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()); - CheckPDP.reset(); + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path : " + + pdpPath.toString()); + CheckPdpProperties.reset(); return; } readProps(); @@ -134,18 +140,18 @@ public class CheckPDP { List<String> sorted = new ArrayList(unsorted); Collections.sort(sorted); for (String propKey : sorted) { - loadPDPProperties(propKey, pdpProp); + loadPdpProperties(propKey, pdpProp); } } catch (IOException e) { LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); } if (pdpMap == null || pdpMap.isEmpty()) { LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Proceed without PDP_URLs"); - CheckPDP.reset(); + CheckPdpProperties.reset(); } } - private static void loadPDPProperties(String propKey, Properties pdpProp) { + private static void loadPdpProperties(String propKey, Properties pdpProp) { if (propKey.startsWith("PDP_URL")) { String checkVal = pdpProp.getProperty(propKey); if (checkVal == null) { @@ -156,14 +162,14 @@ public class CheckPDP { int pdpCount = 0; while (pdpCount < pdpDefault.size()) { String pdpVal = pdpDefault.get(pdpCount); - readPDPParam(pdpVal); + readPdpParam(pdpVal); pdpCount++; } } } } - private static void readPDPParam(String pdpVal) { + private static void readPdpParam(String pdpVal) { if (pdpVal.contains(",")) { List<String> pdpValues = new ArrayList<>(Arrays.asList(pdpVal.split("\\s*,\\s*"))); if (pdpValues.size() == 3) { @@ -173,7 +179,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); } @@ -182,6 +188,13 @@ public class CheckPDP { } } + /** + * getEncoding reads in the PDP properties and returns an encoding + * for the given pdp. + * + * @param pdpID Input PDP Id + * @return String encoding + */ public static String getEncoding(String pdpID) { try { readFile(); @@ -196,8 +209,7 @@ public class CheckPDP { LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); } return encoding; - } else { - return null; } + return null; } } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java index 6aa40dacf..343a19f1a 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,12 +39,16 @@ 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); + /** + * configure. + * + * @param policyAdapter PolicyRestAdapter object + * @param entity PolicyEntity object + */ public void configure(PolicyRestAdapter policyAdapter, PolicyEntity entity) { String policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf('_')); String configPolicyName = getConfigPolicyName(policyAdapter); @@ -63,28 +69,25 @@ public class PolicyAdapter { } private String getConfigPolicyName(PolicyRestAdapter policyAdapter) { - String configPolicyName = null; if (policyAdapter.getPolicyName().startsWith("Config_PM")) { - configPolicyName = "ClosedLoop_PM"; + return "ClosedLoop_PM"; } else if (policyAdapter.getPolicyName().startsWith("Config_Fault")) { - configPolicyName = "ClosedLoop_Fault"; + return "ClosedLoop_Fault"; } else if (policyAdapter.getPolicyName().startsWith("Config_FW")) { - configPolicyName = "Firewall Config"; + return "Firewall Config"; } else if (policyAdapter.getPolicyName().startsWith("Config_BRMS_Raw")) { - configPolicyName = "BRMS_Raw"; + return "BRMS_Raw"; } else if (policyAdapter.getPolicyName().startsWith("Config_BRMS_Param")) { - configPolicyName = "BRMS_Param"; + return "BRMS_Param"; } else if (policyAdapter.getPolicyName().startsWith("Config_MS")) { - configPolicyName = "Micro Service"; + return "Micro Service"; } else if (policyAdapter.getPolicyName().startsWith("Config_OOF")) { - configPolicyName = "Optimization"; - } else if (policyAdapter.getPolicyName().startsWith("Action") || policyAdapter.getPolicyName() - .startsWith("Decision")) { - // No configPolicyName is applicable - } else { - configPolicyName = "Base"; + return "Optimization"; + } else if (policyAdapter.getPolicyName().startsWith("Action") + || policyAdapter.getPolicyName().startsWith("Decision")) { + return null; } - return configPolicyName; + return "Base"; } private void prePopulatePolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { @@ -107,12 +110,18 @@ public class PolicyAdapter { } } + /** + * getInstance. + * + * @return Returns a PolicyAdapter instance + */ 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..a23a0e821 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. * Modifications Copyright (C) 2019 Bell Canada * ================================================================================ @@ -63,6 +63,7 @@ import org.apache.commons.compress.utils.IOUtils; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; +import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpStatus; import org.elasticsearch.common.Strings; import org.json.JSONArray; @@ -73,8 +74,8 @@ import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.components.HumanPolicyComponent; import org.onap.policy.controller.PolicyController; import org.onap.policy.controller.PolicyExportAndImportController; -import org.onap.policy.rest.XACMLRest; -import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.XacmlRest; +import org.onap.policy.rest.XacmlRestProperties; import org.onap.policy.rest.adapter.PolicyRestAdapter; import org.onap.policy.rest.jpa.ActionBodyEntity; import org.onap.policy.rest.jpa.ConfigurationDataEntity; @@ -87,11 +88,16 @@ import org.onap.policy.utils.PolicyUtils; import org.onap.policy.utils.UserUtils.Pair; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.onap.policy.xacml.util.XACMLPolicyScanner; +import org.onap.portalsdk.core.domain.User; 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 +132,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 +149,18 @@ 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; @@ -173,17 +191,17 @@ public class PolicyManagerServlet extends HttpServlet { // // Common initialization // - XACMLRest.xacmlInit(servletConfig); + XacmlRest.xacmlInit(servletConfig); // init aes key from prop or env - PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY)); + PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XacmlRestProperties.PROP_AES_KEY)); // // Initialize ClosedLoop JSON // - PolicyManagerServlet.initializeJSONLoad(); + PolicyManagerServlet.initializeJsonLoad(); } - private static void initializeJSONLoad() { - Path closedLoopJsonLocation = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP)); + private static void initializeJsonLoad() { + Path closedLoopJsonLocation = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_ADMIN_CLOSEDLOOP)); String location = closedLoopJsonLocation.toString(); if (!location.endsWith("json")) { LOGGER.warn("JSONConfig file does not end with extension .json"); @@ -208,7 +226,7 @@ public class PolicyManagerServlet extends HttpServlet { LOGGER.debug("doPost"); try { // if request contains multipart-form-data - if (ServletFileUpload.isMultipartContent(request)) { + if (isMultipartContent(request)) { uploadFile(request, response); } // all other post request has json params in body @@ -224,10 +242,14 @@ public class PolicyManagerServlet extends HttpServlet { } } + protected boolean isMultipartContent(HttpServletRequest request) { + return ServletFileUpload.isMultipartContent(request); + } + // Set Error Message for Exception - private void setError(Exception t, HttpServletResponse response) throws IOException { + private void setError(Exception exception, HttpServletResponse response) throws IOException { try { - JSONObject responseJsonObject = error(t.getMessage()); + JSONObject responseJsonObject = error(exception.getMessage()); response.setContentType(CONTENTTYPE); PrintWriter out = response.getWriter(); out.print(responseJsonObject); @@ -242,20 +264,24 @@ public class PolicyManagerServlet extends HttpServlet { private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException { try { Map<String, InputStream> files = new HashMap<>(); - + String resp = null; List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { // Process form file field (input type="file"). files.put(item.getName(), item.getInputStream()); - processFormFile(request, item); + resp = processFormFile(request, item, response); } } - JSONObject responseJsonObject; - responseJsonObject = this.success(); response.setContentType(CONTENTTYPE); PrintWriter out = response.getWriter(); + JSONObject responseJsonObject; + if (!StringUtils.isBlank(resp)) { + responseJsonObject = this.error("Import Issue " + resp); + } else { + responseJsonObject = this.success(); + } out.print(responseJsonObject); out.flush(); } catch (Exception e) { @@ -264,23 +290,35 @@ public class PolicyManagerServlet extends HttpServlet { } } - private void processFormFile(HttpServletRequest request, FileItem item) { + private String processFormFile(HttpServletRequest request, FileItem item, HttpServletResponse response) { String newFile; - if (item.getName().endsWith(".xls") && item.getSize() <= PolicyController.getFileSizeLimit()) { + String outPutResp = null; + if (item.getName().endsWith(".xls") && item.getSize() <= getFileSizeLimit()) { File file = new File(item.getName()); try (OutputStream outputStream = new FileOutputStream(file)) { IOUtils.copy(item.getInputStream(), outputStream); newFile = file.toString(); PolicyExportAndImportController importController = new PolicyExportAndImportController(); - importController.importRepositoryFile(newFile, request); + return importController.importRepositoryFile(newFile, request); } catch (Exception e) { LOGGER.error("Upload error : " + e); } } else if (!item.getName().endsWith(".xls")) { - LOGGER.error("Non .xls filetype uploaded: " + item.getName()); + outPutResp = "Non .xls filetype uploaded: " + item.getName(); + LOGGER.error(outPutResp); } else { // uploaded file size is greater than allowed - LOGGER.error("Upload file size limit exceeded! File size (Bytes) is: " + item.getSize()); + outPutResp = "Upload file size limit exceeded! File size (Bytes) is: " + item.getSize(); + LOGGER.error(outPutResp); } + return outPutResp; + } + + protected long copyStream(InputStream inputStream, OutputStream outputStream) throws IOException { + return IOUtils.copy(inputStream, outputStream); + } + + protected long getFileSizeLimit() { + return PolicyController.getFileSizeLimit(); } // File Operation Functionality @@ -299,17 +337,17 @@ public class PolicyManagerServlet extends HttpServlet { return; } try { - JSONObject jObj = new JSONObject(sb.toString()); - JSONObject params = jObj.getJSONObject("params"); + JSONObject jsonObject = new JSONObject(sb.toString()); + JSONObject params = jsonObject.getJSONObject("params"); Mode mode = Mode.valueOf(params.getString("mode")); - String userId = UserUtils.getUserSession(request).getOrgUserId(); + String userId = getUserSession(request).getOrgUserId(); LOGGER.info( - "****************************************Logging UserID while doing actions on Editor tab*******************************************"); + "********************Logging UserID while doing actions on Editor tab****************************"); LOGGER.info( "UserId: " + userId + "Action Mode: " + mode.toString() + "Action Params: " + params.toString()); LOGGER.info( - "***********************************************************************************************************************************"); + "************************************************************************************************"); responseJsonObject = operateBasedOnMode(mode, params, request); } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Processing Json" + e); @@ -318,6 +356,10 @@ public class PolicyManagerServlet extends HttpServlet { setResponse(response, responseJsonObject); } + protected User getUserSession(HttpServletRequest request) { + return UserUtils.getUserSession(request); + } + private void setResponse(HttpServletResponse response, JSONObject responseJsonObject) { response.setContentType(CONTENTTYPE); try (PrintWriter out = response.getWriter()) { @@ -371,7 +413,6 @@ public class PolicyManagerServlet extends HttpServlet { } private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) { - List<Object> policyData = new ArrayList<>(); JSONArray policyList = null; if (params.has("policyList")) { policyList = (JSONArray) params.get("policyList"); @@ -379,9 +420,9 @@ public class PolicyManagerServlet extends HttpServlet { PolicyController controller = getPolicyControllerInstance(); List<JSONObject> resultList = new ArrayList<>(); try { - if (!lookupPolicyData(request, policyData, policyList, controller, resultList)) + if (!lookupPolicyData(request, new ArrayList<>(), policyList, controller, resultList)) { return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin"); - + } } catch (Exception e) { LOGGER.error( "Exception occured while reading policy Data from Policy Version table for Policy Search Data" + e); @@ -392,13 +433,11 @@ public class PolicyManagerServlet extends HttpServlet { private boolean lookupPolicyData(HttpServletRequest request, List<Object> policyData, JSONArray policyList, PolicyController controller, List<JSONObject> resultList) { - List<String> roles; - Set<String> scopes;// Get the Login Id of the User from Request - String userId = UserUtils.getUserSession(request).getOrgUserId(); + String userId = 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; + Pair<Set<String>, List<String>> pair = checkRoleAndScope(userRoles); + List<String> roles = pair.second; + Set<String> scopes = pair.first; if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)) { if (scopes.isEmpty()) { return false; @@ -415,12 +454,16 @@ public class PolicyManagerServlet extends HttpServlet { parsePolicyList(resultList, controller, policyName, version); } } else { - getPolicyDataForSUPERRoles(policyData, controller, resultList, roles, scopes); + getPolicyDataForSuperRoles(policyData, controller, resultList, roles, scopes); } return true; } - private void getPolicyDataForSUPERRoles(List<Object> policyData, PolicyController controller, + protected Pair<Set<String>, List<String>> checkRoleAndScope(List<Object> userRoles) { + return org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles); + } + + private void getPolicyDataForSuperRoles(List<Object> policyData, PolicyController controller, List<JSONObject> resultList, List<String> roles, Set<String> scopes) { if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) { policyData = controller.getData(PolicyVersion.class); @@ -448,8 +491,8 @@ public class PolicyManagerServlet extends HttpServlet { } private void updateResultList(List<Object> policyData, List<JSONObject> resultList) { - for (Object aPolicyData : policyData) { - PolicyVersion policy = (PolicyVersion) aPolicyData; + for (Object data : policyData) { + PolicyVersion policy = (PolicyVersion) data; JSONObject el = new JSONObject(); el.put(NAME, policy.getPolicyName().replace(File.separator, FORWARD_SLASH)); el.put(DATE, policy.getModifiedDate()); @@ -467,7 +510,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); @@ -489,8 +533,8 @@ public class PolicyManagerServlet extends HttpServlet { private void addScope(Set<String> scopes, String scope) { List<Object> scopesList = queryPolicyEditorScopes(scope); if (!scopesList.isEmpty()) { - for (Object aScopesList : scopesList) { - PolicyEditorScopes tempScope = (PolicyEditorScopes) aScopesList; + for (Object scopeItem : scopesList) { + PolicyEditorScopes tempScope = (PolicyEditorScopes) scopeItem; scopes.add(tempScope.getScopeName()); } } @@ -501,7 +545,7 @@ public class PolicyManagerServlet extends HttpServlet { String path = params.getString("path"); String userId = null; try { - userId = UserUtils.getUserSession(request).getOrgUserId(); + userId = getUserSession(request).getOrgUserId(); } catch (Exception e) { LOGGER.error("Exception Occured while reading userid from cookie" + e); } @@ -524,11 +568,11 @@ public class PolicyManagerServlet extends HttpServlet { return error("The Version shouldn't be greater than Highest Value"); } activePolicy = policyName + "." + activeVersion + ".xml"; - String[] splitDBCheckName = modifyPolicyName(activePolicy); + String[] splitDbCheckName = modifyPolicyName(activePolicy); String peQuery = "FROM PolicyEntity where policyName = :splitDBCheckName_1 and scope = :splitDBCheckName_0"; SimpleBindings policyParams = new SimpleBindings(); - policyParams.put("splitDBCheckName_1", splitDBCheckName[1]); - policyParams.put("splitDBCheckName_0", splitDBCheckName[0]); + policyParams.put("splitDBCheckName_1", splitDbCheckName[1]); + policyParams.put("splitDBCheckName_0", splitDbCheckName[0]); List<Object> policyEntity = controller.getDataByQuery(peQuery, policyParams); PolicyEntity pentity = (PolicyEntity) policyEntity.get(0); if (pentity.isDeleted()) { @@ -541,8 +585,8 @@ public class PolicyManagerServlet extends HttpServlet { if (policyName.contains(BACKSLASH)) { policyName = policyName.replace(File.separator, BACKSLASH); } - policyName = splitDBCheckName[0].replace(".", File.separator) + File.separator + policyName; - String watchPolicyName = policyName; + policyName = splitDbCheckName[0].replace(".", File.separator) + File.separator + policyName; + final String watchPolicyName = policyName; if (policyName.contains(FORWARD_SLASH)) { policyName = policyName.replace(FORWARD_SLASH, File.separator); } @@ -564,7 +608,6 @@ public class PolicyManagerServlet extends HttpServlet { // Describe Policy private JSONObject describePolicy(JSONObject params) throws ServletException { - JSONObject object; String path = params.getString("path"); String policyName; if (path.startsWith(FORWARD_SLASH)) { @@ -582,13 +625,12 @@ public class PolicyManagerServlet extends HttpServlet { } else if (path.contains(DECISION2)) { path = path.replace(DECISION, DECISION1); } - PolicyController controller = getPolicyControllerInstance(); String[] split = path.split(":"); String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0"; SimpleBindings peParams = new SimpleBindings(); peParams.put(SPLIT_1, split[1]); peParams.put(SPLIT_0, split[0]); - List<Object> queryData = getDataByQueryFromController(controller, query, peParams); + List<Object> queryData = getDataByQueryFromController(getPolicyControllerInstance(), query, peParams); if (queryData.isEmpty()) { return error("Error Occured while Describing the Policy - query is empty"); } @@ -606,7 +648,7 @@ public class PolicyManagerServlet extends HttpServlet { } catch (IOException e) { LOGGER.error("Exception Occured while Describing the Policy" + e); } - object = HumanPolicyComponent.DescribePolicy(temp); + JSONObject object = HumanPolicyComponent.DescribePolicy(temp); try { Files.delete(temp.toPath()); } catch (IOException e) { @@ -626,14 +668,13 @@ public class PolicyManagerServlet extends HttpServlet { } private JSONObject processPolicyList(JSONObject params, HttpServletRequest request) throws ServletException { - PolicyController controller = getPolicyControllerInstance(); // Get the Login Id of the User from Request String testUserID = getTestUserId(); - String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId(); - List<Object> userRoles = controller.getRoles(userId); - Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles); - List<String> roles = pair.u; - Set<String> scopes = pair.t; + String userId = testUserID != null ? testUserID : getUserSession(request).getOrgUserId(); + List<Object> userRoles = getPolicyControllerInstance().getRoles(userId); + Pair<Set<String>, List<String>> pair = checkRoleAndScope(userRoles); + List<String> roles = pair.second; + Set<String> scopes = pair.first; Map<String, String> roleByScope = org.onap.policy.utils.UserUtils.getRoleByScope(userRoles); List<JSONObject> resultList = new ArrayList<>(); @@ -672,39 +713,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); + } + }); } } @@ -724,7 +763,6 @@ public class PolicyManagerServlet extends HttpServlet { // Get Active Policy List based on Scope Selection from Policy Version table private void activePolicyList(String inScopeName, List<JSONObject> resultList, List<String> roles, Set<String> scopes, Map<String, String> roleByScope) { - PolicyController controller = getPolicyControllerInstance(); String scopeName = inScopeName; if (scopeName.contains(FORWARD_SLASH)) { scopeName = scopeName.replace(FORWARD_SLASH, File.separator); @@ -737,20 +775,20 @@ public class PolicyManagerServlet extends HttpServlet { SimpleBindings params = new SimpleBindings(); params.put(SCOPE_NAME, scopeName + "%"); - List<Object> activePolicies = getDataByQueryFromController(controller, query, params); - List<Object> scopesList = getDataByQueryFromController(controller, - FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME, params); + List<Object> activePolicies = getDataByQueryFromController(getPolicyControllerInstance(), query, params); + List<Object> scopesList = getDataByQueryFromController(getPolicyControllerInstance(), + 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 +800,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 +819,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); @@ -828,8 +866,8 @@ public class PolicyManagerServlet extends HttpServlet { } private String getUserName(String loginId) { - PolicyController controller = getPolicyControllerInstance(); - UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId); + UserInfo userInfo = (UserInfo) getPolicyControllerInstance().getEntityItem(UserInfo.class, "userLoginId", + loginId); if (userInfo == null) { return SUPERADMIN; } @@ -848,9 +886,9 @@ public class PolicyManagerServlet extends HttpServlet { private JSONObject handlePolicyRename(JSONObject params, HttpServletRequest request) throws ServletException { boolean isActive = false; - List<String> policyActiveInPDP = new ArrayList<>(); - Set<String> scopeOfPolicyActiveInPDP = new HashSet<>(); - String userId = UserUtils.getUserSession(request).getOrgUserId(); + List<String> policyActiveInPdp = new ArrayList<>(); + Set<String> scopeOfPolicyActiveInPdp = new HashSet<>(); + String userId = getUserSession(request).getOrgUserId(); String oldPath = params.getString("path"); String newPath = params.getString("newPath"); oldPath = oldPath.substring(oldPath.indexOf('/') + 1); @@ -858,8 +896,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 +926,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) + "." @@ -897,19 +936,19 @@ public class PolicyManagerServlet extends HttpServlet { JSONObject result = policyRename(policyOldPath, policyNewPath, userId); if (!(Boolean) (result.getJSONObject("result").get(SUCCESS))) { isActive = true; - policyActiveInPDP.add(policyOldPath); + policyActiveInPdp.add(policyOldPath); String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf('/')); - scopeOfPolicyActiveInPDP.add(scope.replace(FORWARD_SLASH, File.separator)); + scopeOfPolicyActiveInPdp.add(scope.replace(FORWARD_SLASH, File.separator)); } } - boolean rename = activePolicies.size() != policyActiveInPDP.size(); - if (policyActiveInPDP.isEmpty()) { + boolean rename = activePolicies.size() != policyActiveInPdp.size(); + if (policyActiveInPdp.isEmpty()) { renameScope(scopesList, scopeName, newScopeName, controller); } else if (rename) { renameScope(scopesList, scopeName, newScopeName, controller); UserInfo userInfo = new UserInfo(); userInfo.setUserLoginId(userId); - scopeOfPolicyActiveInPDP.forEach(scope -> { + scopeOfPolicyActiveInPdp.forEach(scope -> { PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes(); editorScopeEntity.setScopeName(scope.replace(BACKSLASH, BACKSLASH_8TIMES)); editorScopeEntity.setUserCreatedBy(userInfo); @@ -919,7 +958,7 @@ public class PolicyManagerServlet extends HttpServlet { } if (isActive) { return error("The Following policies rename failed. Since they are active in PDP Groups" - + policyActiveInPDP); + + policyActiveInPdp); } } return success(); @@ -955,10 +994,11 @@ public class PolicyManagerServlet extends HttpServlet { String newpolicyName = newPath.replace("/", "."); String[] newPolicySplit = modifyPolicyName(newPath); - String[] oldPolicySplit = modifyPolicyName(oldPath); + final 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,15 +1009,15 @@ public class PolicyManagerServlet extends HttpServlet { // Query the Policy Entity with oldPolicy Name String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf('.')); - String oldPolicyEntityQuery = "FROM PolicyEntity where policyName like :policyEntityCheck and scope = " - + ":oldPolicySplit_0"; + String oldPolicyEntityQuery = + "FROM PolicyEntity where policyName like :policyEntityCheck and scope = " + ":oldPolicySplit_0"; SimpleBindings params = new SimpleBindings(); params.put("policyEntityCheck", policyEntityCheck + "%"); params.put("oldPolicySplit_0", oldPolicySplit[0]); List<Object> oldEntityData = controller.getDataByQuery(oldPolicyEntityQuery, params); if (oldEntityData.isEmpty()) { return error( - "Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin."); + "Policy rename failed due to policy not able to retrieve from database. Contact super-admin."); } StringBuilder groupQuery = new StringBuilder(); @@ -1042,10 +1082,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 +1105,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,17 +1118,17 @@ 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); } } controller.updateData(entity); PolicyRestController restController = new PolicyRestController(); - restController.notifyOtherPAPSToUpdateConfigurations("rename", newConfigurationName, oldConfigurationName); - PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", - oldPolicyName); + restController.notifyOtherPapsToUpdateConfigurations("rename", newConfigurationName, oldConfigurationName); + PolicyVersion versionEntity = + (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldPolicyName); versionEntity.setPolicyName(policyName); versionEntity.setModifiedBy(userId); controller.updateData(versionEntity); @@ -1136,8 +1176,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 +1198,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) { @@ -1175,13 +1215,13 @@ public class PolicyManagerServlet extends HttpServlet { // Notify others paps regarding clone policy. PolicyRestController restController = new PolicyRestController(); - restController.notifyOtherPAPSToUpdateConfigurations("clonePolicy", newConfigurationName, null); + restController.notifyOtherPapsToUpdateConfigurations("clonePolicy", newConfigurationName, null); } // Clone the Policy private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException { try { - String userId = UserUtils.getUserSession(request).getOrgUserId(); + String userId = getUserSession(request).getOrgUserId(); String oldPath = params.getString("path"); String newPath = params.getString("newPath"); oldPath = oldPath.substring(oldPath.indexOf('/') + 1); @@ -1194,8 +1234,6 @@ public class PolicyManagerServlet extends HttpServlet { String newPolicyName = newPath.replace(FORWARD_SLASH, "."); - String originalPolicyName = oldPath.replace(FORWARD_SLASH, "."); - String newPolicyCheck = newPolicyName; if (newPolicyCheck.contains(CONFIG2)) { newPolicyCheck = newPolicyCheck.replace(CONFIG, CONFIG1); @@ -1210,13 +1248,15 @@ 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."); } - String[] oldPolicySplit = modifyPolicyName(originalPolicyName); + String originalPolicyName = oldPath.replace(FORWARD_SLASH, "."); + + final String[] oldPolicySplit = modifyPolicyName(originalPolicyName); PolicyController controller = getPolicyControllerInstance(); @@ -1224,7 +1264,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]); @@ -1272,7 +1313,7 @@ public class PolicyManagerServlet extends HttpServlet { PolicyEntity policyEntity = null; String policyNamewithoutExtension; try { - String userId = UserUtils.getUserSession(request).getOrgUserId(); + String userId = getUserSession(request).getOrgUserId(); String deleteVersion = ""; String path = params.getString("path"); LOGGER.debug("delete {}" + path); @@ -1307,8 +1348,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 +1357,7 @@ public class PolicyManagerServlet extends HttpServlet { activePolicyName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); } else { deleteEntityFromEsAndPolicyEntityTable(controller, restController, policyEntity, - policyNamewithoutExtension); + policyNamewithoutExtension); } } } @@ -1327,15 +1368,15 @@ public class PolicyManagerServlet extends HttpServlet { controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll"); if (pdpCheck) { // Delete from policyVersion table - String getActivePDPPolicyVersion = activePolicyName.replace(".xml", ""); - getActivePDPPolicyVersion = getActivePDPPolicyVersion - .substring(getActivePDPPolicyVersion.lastIndexOf('.') + 1); - String policyVersionQuery = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION + getActivePDPPolicyVersion - + "' , highest_version='" + getActivePDPPolicyVersion + "' where policy_name ='" + String getActivePdpPolicyVersion = activePolicyName.replace(".xml", ""); + 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"; controller.executeQuery(policyVersionQuery); return error( - "Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: " + "Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: " + activePolicyName); } else { // No Active Policy in PDP. So, deleting all entries from policyVersion table @@ -1344,12 +1385,13 @@ 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, "."); - query = "FROM PolicyEntity where policyName = :currentVersionPolicyName and scope = :currentVersionScope"; + 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(); peParams.put("currentVersionPolicyName", currentVersionPolicyName); @@ -1363,7 +1405,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 +1417,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; @@ -1414,7 +1457,7 @@ public class PolicyManagerServlet extends HttpServlet { } } } else { - List<String> activePoliciesInPDP = new ArrayList<>(); + List<String> activePoliciesInPdp = new ArrayList<>(); if (policyEntityObjects.isEmpty()) { String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '" + path.replace(BACKSLASH, ESCAPE_BACKSLASH) + PERCENT_AND_ID_GT_0; @@ -1429,7 +1472,7 @@ public class PolicyManagerServlet extends HttpServlet { List<Object> groupobject = controller.getDataByQuery(groupEntityQuery, geParams); if (!groupobject.isEmpty()) { pdpCheck = true; - activePoliciesInPDP.add(policyEntity.getScope() + "." + policyEntity.getPolicyName()); + activePoliciesInPdp.add(policyEntity.getScope() + "." + policyEntity.getPolicyName()); } else { // Delete the entity from Elastic Search Database String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); @@ -1441,13 +1484,13 @@ public class PolicyManagerServlet extends HttpServlet { Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName())); controller.deleteData(policyEntity.getConfigurationData()); - restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, + restController.notifyOtherPapsToUpdateConfigurations(DELETE, null, policyEntity.getConfigurationData().getConfigurationName()); } else if (policyNamewithoutExtension.contains(ACTION2)) { Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName())); controller.deleteData(policyEntity.getActionBodyEntity()); - restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, + restController.notifyOtherPapsToUpdateConfigurations(DELETE, null, policyEntity.getActionBodyEntity().getActionBodyName()); } } @@ -1464,22 +1507,22 @@ public class PolicyManagerServlet extends HttpServlet { controller.watchPolicyFunction(entity, path, "DeleteScope"); if (pdpCheck) { // Add Active Policies List to PolicyVersionTable - for (String anActivePoliciesInPDP : activePoliciesInPDP) { - String activePDPPolicyName = anActivePoliciesInPDP.replace(".xml", ""); - int activePDPPolicyVersion = Integer - .parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf('.') + 1)); - activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf('.')) + for (String anActivePoliciesInPdp : activePoliciesInPdp) { + String activePdpPolicyName = anActivePoliciesInPdp.replace(".xml", ""); + int activePdpPolicyVersion = Integer + .parseInt(activePdpPolicyName.substring(activePdpPolicyName.lastIndexOf('.') + 1)); + activePdpPolicyName = activePdpPolicyName.substring(0, activePdpPolicyName.lastIndexOf('.')) .replace(".", File.separator); - PolicyVersion insertActivePDPVersion = new PolicyVersion(); - insertActivePDPVersion.setPolicyName(activePDPPolicyName); - insertActivePDPVersion.setHigherVersion(activePDPPolicyVersion); - insertActivePDPVersion.setActiveVersion(activePDPPolicyVersion); - insertActivePDPVersion.setCreatedBy(userId); - insertActivePDPVersion.setModifiedBy(userId); - controller.saveData(insertActivePDPVersion); + PolicyVersion insertActivePdpVersion = new PolicyVersion(); + insertActivePdpVersion.setPolicyName(activePdpPolicyName); + insertActivePdpVersion.setHigherVersion(activePdpPolicyVersion); + insertActivePdpVersion.setActiveVersion(activePdpPolicyVersion); + insertActivePdpVersion.setCreatedBy(userId); + insertActivePdpVersion.setModifiedBy(userId); + controller.saveData(insertActivePdpVersion); } return error("All the Policies has been deleted in Scope. Except the following list of Policies:" - + activePoliciesInPDP); + + activePoliciesInPdp); } else { String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '" + path.replace(BACKSLASH, ESCAPE_BACKSLASH) + PERCENT_AND_ID_GT_0; @@ -1495,8 +1538,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 +1547,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()); + restController.notifyOtherPapsToUpdateConfigurations(DELETE, null, + 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()); + restController.notifyOtherPapsToUpdateConfigurations(DELETE, null, + policyEntity.getActionBodyEntity().getActionBodyName()); } } @@ -1521,8 +1564,7 @@ public class PolicyManagerServlet extends HttpServlet { private JSONObject editFile(JSONObject params) throws ServletException { // get content try { - PolicyController controller = getPolicyControllerInstance(); - String mode = params.getString("mode"); + final String mode = params.getString("mode"); String path = params.getString("path"); LOGGER.debug("editFile path: {}" + path); @@ -1538,7 +1580,7 @@ public class PolicyManagerServlet extends HttpServlet { SimpleBindings peParams = new SimpleBindings(); peParams.put(SPLIT_1, split[1]); peParams.put(SPLIT_0, split[0]); - List<Object> queryData = getDataByQueryFromController(controller, query, peParams); + List<Object> queryData = getDataByQueryFromController(getPolicyControllerInstance(), query, peParams); PolicyEntity entity = (PolicyEntity) queryData.get(0); InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8)); @@ -1577,11 +1619,10 @@ public class PolicyManagerServlet extends HttpServlet { // Add Scopes private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException { - PolicyController controller = getPolicyControllerInstance(); 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,19 +1632,20 @@ 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) getPolicyControllerInstance().getEntityItem( + PolicyEditorScopes.class, SCOPE_NAME, name); if (entity != null) { return error("Scope Already Exists"); } - String userId = UserUtils.getUserSession(request).getOrgUserId(); + String userId = getUserSession(request).getOrgUserId(); UserInfo userInfo = new UserInfo(); userInfo.setUserLoginId(userId); PolicyEditorScopes newScope = new PolicyEditorScopes(); newScope.setScopeName(name); newScope.setUserCreatedBy(userInfo); newScope.setUserModifiedBy(userInfo); - controller.saveData(newScope); + getPolicyControllerInstance().saveData(newScope); } return success(); } catch (Exception e) { 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..34a95d98b 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,16 +2,16 @@ * ============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 * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -48,20 +48,26 @@ import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; /** - * Send policy notification mail depending on the mode for every policy being watched + * 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); + /** + * javaMailSenderImpl. + * + * @return JavaMailSenderImpl object + */ @Bean - public JavaMailSenderImpl javaMailSenderImpl(){ + public JavaMailSenderImpl javaMailSenderImpl() { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost(PolicyController.getSmtpHost()); mailSender.setPort(Integer.parseInt(PolicyController.getSmtpPort())); @@ -79,51 +85,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 +173,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 +181,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 +196,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; @@ -178,29 +204,31 @@ 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 - * @param message - * @param checkPolicyName - * @param watchList + * send the notification. + * + * @param mode String for the mode + * @param policyNotificationDao CommonClassDao + * @param subject String subject + * @param message String message + * @param checkPolicyName String check policy name + * @param watchList List of watch objects */ - 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 condition 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 +240,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..76bb04945 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; @@ -53,7 +56,7 @@ import org.onap.policy.controller.CreateDcaeMicroServiceController; import org.onap.policy.controller.CreateFirewallController; import org.onap.policy.controller.CreateOptimizationController; import org.onap.policy.controller.PolicyController; -import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.XacmlRestProperties; import org.onap.policy.rest.adapter.PolicyRestAdapter; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.PolicyVersion; @@ -121,29 +124,32 @@ public class PolicyRestController extends RestrictedBaseController { PolicyRestController.commonClassDao = commonClassDao; } - - + /** + * policyCreationController. + * + * @param request Request + * @param response Response + */ @RequestMapping(value = {"/policycreation/save_policy"}, method = {RequestMethod.POST}) public void policyCreationController(HttpServletRequest request, HttpServletResponse response) { - String userId = UserUtils.getUserSession(request).getOrgUserId(); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); try { - updateAndSendToPAP(request, response, userId, mapper); + updateAndSendToPap(request, response, UserUtils.getUserSession(request).getOrgUserId(), mapper); } catch (Exception e) { policyLogger.error("Exception Occured while saving policy", e); } } - private void updateAndSendToPAP(HttpServletRequest request, HttpServletResponse response, String userId, + private void updateAndSendToPap(HttpServletRequest request, HttpServletResponse response, String userId, ObjectMapper mapper) throws IOException { JsonNode root = mapper.readTree(request.getReader()); policyLogger.info( - "****************************************Logging UserID while Create/Update Policy**************************************************"); + "********************Logging UserID while Create/Update Policy***********************************"); policyLogger.info(USER_ID + userId + "Policy Data Object: " + root.get(PolicyController.getPolicydata()).get("policy").toString()); policyLogger.info( - "***********************************************************************************************************************************"); + "************************************************************************************************"); PolicyRestAdapter policyData = mapper.readValue( root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class); @@ -164,17 +170,16 @@ public class PolicyRestController extends RestrictedBaseController { policyData.setUserId(userId); String result; - String body = PolicyUtils.objectToJsonString(policyData); - String uri = request.getRequestURI(); - ResponseEntity<?> responseEntity = sendToPAP(body, uri, HttpMethod.POST); + ResponseEntity<?> responseEntity = sendToPap(PolicyUtils.objectToJsonString(policyData), + request.getRequestURI(), HttpMethod.POST); if (responseEntity != null && responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)) { result = "PolicyExists"; } else if (responseEntity != null) { result = responseEntity.getBody().toString(); String policyName = responseEntity.getHeaders().get(POLICY_NAME).get(0); if (policyData.isEditPolicy() && SUCCESS.equalsIgnoreCase(result)) { - PolicyNotificationMail email = new PolicyNotificationMail(); - String mode = "EditPolicy"; + final PolicyNotificationMail email = new PolicyNotificationMail(); + final String mode = "EditPolicy"; String watchPolicyName = policyName.replace(XML, ""); String version = watchPolicyName.substring(watchPolicyName.lastIndexOf('.') + 1); watchPolicyName = @@ -197,8 +202,8 @@ public class PolicyRestController extends RestrictedBaseController { PrintWriter out = response.getWriter(); String responseString = mapper.writeValueAsString(result); - JSONObject j = new JSONObject("{policyData: " + responseString + "}"); - out.write(j.toString()); + JSONObject json = new JSONObject("{policyData: " + responseString + "}"); + out.write(json.toString()); } private void modifyPolicyData(JsonNode root, PolicyRestAdapter policyData) { @@ -227,13 +232,12 @@ public class PolicyRestController extends RestrictedBaseController { } } - - private ResponseEntity<?> sendToPAP(String body, String requestURI, HttpMethod method) { + private ResponseEntity<?> sendToPap(String body, String requestUri, HttpMethod method) { String papUrl = PolicyController.getPapUrl(); - String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); - String papPass = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)); - Base64.Encoder encoder = Base64.getEncoder(); - String encoding = encoder.encodeToString((papID + ":" + papPass).getBytes(StandardCharsets.UTF_8)); + String papPass = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_PASS)); + String encoding = Base64.getEncoder().encodeToString( + (XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_USERID) + + ":" + papPass).getBytes(StandardCharsets.UTF_8)); HttpHeaders headers = new HttpHeaders(); headers.set(AUTHORIZATION, BASIC + encoding); headers.set(CONTENT_TYPE, PolicyController.getContenttype()); @@ -242,7 +246,7 @@ public class PolicyRestController extends RestrictedBaseController { HttpEntity<?> requestEntity = new HttpEntity<>(body, headers); ResponseEntity<?> result = null; HttpClientErrorException exception = null; - String uri = requestURI; + String uri = requestUri; if (uri.startsWith("/")) { uri = uri.substring(uri.indexOf('/') + 1); } @@ -279,27 +283,24 @@ public class PolicyRestController extends RestrictedBaseController { return result; } - private String callPAP(HttpServletRequest request, String method, String uriValue) { - String uri = uriValue; - String papUrl = PolicyController.getPapUrl(); - String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); - PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY)); - String papPass = PeCryptoUtils.decrypt((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS))); + private String callPap(HttpServletRequest request, String method, String uriValue) { + PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XacmlRestProperties.PROP_AES_KEY)); + String papPass = PeCryptoUtils.decrypt((XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_PASS))); Base64.Encoder encoder = Base64.getEncoder(); - String encoding = encoder.encodeToString((papID + ":" + papPass).getBytes(StandardCharsets.UTF_8)); + String encoding = encoder.encodeToString((XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_USERID) + + ":" + papPass).getBytes(StandardCharsets.UTF_8)); HttpHeaders headers = new HttpHeaders(); headers.set(AUTHORIZATION, BASIC + encoding); headers.set(CONTENT_TYPE, PolicyController.getContenttype()); - HttpURLConnection connection = null; - List<FileItem> items; FileItem item = null; File file = null; + String uri = uriValue; if (uri.contains(IMPORT_DICTIONARY)) { try { - items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); + List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); item = items.get(0); file = new File(item.getName()); String newFile = file.toString(); @@ -310,7 +311,7 @@ public class PolicyRestController extends RestrictedBaseController { } try { - URL url = new URL(papUrl + uri); + URL url = new URL(PolicyController.getPapUrl() + uri); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(method); connection.setUseCaches(false); @@ -324,7 +325,7 @@ public class PolicyRestController extends RestrictedBaseController { return doConnect(connection); } - checkURI(request, uri, connection, item); + checkUri(request, uri, connection, item); return doConnect(connection); } catch (Exception e) { @@ -351,9 +352,8 @@ public class PolicyRestController extends RestrictedBaseController { return null; } - private void checkURI(HttpServletRequest request, String uri, HttpURLConnection connection, FileItem item) + private void checkUri(HttpServletRequest request, String uri, HttpURLConnection connection, FileItem item) throws IOException { - String boundary; if (!(uri.endsWith("set_BRMSParamData") || uri.contains(IMPORT_DICTIONARY))) { connection.setRequestProperty(CONTENT_TYPE, PolicyController.getContenttype()); ObjectMapper mapper = new ObjectMapper(); @@ -380,7 +380,7 @@ public class PolicyRestController extends RestrictedBaseController { IOUtils.copy(request.getInputStream(), os); } } else { - boundary = "===" + System.currentTimeMillis() + "==="; + String boundary = "===" + System.currentTimeMillis() + "==="; connection.setRequestProperty(CONTENT_TYPE, "multipart/form-data; boundary=" + boundary); try (OutputStream os = connection.getOutputStream()) { if (item != null) { @@ -402,8 +402,7 @@ public class PolicyRestController extends RestrictedBaseController { private String doConnect(final HttpURLConnection connection) throws IOException { connection.connect(); - int responseCode = connection.getResponseCode(); - if (responseCode == 200) { + if (connection.getResponseCode() == 200) { // get the response content into a String String responseJson = null; // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file) @@ -425,11 +424,17 @@ public class PolicyRestController extends RestrictedBaseController { return null; } + /** + * getDictionaryController. + * + * @param request Request + * @param response Response + */ @RequestMapping(value = {"/getDictionary/*"}, method = {RequestMethod.GET}) public void getDictionaryController(HttpServletRequest request, HttpServletResponse response) { - String uri = request.getRequestURI().replace("/getDictionary", ""); String body; - ResponseEntity<?> responseEntity = sendToPAP(null, uri, HttpMethod.GET); + ResponseEntity<?> responseEntity = sendToPap(null, request.getRequestURI().replace("/getDictionary", ""), + HttpMethod.GET); if (responseEntity != null) { body = responseEntity.getBody().toString(); } else { @@ -442,6 +447,13 @@ public class PolicyRestController extends RestrictedBaseController { } } + /** + * saveDictionaryController. + * + * @param request Request + * @param response Response + * @throws IOException IO Exception + */ @RequestMapping(value = {"/saveDictionary/*/*"}, method = {RequestMethod.POST}) public void saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException { String userId = ""; @@ -456,12 +468,12 @@ public class PolicyRestController extends RestrictedBaseController { } policyLogger.info( - "****************************************Logging UserID while Saving Dictionary*****************************************************"); + "********************Logging UserID while Saving Dictionary**************************************"); policyLogger.info(USER_ID + userId); policyLogger.info( - "***********************************************************************************************************************************"); + "************************************************************************************************"); - String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim()); + String body = callPap(request, "POST", uri.replaceFirst("/", "").trim()); if (body != null && !body.isEmpty()) { response.getWriter().write(body); } else { @@ -469,6 +481,13 @@ public class PolicyRestController extends RestrictedBaseController { } } + /** + * deletetDictionaryController. + * + * @param request Request + * @param response Response + * @throws IOException IO Exception + */ @RequestMapping(value = {"/deleteDictionary/*/*"}, method = {RequestMethod.POST}) public void deletetDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException { @@ -480,12 +499,12 @@ public class PolicyRestController extends RestrictedBaseController { String userId = UserUtils.getUserSession(request).getOrgUserId(); policyLogger.info( - "****************************************Logging UserID while Deleting Dictionary*****************************************************"); + "**********************Logging UserID while Deleting Dictionary*************************************"); policyLogger.info(USER_ID + userId); policyLogger.info( - "*************************************************************************************************************************************"); + "***************************************************************************************************"); - String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim()); + String body = callPap(request, "POST", uri.replaceFirst("/", "").trim()); if (body != null && !body.isEmpty()) { response.getWriter().write(body); } else { @@ -493,6 +512,14 @@ public class PolicyRestController extends RestrictedBaseController { } } + /** + * searchDictionaryController. + * + * @param request Request + * @param response Response + * @return ModelAndView object + * @throws IOException IO Exception + */ @RequestMapping(value = {"/searchDictionary"}, method = {RequestMethod.POST}) public ModelAndView searchDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException { @@ -503,14 +530,13 @@ public class PolicyRestController extends RestrictedBaseController { } uri = ONAP + uri.substring(uri.indexOf('/')); try { - String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim()); + String body = callPap(request, "POST", uri.replaceFirst("/", "").trim()); if (body.contains("CouldNotConnectException")) { List<String> data = new ArrayList<>(); data.add("Elastic Search Server is down"); resultList = data; } else { - JSONObject json = new JSONObject(body); - resultList = json.get("policyresult"); + resultList = new JSONObject(body).get("policyresult"); } } catch (Exception e) { policyLogger.error( @@ -522,12 +548,18 @@ public class PolicyRestController extends RestrictedBaseController { response.setCharacterEncoding(PolicyController.getCharacterencoding()); response.setContentType(PolicyController.getContenttype()); - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{result: " + resultList + "}"); - out.write(j.toString()); + response.getWriter().write(new JSONObject("{result: " + resultList + "}").toString()); return null; } + /** + * searchPolicy. + * + * @param request request + * @param response response + * @return ModelAndView object + * @throws IOException IO exception + */ @RequestMapping(value = {"/searchPolicy"}, method = {RequestMethod.POST}) public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException { Object resultList; @@ -536,7 +568,7 @@ public class PolicyRestController extends RestrictedBaseController { uri = uri.substring(uri.indexOf('/') + 1); } uri = ONAP + uri.substring(uri.indexOf('/')); - String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim()); + String body = callPap(request, "POST", uri.replaceFirst("/", "").trim()); JSONObject json = new JSONObject(body); try { @@ -554,21 +586,27 @@ public class PolicyRestController extends RestrictedBaseController { response.setContentType("application / json"); request.setCharacterEncoding(UTF_8); - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{result: " + resultList + "}"); - out.write(j.toString()); + response.getWriter().write(new JSONObject("{result: " + resultList + "}").toString()); return null; } public void deleteElasticData(String fileName) { String uri = "searchPolicy?action=delete&policyName='" + fileName + "'"; - callPAP(null, "POST", uri.trim()); + callPap(null, "POST", uri.trim()); } - public String notifyOtherPAPSToUpdateConfigurations(String mode, String newName, String oldName) { + /** + * notifyOtherPAPSToUpdateConfigurations. + * + * @param mode Mode + * @param newName New Name + * @param oldName Old Name + * @return String + */ + public String notifyOtherPapsToUpdateConfigurations(String mode, String newName, String oldName) { String uri = "onap/notifyOtherPAPs?action=" + mode + "&newPolicyName=" + newName + "&oldPolicyName=" + oldName + ""; - return callPAP(null, "POST", uri.trim()); + return callPap(null, "POST", uri.trim()); } } 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..9cf647954 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,25 +39,26 @@ 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 { private static final Logger LOGGER = FlexLogger.getLogger(PolicyUserInfoController.class); + /** + * getPolicyUserInfo - fills the HTTP response with user information. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + */ @RequestMapping(value = "/get_PolicyUserInfo", method = RequestMethod.GET) public void getPolicyUserInfo(HttpServletRequest request, HttpServletResponse response) { - JsonMessage msg; try { String userId = UserUtils.getUserSession(request).getOrgUserId(); Map<String, Object> model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); model.put("userid", userId); - msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); + response.getWriter().write(new JSONObject(new JsonMessage( + new ObjectMapper().writeValueAsString(model))).toString()); } catch (Exception e) { LOGGER.error("Exception Occurred" + e); } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java index a500c1dbe..d89dd2784 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 @@ -29,6 +29,7 @@ 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; @@ -37,6 +38,7 @@ import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; +import java.net.URLConnection; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.Arrays; @@ -45,10 +47,12 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; + import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.StringUtils; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.XacmlRestProperties; import org.onap.policy.rest.adapter.PolicyRestAdapter; import org.onap.policy.utils.PeCryptoUtils; import org.onap.policy.xacml.api.XACMLErrorConstants; @@ -64,7 +68,7 @@ import org.onap.policy.xacml.std.pap.StdPDPStatus; /** * Implementation of the PAPEngine interface that communicates with a PAP engine in a remote servlet through a RESTful - * interface + * interface. * * */ @@ -72,25 +76,29 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP private static final Logger LOGGER = FlexLogger.getLogger(RESTfulPAPEngine.class); private static final String GROUP_ID = "groupId="; + private static final String UNABLE_MSG = "Unable to PUT policy '"; + private static final String EXCEPTION_MSG = "', e:"; + private static final String ERROR_MSG = "error"; + private static final String PDPID_MSG = "pdpId="; // // URL of the PAP Servlet that this Admin Console talks to // - private String papServletURLString; + private String papServletUrlString; /** - * Set up link with PAP Servlet and get our initial set of Groups + * Set up link with PAP Servlet and get our initial set of Groups. * * @throws PAPException When failing to register with PAP */ - public RESTfulPAPEngine(String myURLString) throws PAPException { + public RESTfulPAPEngine(String myUrlString) throws PAPException { // // Get our URL to the PAP servlet // - this.papServletURLString = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); - if (this.papServletURLString == null || this.papServletURLString.length() == 0) { - String message = - "The property 'POLICYENGINE_ADMIN_ACTIVE' was not set during installation. Admin Console cannot call PAP."; + this.papServletUrlString = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URL); + if (StringUtils.isBlank(this.papServletUrlString)) { + String message = "The property 'POLICYENGINE_ADMIN_ACTIVE' was not set during installation. " + + "Admin Console cannot call PAP."; LOGGER.error(message); throw new PAPException(message); } @@ -98,14 +106,14 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP // // register this Admin Console with the PAP Servlet to get updates // - Object newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString); - if (newURL != null) { + Object newUrl = sendToPap("PUT", null, null, null, "adminConsoleURL=" + myUrlString); + if (newUrl != null) { // assume this was a re-direct and try again - LOGGER.warn("Redirecting to '" + newURL + "'"); - this.papServletURLString = (String) newURL; - newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString); - if (newURL != null) { - LOGGER.error("Failed to redirect to " + this.papServletURLString); + LOGGER.warn("Redirecting to '" + newUrl + "'"); + this.papServletUrlString = (String) newUrl; + newUrl = sendToPap("PUT", null, null, null, "adminConsoleURL=" + myUrlString); + if (newUrl != null) { + LOGGER.error("Failed to redirect to " + this.papServletUrlString); throw new PAPException("Failed to register with PAP"); } } @@ -117,25 +125,25 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP @Override public OnapPDPGroup getDefaultGroup() throws PAPException { - return (OnapPDPGroup) sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID, "default="); + return (OnapPDPGroup) sendToPap("GET", null, null, StdPDPGroup.class, GROUP_ID, "default="); } @Override public void setDefaultGroup(OnapPDPGroup group) throws PAPException { - sendToPAP("POST", null, null, null, GROUP_ID + group.getId(), "default=true"); + sendToPap("POST", null, null, null, GROUP_ID + group.getId(), "default=true"); } @SuppressWarnings("unchecked") @Override public Set<OnapPDPGroup> getOnapPDPGroups() throws PAPException { Set<OnapPDPGroup> newGroupSet; - newGroupSet = (Set<OnapPDPGroup>) this.sendToPAP("GET", null, Set.class, StdPDPGroup.class, GROUP_ID); + newGroupSet = (Set<OnapPDPGroup>) this.sendToPap("GET", null, Set.class, StdPDPGroup.class, GROUP_ID); return Collections.unmodifiableSet(newGroupSet); } @Override public OnapPDPGroup getGroup(String id) throws PAPException { - return (OnapPDPGroup) sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID + id); + return (OnapPDPGroup) sendToPap("GET", null, null, StdPDPGroup.class, GROUP_ID + id); } @Override @@ -149,17 +157,10 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP throw new PAPException("Unable to send name or description to PAP: " + e.getMessage() + e); } - this.sendToPAP("POST", null, null, null, GROUP_ID, "groupName=" + escapedName, + this.sendToPap("POST", null, null, null, GROUP_ID, "groupName=" + escapedName, "groupDescription=" + escapedDescription); } - /** - * Update the configuration on the PAP for a single Group. - * - * @param group - * @return - * @throws PAPException - */ @Override public void updateGroup(OnapPDPGroup group) throws PAPException { try { @@ -175,9 +176,9 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP // However, the policy files are (probably!) not too huge, and this is a good way to ensure that any // corrupted files on the PAP get refreshed. // now update the group object on the PAP - sendToPAP("PUT", group, null, null, GROUP_ID + group.getId()); + sendToPap("PUT", group, null, null, GROUP_ID + group.getId()); } catch (Exception e) { - String message = "Unable to PUT policy '" + group.getId() + "', e:" + e; + String message = UNABLE_MSG + group.getId() + EXCEPTION_MSG + e; LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); throw new PAPException(message); } @@ -192,9 +193,9 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP @Override public void updateGroup(OnapPDPGroup group, String userName) throws PAPException { try { - sendToPAP("PUT", group, null, null, GROUP_ID + group.getId(), "userId=" + userName); + sendToPap("PUT", group, null, null, GROUP_ID + group.getId(), "userId=" + userName); } catch (Exception e) { - String message = "Unable to PUT policy '" + group.getId() + "', e:" + e; + String message = UNABLE_MSG + group.getId() + EXCEPTION_MSG + e; LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); throw new PAPException(message); } @@ -206,7 +207,7 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP if (newGroup != null) { moveToGroupString = "movePDPsToGroupId=" + newGroup.getId(); } - sendToPAP("DELETE", null, null, null, GROUP_ID + group.getId(), moveToGroupString); + sendToPap("DELETE", null, null, null, GROUP_ID + group.getId(), moveToGroupString); } @Override @@ -215,56 +216,61 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP } public OnapPDPGroup getPDPGroup(String pdpId) throws PAPException { - return (OnapPDPGroup) sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID, "pdpId=" + pdpId, + return (OnapPDPGroup) sendToPap("GET", null, null, StdPDPGroup.class, GROUP_ID, PDPID_MSG + pdpId, "getPDPGroup="); } @Override public OnapPDP getPDP(String pdpId) throws PAPException { - return (OnapPDP) sendToPAP("GET", null, null, StdPDP.class, GROUP_ID, "pdpId=" + pdpId); + return (OnapPDP) sendToPap("GET", null, null, StdPDP.class, GROUP_ID, PDPID_MSG + pdpId); } @Override public void newPDP(String id, OnapPDPGroup group, String name, String description, int jmxport) throws PAPException { - StdPDP newPDP = new StdPDP(id, name, description, jmxport); - sendToPAP("PUT", newPDP, null, null, GROUP_ID + group.getId(), "pdpId=" + id); + StdPDP newPdp = new StdPDP(id, name, description, jmxport); + sendToPap("PUT", newPdp, null, null, GROUP_ID + group.getId(), PDPID_MSG + id); } @Override public void movePDP(OnapPDP pdp, OnapPDPGroup newGroup) throws PAPException { - sendToPAP("POST", null, null, null, GROUP_ID + newGroup.getId(), "pdpId=" + pdp.getId()); + sendToPap("POST", null, null, null, GROUP_ID + newGroup.getId(), PDPID_MSG + pdp.getId()); } @Override public void updatePDP(OnapPDP pdp) throws PAPException { OnapPDPGroup group = getPDPGroup(pdp); - sendToPAP("PUT", pdp, null, null, GROUP_ID + group.getId(), "pdpId=" + pdp.getId()); + sendToPap("PUT", pdp, null, null, GROUP_ID + group.getId(), PDPID_MSG + pdp.getId()); } @Override public void removePDP(OnapPDP pdp) throws PAPException { OnapPDPGroup group = getPDPGroup(pdp); - sendToPAP("DELETE", null, null, null, GROUP_ID + group.getId(), "pdpId=" + pdp.getId()); + sendToPap("DELETE", null, null, null, GROUP_ID + group.getId(), PDPID_MSG + pdp.getId()); } - // Validate the Policy Data + /** + * validatePolicyRequest Creates a pap policy and then send to pap. + * + * @param policyAdapter Input Adapter + * @param policyType Type of Policy + * @return true if validated + * @throws PAPException exception if invalid + */ public boolean validatePolicyRequest(PolicyRestAdapter policyAdapter, String policyType) throws PAPException { - StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getConfigBodyData(), + StdPAPPolicy newPapPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getConfigBodyData(), policyAdapter.getConfigType(), "Base"); // send JSON object to PAP - return (Boolean) sendToPAP("PUT", newPAPPolicy, null, null, "operation=validate", "apiflag=admin", + return (Boolean) sendToPap("PUT", newPapPolicy, null, null, "operation=validate", "apiflag=admin", "policyType=" + policyType); } - - @Override public void publishPolicy(String id, String name, boolean isRoot, InputStream policy, OnapPDPGroup group) throws PAPException { // copy the (one) file into the target directory on the PAP servlet - copyFile(id, group, policy); + copyFile(id, group, policy, null); // adjust the local copy of the group to include the new policy PDPPolicy pdpPolicy = new StdPDPPolicy(id, isRoot, name); @@ -278,32 +284,31 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP * Copy a single Policy file from the input stream to the PAP Servlet. Either this works (silently) or it throws an * exception. * - * @param policyId - * @param group - * @param policy - * @return - * @throws PAPException + * @param policyId ID of policy + * @param group PDP Group + * @param policy Input stream of policy + * @throws PAPException exception */ - public void copyFile(String policyId, OnapPDPGroup group, InputStream policy) throws PAPException { + public void copyFile(String policyId, OnapPDPGroup group, InputStream policy, String usrId) throws PAPException { // send the policy file to the PAP Servlet try { - sendToPAP("POST", policy, null, null, GROUP_ID + group.getId(), "policyId=" + policyId); + sendToPap("POST", policy, null, null, GROUP_ID + group.getId(), "policyId=" + policyId, "userId=" + usrId ); } catch (Exception e) { - String message = "Unable to PUT policy '" + policyId + "', e:" + e; + String message = UNABLE_MSG + policyId + EXCEPTION_MSG + e; LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); throw new PAPException(message); } } @Override - public void copyPolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException { + public void copyPolicy(PDPPolicy policy, OnapPDPGroup group, String userId) throws PAPException { if (policy == null || group == null) { throw new PAPException("Null input policy=" + policy + " group=" + group); } try (InputStream is = new FileInputStream(new File(policy.getLocation()))) { - copyFile(policy.getId(), group, is); + copyFile(policy.getId(), group, is, userId); } catch (Exception e) { - String message = "Unable to PUT policy '" + policy.getId() + "', e:" + e; + String message = UNABLE_MSG + policy.getId() + EXCEPTION_MSG + e; LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); throw new PAPException(message); } @@ -318,13 +323,13 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP * Special operation - Similar to the normal PAP operations but this one contacts the PDP directly to get detailed * status info. * - * @param pdp - * @return - * @throws PAPException + * @param pdp PDP to get status + * @return PDPStatus object + * @throws PAPException Exception */ @Override public PDPStatus getStatus(OnapPDP pdp) throws PAPException { - return (StdPDPStatus) sendToPAP("GET", pdp, null, StdPDPStatus.class); + return (StdPDPStatus) sendToPap("GET", pdp, null, StdPDPStatus.class); } // @@ -334,57 +339,56 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP /** * Send a request to the PAP Servlet and get the response. * - * The content is either an InputStream to be copied to the Request OutputStream OR it is an object that is to be + * <p>The content is either an InputStream to be copied to the Request OutputStream OR it is an object that is to be * encoded into JSON and pushed into the Request OutputStream. * - * The Request parameters may be encoded in multiple "name=value" sets, or parameters may be combined by the caller. + * <p>The Request parameters may be encoded in multiple "name=value" sets, or parameters may be + * combined by the caller. * - * @param method + * @param method method * @param content - EITHER an InputStream OR an Object to be encoded in JSON - * @param collectionTypeClass - * @param responseContentClass - * @param parameters - * @return - * @throws PAPException + * @param collectionTypeClass Collection + * @param responseContentClass Response Content + * @param parameters List of parameters + * @return Object + * @throws PAPException exception */ @SuppressWarnings({"rawtypes", "unchecked"}) - private Object sendToPAP(String method, Object content, Class collectionTypeClass, Class responseContentClass, + private Object sendToPap(String method, Object content, Class collectionTypeClass, Class responseContentClass, String... parameters) throws PAPException { HttpURLConnection connection = null; - String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); + String papID = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_USERID); LOGGER.info("User Id is " + papID); - PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY)); + PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XacmlRestProperties.PROP_AES_KEY)); String papPass = PeCryptoUtils - .decrypt(PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS))); + .decrypt(PeCryptoUtils.decrypt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_PASS))); Base64.Encoder encoder = Base64.getEncoder(); String encoding = encoder.encodeToString((papID + ":" + papPass).getBytes(StandardCharsets.UTF_8)); Object contentObj = content; LOGGER.info("Encoding for the PAP is: " + encoding); try { - String fullURL = papServletURLString; + String fullUrl = papServletUrlString; if (parameters != null && parameters.length > 0) { StringBuilder queryString = new StringBuilder(); Arrays.stream(parameters).map(p -> "&" + p).forEach(queryString::append); - fullURL += "?" + queryString.substring(1); + fullUrl += "?" + queryString.substring(1); } // special case - Status (actually the detailed status) comes from the PDP directly, not the PAP if ("GET".equals(method) && (contentObj instanceof OnapPDP) && responseContentClass == StdPDPStatus.class) { // Adjust the url and properties appropriately String pdpID = ((OnapPDP) contentObj).getId(); - fullURL = pdpID + "?type=Status"; + fullUrl = pdpID + "?type=Status"; contentObj = null; - if (CheckPDP.validateID(pdpID)) { - encoding = CheckPDP.getEncoding(pdpID); + if (CheckPdpProperties.validateId(pdpID)) { + encoding = CheckPdpProperties.getEncoding(pdpID); } } - URL url = new URL(fullURL); - // // Open up the connection // - connection = (HttpURLConnection) url.openConnection(); + connection = (HttpURLConnection) makeConnection(fullUrl); // // Setup our method and headers // @@ -434,9 +438,9 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP String finalPolicyPath = connection.getHeaderField("finalPolicyPath"); successMap.put("success", finalPolicyPath); return successMap; - } else if ("error".equalsIgnoreCase(isSuccess)) { + } else if (ERROR_MSG.equalsIgnoreCase(isSuccess)) { LOGGER.info("There was an error while creating the policy!"); - successMap.put("error", "error"); + successMap.put(ERROR_MSG, ERROR_MSG); return successMap; } else { // get the response content into a String @@ -457,19 +461,19 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP } } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) { // redirection - String newURL = connection.getHeaderField("Location"); - if (newURL == null) { + String newUrl = connection.getHeaderField("Location"); + if (newUrl == null) { LOGGER.error( "No Location header to redirect to when response code=" + connection.getResponseCode()); throw new IOException( "No redirect Location header when response code=" + connection.getResponseCode()); } - int qIndex = newURL.indexOf('?'); - if (qIndex > 0) { - newURL = newURL.substring(0, qIndex); + int qindex = newUrl.indexOf('?'); + if (qindex > 0) { + newUrl = newUrl.substring(0, qindex); } - LOGGER.info("Redirect seen. Redirecting " + fullURL + " to " + newURL); - return newURL; + LOGGER.info("Redirect seen. Redirecting " + fullUrl + " to " + newUrl); + return newUrl; } else { LOGGER.warn("Unexpected response code: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); @@ -527,4 +531,10 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP LOGGER.info("JSON response from PAP: " + json); return json; } + + // these may be overridden by junit tests + + protected URLConnection makeConnection(String fullUrl) throws IOException { + return new URL(fullUrl).openConnection(); + } } 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..f2c3a5d7a 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,15 +2,15 @@ * ============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"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -39,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; @@ -104,9 +106,16 @@ public class HumanPolicyComponent { // Default Constructor } + /** + * DescribePolicy. + * + * @param policyFile File + * @return JSONObject + */ public static JSONObject DescribePolicy(final File policyFile) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace(ENTER); + } HumanPolicyComponent.policyFile = policyFile; return humanPolicyLayout(); @@ -114,8 +123,9 @@ public class HumanPolicyComponent { } private static JSONObject humanPolicyLayout() { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace(ENTER); + } try { String html = processPolicy(); @@ -135,8 +145,9 @@ public class HumanPolicyComponent { } try (FileInputStream pIS = new FileInputStream(policyFile)) { Object policy = XACMLPolicyScanner.readPolicy(pIS); - if (policy == null) + if (policy == null) { throw new IllegalArgumentException("Policy File " + policyFile.getName() + " cannot be unmarshalled"); + } HumanPolicyComponent.htmlProcessor = new HtmlProcessor(HumanPolicyComponent.policyFile, policy); @@ -144,8 +155,9 @@ public class HumanPolicyComponent { XACMLPolicyScanner xacmlScanner = new XACMLPolicyScanner(policyPath, htmlProcessor); xacmlScanner.scan(); String html = htmlProcessor.html(); - if (LOGGER.isDebugEnabled()) + if (LOGGER.isDebugEnabled()) { LOGGER.debug(policyPath + System.lineSeparator() + html); + } return html; @@ -165,6 +177,7 @@ class HtmlProcessor extends SimpleCallback { private static final String ENTER = "ENTER"; private static Map<String, String> function2human; + static { function2human = new HashMap<>(); function2human.put(HumanPolicyComponent.FUNCTION_STRING_EQUAL, "equal"); @@ -175,6 +188,7 @@ class HtmlProcessor extends SimpleCallback { } private static Map<String, String> combiningAlgo2human; + static { combiningAlgo2human = new HashMap<>(); combiningAlgo2human.put("deny-overrides", "to deny if any $placeholder$ below evaluates to <i>deny</i>"); @@ -203,8 +217,9 @@ class HtmlProcessor extends SimpleCallback { private final Object rootPolicyObject; public HtmlProcessor(File policyFile, Object policyObject) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace(ENTER); + } if (policyFile == null) { LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Null Policy File"); @@ -259,6 +274,8 @@ class HtmlProcessor extends SimpleCallback { } /** + * getAttributeIdentifiersMap. + * * @return the attributeIdentifiersMap */ public Map<String, AttributeIdentifiers> getAttributeIdentifiersMap() { @@ -267,8 +284,9 @@ class HtmlProcessor extends SimpleCallback { @Override public void onFinishScan(Object root) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace(ENTER); + } if (rootPolicyObject instanceof PolicySetType) { htmlOut.println("</dl>"); @@ -306,43 +324,52 @@ class HtmlProcessor extends SimpleCallback { @Override public CallbackResult onPreVisitPolicySet(PolicySetType parent, PolicySetType policySet) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Version: " + policySet.getVersion()); + } - if (parent != null && LOGGER.isTraceEnabled()) + if (parent != null && LOGGER.isTraceEnabled()) { LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); + } String description = policySet.getDescription(); - if (description != null && LOGGER.isTraceEnabled()) + if (description != null && LOGGER.isTraceEnabled()) { LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Description: " + policySet.getDescription()); + } - if (parent == null) // root + if (parent == null) { // root policySet(policySet, "dl"); - else + } else { policySet(policySet, "li"); + } - if (!policySet.getPolicySetOrPolicyOrPolicySetIdReference().isEmpty()) + if (!policySet.getPolicySetOrPolicyOrPolicySetIdReference().isEmpty()) { htmlOut.println("<ol>"); + } return super.onPreVisitPolicySet(parent, policySet); } @Override public CallbackResult onPostVisitPolicySet(PolicySetType parent, PolicySetType policySet) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Version: " + policySet.getVersion()); + } - if (parent != null && LOGGER.isTraceEnabled()) + if (parent != null && LOGGER.isTraceEnabled()) { LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); + } String description = policySet.getDescription(); - if (description != null && LOGGER.isTraceEnabled()) + if (description != null && LOGGER.isTraceEnabled()) { LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Description: " + policySet.getDescription()); + } - if (!policySet.getPolicySetOrPolicyOrPolicySetIdReference().isEmpty()) + if (!policySet.getPolicySetOrPolicyOrPolicySetIdReference().isEmpty()) { htmlOut.println("</ol>"); + } htmlOut.println("<p></p>"); @@ -350,23 +377,25 @@ class HtmlProcessor extends SimpleCallback { } public void policySet(PolicySetType policySet, String htmlListElement) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace("PolicySet: " + policySet.getPolicySetId()); + } String combiningAlgorithm = "-"; String id = "-"; String version = "-"; - - if (policySet.getPolicyCombiningAlgId() != null) + if (policySet.getPolicyCombiningAlgId() != null) { combiningAlgorithm = extractLastIdentifier(policySet.getPolicyCombiningAlgId(), ":"); + } - if (policySet.getPolicySetId() != null) + if (policySet.getPolicySetId() != null) { id = extractLastIdentifier(policySet.getPolicySetId(), ":"); + } - if (policySet.getVersion() != null) + if (policySet.getVersion() != null) { version = policySet.getVersion(); - + } htmlOut.println("<" + htmlListElement + "><b>Policy Set ID</b>: <i>" + id + "</i> (v" + version + ") " + "</" + htmlListElement + ">"); @@ -378,8 +407,7 @@ class HtmlProcessor extends SimpleCallback { htmlOut.print("<p>"); htmlOut.print("This policy set applies to requests with attributes "); - List<AnyOfType> anyOf_s = policySet.getTarget().getAnyOf(); - target(anyOf_s); + target(policySet.getTarget().getAnyOf()); htmlOut.println(".</p>"); } @@ -398,58 +426,68 @@ class HtmlProcessor extends SimpleCallback { @Override public CallbackResult onPreVisitPolicy(PolicySetType parent, PolicyType policy) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace("PolicySet: " + policy.getPolicyId() + " Version: " + policy.getVersion()); + } - if (parent != null && LOGGER.isTraceEnabled()) + if (parent != null && LOGGER.isTraceEnabled()) { LOGGER.trace("PolicySet: " + policy.getPolicyId() + "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); + } String description = policy.getDescription(); - if (description != null && LOGGER.isTraceEnabled()) + if (description != null && LOGGER.isTraceEnabled()) { LOGGER.trace("PolicySet: " + policy.getPolicyId() + " Description: " + policy.getDescription()); + } policy(policy); - if (!policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().isEmpty()) + if (!policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().isEmpty()) { htmlOut.println("<ol type=\"i\">"); + } return super.onPreVisitPolicy(parent, policy); } @Override public CallbackResult onPostVisitPolicy(PolicySetType parent, PolicyType policy) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace("PolicySet: " + policy.getPolicyId() + " Version: " + policy.getVersion()); + } - if (parent != null && LOGGER.isTraceEnabled()) + if (parent != null && LOGGER.isTraceEnabled()) { LOGGER.trace("PolicySet: " + policy.getPolicyId() + "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); + } - if (!policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().isEmpty()) + if (!policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().isEmpty()) { htmlOut.println("</ol>"); + } htmlOut.println("<p></p>"); return super.onPostVisitPolicy(parent, policy); } public void policy(PolicyType policy) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Policy: " + policy.getPolicyId()); + } String combiningAlgorithm = "-"; String id = "-"; String version = "-"; - - if (policy.getRuleCombiningAlgId() != null) + if (policy.getRuleCombiningAlgId() != null) { combiningAlgorithm = extractLastIdentifier(policy.getRuleCombiningAlgId(), ":"); + } - if (policy.getPolicyId() != null) + if (policy.getPolicyId() != null) { id = extractLastIdentifier(policy.getPolicyId(), ":"); + } - if (policy.getVersion() != null) + if (policy.getVersion() != null) { version = policy.getVersion(); + } htmlOut.println("<li><b>Policy ID</b>: <i>" + id + "</i> (v" + version + ") " + "</li>"); @@ -460,8 +498,7 @@ class HtmlProcessor extends SimpleCallback { htmlOut.print("<p>"); htmlOut.print("This policy applies to requests with attributes "); - List<AnyOfType> anyOf_s = policy.getTarget().getAnyOf(); - target(anyOf_s); + target(policy.getTarget().getAnyOf()); htmlOut.println(".</p>"); } @@ -477,14 +514,15 @@ class HtmlProcessor extends SimpleCallback { } } - @Override public CallbackResult onPreVisitRule(PolicyType parent, RuleType rule) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace("Rule: " + rule.getRuleId()); + } - if (parent != null && LOGGER.isTraceEnabled()) + if (parent != null && LOGGER.isTraceEnabled()) { LOGGER.trace("Parent Policy: " + parent.getPolicyId() + " Version: " + parent.getVersion()); + } String description = rule.getDescription(); if (description != null && LOGGER.isTraceEnabled()) { @@ -498,23 +536,21 @@ class HtmlProcessor extends SimpleCallback { @Override public CallbackResult onPostVisitRule(PolicyType parent, RuleType rule) { - if (LOGGER.isTraceEnabled()) - LOGGER.trace("Rule: " + rule.getRuleId()); - if (parent != null && LOGGER.isTraceEnabled()) + if (parent != null && LOGGER.isTraceEnabled()) { LOGGER.trace("Parent Policy: " + parent.getPolicyId() + " Version: " + parent.getVersion()); + } return super.onPostVisitRule(parent, rule); } public void rule(RuleType rule) { - if (LOGGER.isTraceEnabled()) - LOGGER.trace("Rule: " + rule.getRuleId()); String id = "-"; - if (rule.getRuleId() != null) + if (rule.getRuleId() != null) { id = extractLastIdentifier(rule.getRuleId(), ":"); + } htmlOut.println("<li><b>Rule ID</b>: <i>" + id + "</i></li>"); @@ -526,9 +562,8 @@ class HtmlProcessor extends SimpleCallback { if (rule.getTarget() == null || rule.getTarget().getAnyOf() == null || rule.getTarget().getAnyOf().isEmpty()) { htmlOut.print(" for all requests"); } else { - List<AnyOfType> anyOf_s = rule.getTarget().getAnyOf(); htmlOut.print(" for requests with attributes "); - target(anyOf_s); + target(rule.getTarget().getAnyOf()); } if (rule.getCondition() != null) { @@ -540,8 +575,9 @@ class HtmlProcessor extends SimpleCallback { if (rule.getAdviceExpressions() != null) { advice(rule.getAdviceExpressions()); - if (rule.getObligationExpressions() != null) + if (rule.getObligationExpressions() != null) { htmlOut.println(" and "); + } } if (rule.getObligationExpressions() != null) { @@ -552,8 +588,9 @@ class HtmlProcessor extends SimpleCallback { } private void advice(AdviceExpressionsType adviceExpressions) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace(ENTER); + } List<AdviceExpressionType> ae = adviceExpressions.getAdviceExpression(); for (AdviceExpressionType expression : ae) { @@ -569,8 +606,9 @@ class HtmlProcessor extends SimpleCallback { } private void obligation(ObligationExpressionsType obligationExpressions) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace(ENTER); + } List<ObligationExpressionType> oe = obligationExpressions.getObligationExpression(); for (ObligationExpressionType expression : oe) { @@ -586,11 +624,14 @@ class HtmlProcessor extends SimpleCallback { } /** - * @param assignments + * processAttributeAssignments. + * + * @param assignments List of AttributeAssignmentExpressionType */ private void processAttributeAssignments(List<AttributeAssignmentExpressionType> assignments) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace(ENTER); + } for (AttributeAssignmentExpressionType assignment : assignments) { String succintIdentifier = extractLastIdentifier(assignment.getCategory(), ":") + ":" @@ -620,8 +661,9 @@ class HtmlProcessor extends SimpleCallback { for (Object c : avt.getContent()) { countContent++; htmlOut.print("<i>" + c + "</i>"); - if (countContent < numContent) + if (countContent < numContent) { htmlOut.print(" or "); + } } htmlOut.println("</li>"); } else if (assignmentObject instanceof AttributeDesignatorType @@ -634,118 +676,118 @@ class HtmlProcessor extends SimpleCallback { } /** - * - * @param anyOfList + * target. + * + * @param anyOfList List of AnyOfType's */ public void target(List<AnyOfType> anyOfList) { - if (LOGGER.isTraceEnabled()) + if (LOGGER.isTraceEnabled()) { LOGGER.trace(ENTER); + } - if (anyOfList != null) { - Iterator<AnyOfType> iterAnyOf = anyOfList.iterator(); - StringBuilder targetInHuman = new StringBuilder(); - while (iterAnyOf.hasNext()) { - AnyOfType anyOf = iterAnyOf.next(); - List<AllOfType> allOfList = anyOf.getAllOf(); - if (allOfList != null) { - Iterator<AllOfType> iterAllOf = allOfList.iterator(); - while (iterAllOf.hasNext()) { - AllOfType allOf = iterAllOf.next(); - List<MatchType> matchList = allOf.getMatch(); - if (matchList != null) { - Iterator<MatchType> iterMatch = matchList.iterator(); - if (matchList.size() > 1) - targetInHuman.append("("); - while (iterMatch.hasNext()) { - MatchType match = iterMatch.next(); - // - // Finally down to the actual attribute - // - StdAttribute attribute = null; - AttributeValueType value = match.getAttributeValue(); - String attributeDataType; - if (match.getAttributeDesignator() != null && value != null) { - AttributeDesignatorType designator = match.getAttributeDesignator(); - attribute = new StdAttribute(new IdentifierImpl(designator.getCategory()), - new IdentifierImpl(designator.getAttributeId()), - new StdAttributeValue<List<?>>(new IdentifierImpl(value.getDataType()), - value.getContent()), - designator.getIssuer(), false); - attributeDataType = designator.getDataType(); - } else if (match.getAttributeSelector() != null && value != null) { - AttributeSelectorType selector = match.getAttributeSelector(); - attribute = new StdAttribute(new IdentifierImpl(selector.getCategory()), - new IdentifierImpl(selector.getContextSelectorId()), - new StdAttributeValue<List<?>>(new IdentifierImpl(value.getDataType()), - value.getContent()), - null, false); - attributeDataType = selector.getDataType(); - } else { - LOGGER.warn("NULL designator/selector or value for match."); - attributeDataType = "NA"; - } + if (anyOfList == null) { + return; + } + Iterator<AnyOfType> iterAnyOf = anyOfList.iterator(); + StringBuilder targetInHuman = new StringBuilder(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + List<AllOfType> allOfList = anyOf.getAllOf(); + Iterator<AllOfType> iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + List<MatchType> matchList = allOf.getMatch(); + Iterator<MatchType> iterMatch = matchList.iterator(); + if (matchList.size() > 1) { + targetInHuman.append("("); + } + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Finally down to the actual attribute + // + StdAttribute attribute = null; + AttributeValueType value = match.getAttributeValue(); + String attributeDataType; + if (match.getAttributeDesignator() != null && value != null) { + AttributeDesignatorType designator = match.getAttributeDesignator(); + attribute = new StdAttribute(new IdentifierImpl(designator.getCategory()), + new IdentifierImpl(designator.getAttributeId()), + new StdAttributeValue<List<?>>(new IdentifierImpl(value.getDataType()), + value.getContent()), + designator.getIssuer(), false); + attributeDataType = designator.getDataType(); + } else if (match.getAttributeSelector() != null && value != null) { + AttributeSelectorType selector = match.getAttributeSelector(); + attribute = new StdAttribute(new IdentifierImpl(selector.getCategory()), + new IdentifierImpl(selector.getContextSelectorId()), + new StdAttributeValue<List<?>>(new IdentifierImpl(value.getDataType()), + value.getContent()), + null, false); + attributeDataType = selector.getDataType(); + } else { + LOGGER.warn("NULL designator/selector or value for match."); + attributeDataType = "NA"; + } - String functionName = getHumanFunction(match.getMatchId()); - if (attribute != null) { - String succintIdentifier = extractLastIdentifier( - attribute.getCategory().stringValue(), ":") + ":" - + extractLastIdentifier(attribute.getAttributeId().stringValue(), ":"); - AttributeIdentifiers ai = - new AttributeIdentifiers(attribute.getCategory().stringValue(), - attributeDataType, attribute.getAttributeId().stringValue()); - this.attributeIdentifiersMap.put(succintIdentifier, ai); - - targetInHuman.append("<i><a href=\"#" + succintIdentifier + "\">" - + succintIdentifier + "</a></i> " + functionName + " "); - - int numAttributes = attribute.getValues().size(); - int count = 0; - for (AttributeValue<?> v : attribute.getValues()) { - count++; - if (v.getValue() instanceof Collection<?>) { - Collection<?> value_s = (Collection<?>) v.getValue(); - int numValues = value_s.size(); - int countValues = 0; - for (Object o : value_s) { - countValues++; - targetInHuman.append(" <I>" + o + "</I>"); - if (countValues < numValues) { - targetInHuman.append(", or"); - } - } - } else { - targetInHuman.append(" <I>" + v.getValue() + "</I>"); - if (count < numAttributes) { - targetInHuman.append(", or "); - } - } + String functionName = getHumanFunction(match.getMatchId()); + if (attribute != null) { + String succintIdentifier = extractLastIdentifier( + attribute.getCategory().stringValue(), ":") + ":" + + extractLastIdentifier(attribute.getAttributeId().stringValue(), ":"); + AttributeIdentifiers ai = + new AttributeIdentifiers(attribute.getCategory().stringValue(), + attributeDataType, attribute.getAttributeId().stringValue()); + this.attributeIdentifiersMap.put(succintIdentifier, ai); + + targetInHuman.append("<i><a href=\"#" + succintIdentifier + "\">" + + succintIdentifier + "</a></i> " + functionName + " "); + + int numAttributes = attribute.getValues().size(); + int count = 0; + for (AttributeValue<?> v : attribute.getValues()) { + count++; + if (v.getValue() instanceof Collection<?>) { + Collection<?> collectionValues = (Collection<?>) v.getValue(); + int numValues = collectionValues.size(); + int countValues = 0; + for (Object o : collectionValues) { + countValues++; + targetInHuman.append(" <I>" + o + "</I>"); + if (countValues < numValues) { + targetInHuman.append(", or"); } } - - if (iterMatch.hasNext()) { - targetInHuman.append(" and "); + } else { + targetInHuman.append(" <I>" + v.getValue() + "</I>"); + if (count < numAttributes) { + targetInHuman.append(", or "); } - } // end iterMatch - if (matchList.size() > 1) { - targetInHuman.append(")"); } } - if (iterAllOf.hasNext()) { - targetInHuman.append(" or "); - } - } // end iterAllOf - } - if (iterAnyOf.hasNext()) { - targetInHuman = new StringBuilder(); - targetInHuman.append("(" + targetInHuman + ")" + " or "); - } else { - if (anyOfList.size() > 1) { - targetInHuman.append(")"); } + + if (iterMatch.hasNext()) { + targetInHuman.append(" and "); + } + } // end iterMatch + if (matchList.size() > 1) { + targetInHuman.append(")"); } - } // end iterAnyOf - htmlOut.println(targetInHuman); + } + if (iterAllOf.hasNext()) { + targetInHuman.append(" or "); + } + } // end iterAllOf + if (iterAnyOf.hasNext()) { + targetInHuman = new StringBuilder(); + targetInHuman.append("(" + targetInHuman + ")" + " or "); + } else { + if (anyOfList.size() > 1) { + targetInHuman.append(")"); + } } + htmlOut.println(targetInHuman); } private String getHumanFunction(String matchId) { @@ -815,12 +857,12 @@ class HtmlProcessor extends SimpleCallback { } else { StringBuilder forResult = new StringBuilder(); for (JAXBElement<?> e : exps) { - Object v = e.getValue(); + Object theValue = e.getValue(); if (LOGGER.isDebugEnabled()) { - LOGGER.debug("one-and-only children: " + v); + LOGGER.debug("one-and-only children: " + theValue); } - if (v != null) { - forResult.append(stringifyExpression(v)); + if (theValue != null) { + forResult.append(stringifyExpression(theValue)); } } return forResult.toString(); @@ -840,8 +882,8 @@ class HtmlProcessor extends SimpleCallback { } StringBuilder applySubresult = new StringBuilder(); for (JAXBElement<?> e : apply.getExpression()) { - Object v = e.getValue(); - if (v != null) { + Object theValue = e.getValue(); + if (theValue != null) { applySubresult.append(this.stringifyExpression(e.getValue())); } } @@ -906,11 +948,12 @@ class HtmlProcessor extends SimpleCallback { if (expression instanceof AttributeValueType) { AttributeValueType avt = (AttributeValueType) expression; List<Object> content = avt.getContent(); - StringBuilder value_s = new StringBuilder(); + StringBuilder stringValue = new StringBuilder(" "); for (Object o : content) { - value_s.append(" " + o.toString()); + stringValue.append(" "); + stringValue.append(o.toString()); } - return " " + value_s.toString(); + return stringValue.toString(); } if (expression instanceof VariableReferenceType) { // 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..ef6b98803 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. @@ -32,44 +32,43 @@ import org.hibernate.cfg.Configuration; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.controller.PolicyController; -import org.onap.policy.rest.jpa.SystemLogDB; +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..666923b43 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,15 +2,15 @@ * ============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"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,32 +27,28 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; 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; 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.ConditionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType; 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"; @@ -66,41 +62,47 @@ public class ActionPolicyController extends RestrictedBaseController { // Default Constructor } + /** + * prePopulateActionPolicyData. + * + * @param policyAdapter PolicyRestAdapter + */ public void prePopulateActionPolicyData(PolicyRestAdapter policyAdapter) { ruleAlgorithmList = new ArrayList<>(); performer.put("PDP", "PDPAction"); performer.put("PEP", "PEPAction"); - if (policyAdapter.getPolicyData() instanceof PolicyType) { - PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); + if (! (policyAdapter.getPolicyData() instanceof PolicyType)) { + return; + } + PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); - // 1. Set policy-name, policy-filename and description to Policy Adapter - setPolicyAdapterPolicyNameAndDesc(policyAdapter, policy); + // 1. Set policy-name, policy-filename and description to Policy Adapter + setPolicyAdapterPolicyNameAndDesc(policyAdapter, policy); - // 2a. Get the target data under policy for Action. - TargetType target = policy.getTarget(); - if (target == null) { - return; - } + // 2a. Get the target data under policy for Action. + TargetType target = policy.getTarget(); + if (target == null) { + return; + } - // 2b. Set attributes to Policy Adapter - setPolicyAdapterAttributes(policyAdapter, target.getAnyOf()); + // 2b. Set attributes to Policy Adapter + setPolicyAdapterAttributes(policyAdapter, target.getAnyOf()); - List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); - // Under rule we have Condition and obligation. - for (Object o : ruleList) { - if (!(o instanceof RuleType)) { - continue; - } - // 3. Set rule-algorithm choices to Policy Adapter - setPolicyAdapterRuleAlgorithmschoices(policyAdapter, (RuleType) o); + List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); + // Under rule we have Condition and obligation. + for (Object o : ruleList) { + if (!(o instanceof RuleType)) { + continue; + } + // 3. Set rule-algorithm choices to Policy Adapter + setPolicyAdapterRuleAlgorithmschoices(policyAdapter, (RuleType) o); - // 4a. Get the Obligation data under the rule for Form elements. - ObligationExpressionsType obligations = ((RuleType) o).getObligationExpressions(); + // 4a. Get the Obligation data under the rule for Form elements. + ObligationExpressionsType obligations = ((RuleType) o).getObligationExpressions(); - // 4b. Set action attribute-value and action-performer to Policy Adapter - setPolicyAdapterActionData(policyAdapter, obligations); - } + // 4b. Set action attribute-value and action-performer to Policy Adapter + setPolicyAdapterActionData(policyAdapter, obligations); } } @@ -109,22 +111,23 @@ public class ActionPolicyController extends RestrictedBaseController { return; } // Under the obligationExpressions we have obligationExpression. - List<ObligationExpressionType> obligationList = obligations.getObligationExpression(); - if (obligationList == null) { - return; - } - for (ObligationExpressionType obligation : obligationList) { + // NOTE: getObligationExpression() will never return NULL. + // + for (ObligationExpressionType obligation : obligations.getObligationExpression()) { policyAdapter.setActionAttributeValue(obligation.getObligationId()); // Under the obligationExpression we have attributeAssignmentExpression. - List<AttributeAssignmentExpressionType> attributeAssignmentExpressionList = obligation - .getAttributeAssignmentExpression(); - if (attributeAssignmentExpressionList == null) { - continue; - } - for (AttributeAssignmentExpressionType attributeAssignmentExpression : attributeAssignmentExpressionList) { + // + // NOTE: obligation.getAttributeAssignmentExpression() will NEVER be null + // It will always return a list. + // + for (AttributeAssignmentExpressionType attributeAssignmentExpression : + obligation.getAttributeAssignmentExpression()) { + // + // + // 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 +142,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 { @@ -152,11 +155,10 @@ public class ActionPolicyController extends RestrictedBaseController { policyAdapter.setPolicyDescription(description); } - private void setPolicyAdapterRuleAlgorithmschoices(PolicyRestAdapter policyAdapter, RuleType o) { - ConditionType condition = o.getCondition(); - if (condition != null) { + private void setPolicyAdapterRuleAlgorithmschoices(PolicyRestAdapter policyAdapter, RuleType ruleType) { + if (ruleType.getCondition() != null) { int index = 0; - ApplyType actionApply = (ApplyType) condition.getExpression().getValue(); + ApplyType actionApply = (ApplyType) ruleType.getCondition().getExpression().getValue(); ruleAlgorithmTracker = new LinkedList<>(); // Populating Rule Algorithms starting from compound. prePopulateCompoundRuleAlgorithm(index, actionApply); @@ -166,36 +168,43 @@ public class ActionPolicyController extends RestrictedBaseController { private void setPolicyAdapterAttributes(PolicyRestAdapter policyAdapter, List<AnyOfType> anyOfList) { List<Object> attributeList = new ArrayList<>(); - if (anyOfList == null) { - return; - } + // + // NOTE: If using xacml3 code and doing a getAnyOf(), the anyOfList will + // NEVER be null as that code will create it if it is null. + // + // Remove the null check as its impossible to cover it. + // // under target we have AnyOFType for (AnyOfType anyOf : anyOfList) { // Under AntOfType we have AllOfType + // + // NOTE: This will NEVER be null as the method call in the + // previous line getAllOf() will never return a null. It + // always creates it if its empty. + // List<AllOfType> allOfList = anyOf.getAllOf(); - if (allOfList == null) { - continue; - } // Under AllOfType we have Match. for (AllOfType allOfType : allOfList) { - List<MatchType> matchList = allOfType.getMatch(); - if (matchList != null) { - // - // Under the match we have attributeValue and - // attributeDesignator. So,finally down to the actual attribute. - // - // Component attributes are saved under Target here we are fetching them back. - // One row is default so we are not adding dynamic component at index 0. - matchList.forEach(match -> { - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - Map<String, String> attribute = new HashMap<>(); - attribute.put("key", attributeId); - attribute.put("value", value); - attributeList.add(attribute); - }); + // + // NOTE: allOfType.getMatch() will NEVER be null as the method + // call getMatch will always return something. If its + // not there it will create it. + // + // + // Under the match we have attributeValue and + // attributeDesignator. So,finally down to the actual attribute. + // + // Component attributes are saved under Target here we are fetching them back. + // One row is default so we are not adding dynamic component at index 0. + for (MatchType match : allOfType.getMatch()) { + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + Map<String, String> attribute = new HashMap<>(); + attribute.put("key", attributeId); + attribute.put("value", value); + attributeList.add(attribute); } policyAdapter.setAttributes(attributeList); } @@ -211,41 +220,41 @@ public class ActionPolicyController extends RestrictedBaseController { LOGGER.debug("Prepopulating rule algoirthm: " + index); } // Check to see if Attribute Value exists, if yes then it is not a compound rule - if (jaxbElement.getValue() instanceof AttributeValueType) { + if (jaxbElement.getValue() instanceof AttributeValueType + || jaxbElement.getValue() instanceof AttributeDesignatorType) { prePopulateRuleAlgorithms(index, actionApply, jaxbActionTypes); ruleAlgorithmTracker.addLast(index); isCompoundRule = false; index++; } } - if (isCompoundRule) { - // As it's compound rule, Get the Apply types - for (JAXBElement<?> jaxbElement : jaxbActionTypes) { - ApplyType innerActionApply = (ApplyType) jaxbElement.getValue(); - index = prePopulateCompoundRuleAlgorithm(index, innerActionApply); - } - // Populate combo box - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Prepopulating Compound rule algorithm: " + index); - } - Map<String, String> rule = new HashMap<>(); - for (String key : PolicyController.getDropDownMap().keySet()) { - String keyValue = PolicyController.getDropDownMap().get(key); - if (keyValue.equals(actionApply.getFunctionId())) { - rule.put("dynamicRuleAlgorithmCombo", key); - } + if (!isCompoundRule) { + return index; + } + // As it's compound rule, Get the Apply types + for (JAXBElement<?> jaxbElement : jaxbActionTypes) { + ApplyType innerActionApply = (ApplyType) jaxbElement.getValue(); + index = prePopulateCompoundRuleAlgorithm(index, innerActionApply); + } + // Populate combo box + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Prepopulating Compound rule algorithm: " + index); + } + Map<String, String> rule = new HashMap<>(); + for ( Entry<String, String> entrySet : PolicyController.getDropDownMap().entrySet()) { + if (entrySet.getValue().equals(actionApply.getFunctionId())) { + rule.put("dynamicRuleAlgorithmCombo", entrySet.getKey()); } - rule.put("id", "A" + (index + 1)); - // Populate Key and values for Compound Rule - rule.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, "A" + (ruleAlgorithmTracker.getLast() + 1)); - ruleAlgorithmTracker.removeLast(); - rule.put(DYNAMIC_RULE_ALGORITHM_FIELD_2, "A" + (ruleAlgorithmTracker.getLast() + 1)); - ruleAlgorithmTracker.removeLast(); - ruleAlgorithmTracker.addLast(index); - ruleAlgorithmList.add(rule); - index++; } - return index; + rule.put("id", "A" + (index + 1)); + // Populate Key and values for Compound Rule + rule.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, "A" + (ruleAlgorithmTracker.getLast() + 1)); + ruleAlgorithmTracker.removeLast(); + rule.put(DYNAMIC_RULE_ALGORITHM_FIELD_2, "A" + (ruleAlgorithmTracker.getLast() + 1)); + ruleAlgorithmTracker.removeLast(); + ruleAlgorithmTracker.addLast(index); + ruleAlgorithmList.add(rule); + return ++index; } private void prePopulateRuleAlgorithms(int index, ApplyType actionApply, List<JAXBElement<?>> jaxbActionTypes) { @@ -253,7 +262,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 +273,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 @@ -279,11 +288,20 @@ public class ActionPolicyController extends RestrictedBaseController { String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_2, attributeValue); - ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(1).getValue(); - List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression(); - AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0) - .getValue(); - ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, attributeDesignator.getAttributeId()); + // + // This is making a BIG assumption here that there exists an innerApply. This IF + // statement was added to support JUnit code coverage. For lack of any example of what + // this policy should actually look like. + // + if (jaxbActionTypes.size() > 1) { + ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(1).getValue(); + List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression(); + if (! jaxbInnerActionTypes.isEmpty()) { + 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..139b2b87f 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,8 +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 java.io.IOException; -import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; @@ -44,21 +47,16 @@ 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 { private static final Logger LOGGER = FlexLogger.getLogger(AdminTabController.class); - private static final String CHARACTER_ENCODING = "UTF-8"; private static CommonClassDao commonClassDao; public AdminTabController() { - //default constructor + // default constructor } @Autowired @@ -74,57 +72,66 @@ 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) + /** + * getAdminTabEntityData. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + */ + @RequestMapping( + value = {"/get_LockDownData"}, + method = {org.springframework.web.bind.annotation.RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) public void getAdminTabEntityData(HttpServletRequest request, HttpServletResponse response) { try { Map<String, Object> model = new HashMap<>(); ObjectMapper mapper = new ObjectMapper(); model.put("lockdowndata", mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); + response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString()); } catch (Exception e) { LOGGER.error("Exception Occured" + e); } } - @RequestMapping(value = {"/adminTabController/save_LockDownValue.htm"}, method = { - org.springframework.web.bind.annotation.RequestMethod.POST}) + /** + * saveAdminTabLockdownValue. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + * @return ModelAndView object + * @throws IOException IOException + */ + @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 { + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); 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); - response.setCharacterEncoding(CHARACTER_ENCODING); - response.setContentType("application / json"); - request.setCharacterEncoding(CHARACTER_ENCODING); + response.setContentType(PolicyUtils.APPLICATION_JSON); - PrintWriter out = response.getWriter(); String responseString = mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class)); - JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}"); - - out.write(j.toString()); - return null; + response.getWriter().write(new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + + "}").toString()); } catch (Exception e) { LOGGER.error("Exception Occured" + e); - response.setCharacterEncoding(CHARACTER_ENCODING); - request.setCharacterEncoding(CHARACTER_ENCODING); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + response.getWriter().write(PolicyUtils.CATCH_EXCEPTION); } return null; } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java index 44a133068..dc342eeed 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,12 +26,11 @@ 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; import java.io.IOException; -import java.io.PrintWriter; -import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -45,9 +44,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; @@ -57,7 +58,7 @@ import org.onap.policy.rest.adapter.AutoPushTabAdapter; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.PolicyEntity; import org.onap.policy.rest.jpa.PolicyVersion; -import org.onap.policy.rest.util.PDPPolicyContainer; +import org.onap.policy.rest.util.PdpPolicyContainer; import org.onap.policy.utils.PolicyUtils; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.onap.policy.xacml.api.pap.OnapPDPGroup; @@ -78,13 +79,12 @@ import org.springframework.web.servlet.ModelAndView; public class AutoPushController extends RestrictedBaseController { private static final Logger logger = FlexLogger.getLogger(AutoPushController.class); - private static final String UTF8 = "UTF-8"; @Autowired CommonClassDao commonClassDao; private PDPGroupContainer container; - private PDPPolicyContainer policyContainer; + private PdpPolicyContainer policyContainer; private PolicyController policyController; protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<>()); @@ -96,6 +96,9 @@ public class AutoPushController extends RestrictedBaseController { this.policyController = policyController; } + /** + * refreshGroups. + */ public synchronized void refreshGroups() { synchronized (this.groups) { this.groups.clear(); @@ -114,7 +117,22 @@ public class AutoPushController extends RestrictedBaseController { return policyController != null ? getPolicyController() : new PolicyController(); } - @RequestMapping(value = {"/get_AutoPushPoliciesContainerData"}, method = {RequestMethod.GET}, + private Set<String> addAllScopes(Roles userRole, Set<String> scopes) { + if (userRole.getScope() != null) { + scopes.addAll(Stream.of(userRole.getScope().split(",")).collect(Collectors.toSet())); + } + return scopes; + } + + /** + * getPolicyGroupContainerData. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + */ + @RequestMapping( + value = {"/get_AutoPushPoliciesContainerData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response) { try { @@ -130,8 +148,9 @@ public class AutoPushController extends RestrictedBaseController { for (Object role : userRoles) { Roles userRole = (Roles) role; roles.add(userRole.getRole()); - scopes.addAll(Stream.of(userRole.getScope().split(",")).collect(Collectors.toSet())); + addAllScopes(userRole, scopes); } + if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) { data = commonClassDao.getData(PolicyVersion.class); } else { @@ -156,18 +175,30 @@ public class AutoPushController extends RestrictedBaseController { ObjectMapper mapper = new ObjectMapper(); model.put("policydatas", mapper.writeValueAsString(data)); JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); + response.getWriter().write(new JSONObject(msg).toString()); } catch (Exception e) { logger.error("Exception Occurred" + e); } } + /** + * pushPolicyToPDPGroup. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + * @return ModelAndView + * @throws IOException IOException + */ @RequestMapping(value = {"/auto_Push/PushPolicyToPDP.htm"}, method = {RequestMethod.POST}) public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException { try { - ArrayList<Object> selectedPDPS = new ArrayList<>(); + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + // + // + // + ArrayList<Object> selectedPdps = new ArrayList<>(); ArrayList<String> selectedPoliciesInUI = new ArrayList<>(); PolicyController controller = getPolicyControllerInstance(); this.groups.addAll(controller.getPapEngine().getOnapPDPGroups()); @@ -178,17 +209,17 @@ public class AutoPushController extends RestrictedBaseController { String userId = UserUtils.getUserSession(request).getOrgUserId(); logger.info( - "****************************************Logging UserID while Pushing Policy to PDP Group*****************************************"); + "**********************Logging UserID while Pushing Policy to PDP Group***********************"); logger.info("UserId: " + userId + "Push Policy Data: " + root.get("pushTabData").toString()); logger.info( - "***********************************************************************************************************************************"); + "**********************************************************************************************"); AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class); for (Object pdpGroupId : adapter.getPdpDatas()) { - LinkedHashMap<?, ?> selectedPDP = (LinkedHashMap<?, ?>) pdpGroupId; + LinkedHashMap<?, ?> selectedPdp = (LinkedHashMap<?, ?>) pdpGroupId; for (OnapPDPGroup pdpGroup : this.groups) { - if (pdpGroup.getId().equals(selectedPDP.get("id"))) { - selectedPDPS.add(pdpGroup); + if (pdpGroup.getId().equals(selectedPdp.get("id"))) { + selectedPdps.add(pdpGroup); } } } @@ -200,7 +231,7 @@ public class AutoPushController extends RestrictedBaseController { selectedPoliciesInUI.add(policyName); } - for (Object pdpDestinationGroupId : selectedPDPS) { + for (Object pdpDestinationGroupId : selectedPdps) { Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>(); Set<PDPPolicy> selectedPolicies = new HashSet<>(); for (String policyId : selectedPoliciesInUI) { @@ -246,10 +277,9 @@ public class AutoPushController extends RestrictedBaseController { BufferedWriter bw = new BufferedWriter(new FileWriter(temp)); bw.write(policyEntity.getPolicyData()); bw.close(); - URI selectedURI = temp.toURI(); try { // Create the policy - selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI); + selectedPolicy = new StdPDPPolicy(name, true, id, temp.toURI()); } catch (IOException e) { logger.error("Unable to create policy '" + name + "': " + e.getMessage(), e); } @@ -263,7 +293,7 @@ public class AutoPushController extends RestrictedBaseController { } // copy policy to PAP try { - controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId); + controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId, userId); } catch (PAPException e) { logger.error("Exception Occured" + e); return null; @@ -307,53 +337,47 @@ public class AutoPushController extends RestrictedBaseController { currentPoliciesInGroup.addAll(selectedPolicies); updatedGroupObject.setPolicies(currentPoliciesInGroup); this.container.updateGroup(updatedGroupObject, userId); - - response.setCharacterEncoding(UTF8); - response.setContentType("application / json"); - request.setCharacterEncoding(UTF8); - - PrintWriter out = response.getWriter(); + response.setContentType(PolicyUtils.APPLICATION_JSON); refreshGroups(); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); - JSONObject j = new JSONObject(msg); - out.write(j.toString()); - // - // Why is this here? This defeats the purpose of the loop?? - // Sonar says to remove it or make it conditional - // - return null; + response.getWriter().write(new JSONObject( + new JsonMessage(mapper.writeValueAsString(groups))).toString()); } } catch (Exception e) { - response.setCharacterEncoding(UTF8); - request.setCharacterEncoding(UTF8); - PrintWriter out = response.getWriter(); logger.error(e); - out.write(PolicyUtils.CATCH_EXCEPTION); + response.getWriter().write(PolicyUtils.CATCH_EXCEPTION); } return null; } + /** + * removePDPGroup. + */ @SuppressWarnings("unchecked") @RequestMapping(value = {"/auto_Push/remove_GroupPolicies.htm"}, method = {RequestMethod.POST}) public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException { try { + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + // + // + // PolicyController controller = getPolicyControllerInstance(); this.container = new PDPGroupContainer(controller.getPapEngine()); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); - StdPDPGroup group = mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class); - JsonNode removePolicyData = root.get("data"); + final StdPDPGroup group = mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class); + final JsonNode removePolicyData = root.get("data"); String userId = UserUtils.getUserSession(request).getOrgUserId(); logger.info( - "****************************************Logging UserID while Removing Policy from PDP Group*****************************************"); + "**********************Logging UserID while Removing Policy from PDP Group*********************"); logger.info("UserId: " + userId + "PDP Group Data: " + root.get("activePdpGroup").toString() + "Remove Policy Data: " + root.get("data")); logger.info( - "***********************************************************************************************************************************"); + "**********************************************************************************************"); - policyContainer = new PDPPolicyContainer(group); + policyContainer = new PdpPolicyContainer(group); if (removePolicyData.size() > 0) { IntStream.range(0, removePolicyData.size()).mapToObj(i -> removePolicyData.get(i).toString()) .forEach(polData -> this.policyContainer.removeItem(polData)); @@ -366,27 +390,16 @@ public class AutoPushController extends RestrictedBaseController { updatedGroupObject.setPipConfigs(group.getPipConfigs()); updatedGroupObject.setStatus(group.getStatus()); updatedGroupObject.setOperation("delete"); - this.container.updateGroup(updatedGroupObject); + this.container.updateGroup(updatedGroupObject, userId); } - response.setCharacterEncoding(UTF8); - response.setContentType("application / json"); - request.setCharacterEncoding(UTF8); + response.setContentType(PolicyUtils.APPLICATION_JSON); - PrintWriter out = response.getWriter(); refreshGroups(); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); - JSONObject j = new JSONObject(msg); - - out.write(j.toString()); - - return null; + response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString()); } catch (Exception e) { - response.setCharacterEncoding(UTF8); - request.setCharacterEncoding(UTF8); - PrintWriter out = response.getWriter(); logger.error(e); - out.write(PolicyUtils.CATCH_EXCEPTION); + response.getWriter().write(PolicyUtils.CATCH_EXCEPTION); } return null; } 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..143d675bf 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,7 +22,10 @@ package org.onap.policy.controller; -import java.io.PrintWriter; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -36,20 +39,32 @@ 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; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.rest.adapter.PolicyRestAdapter; import org.onap.policy.rest.dao.CommonClassDao; -import org.onap.policy.rest.jpa.BRMSParamTemplate; +import org.onap.policy.rest.jpa.BrmsParamTemplate; import org.onap.policy.rest.jpa.PolicyEntity; +import org.onap.policy.utils.PolicyUtils; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.onap.portalsdk.core.controller.RestrictedBaseController; import org.springframework.beans.factory.annotation.Autowired; @@ -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,13 @@ public class CreateBRMSParamController extends RestrictedBaseController { private static String brmsTemplateVlaue = "<$%BRMSParamTemplate="; private static String string = "String"; - - @RequestMapping(value = {"/policyController/getBRMSTemplateData.htm"}, method = { RequestMethod.POST}) + /** + * getBRMSParamPolicyRuleData. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + */ + @RequestMapping(value = {"/policyController/getBRMSTemplateData.htm"}, method = {RequestMethod.POST}) public void getBRMSParamPolicyRuleData(HttpServletRequest request, HttpServletResponse response) { try { dynamicLayoutMap = new HashMap<>(); @@ -118,20 +123,17 @@ public class CreateBRMSParamController extends RestrictedBaseController { response.setContentType(PolicyController.getContenttype()); request.setCharacterEncoding(PolicyController.getCharacterencoding()); - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(dynamicLayoutMap); - JSONObject j = new JSONObject("{policyData: " + responseString + "}"); - out.write(j.toString()); + response.getWriter().write(new JSONObject("{policyData: " + mapper.writeValueAsString(dynamicLayoutMap) + + "}").toString()); } catch (Exception e) { policyLogger.error("Exception Occured while getting BRMS Rule data", e); } } private String findRule(String ruleTemplate) { - List<Object> datas = commonClassDao.getDataById(BRMSParamTemplate.class, "ruleName", ruleTemplate); - if(CollectionUtils.isNotEmpty(datas)){ - BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate) datas.get(0); - return bRMSParamTemplate.getRule(); + List<Object> datas = commonClassDao.getDataById(BrmsParamTemplate.class, "ruleName", ruleTemplate); + if (CollectionUtils.isNotEmpty(datas)) { + return ((BrmsParamTemplate) datas.get(0)).getRule(); } return null; } @@ -151,7 +153,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++) { @@ -243,79 +245,85 @@ public class CreateBRMSParamController extends RestrictedBaseController { dynamicLayoutMap.put(caption, type); } - /* - * 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 + /** + * prePopulateBRMSParamPolicyData. + * 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. + * + * @param policyAdapter PolicyRestAdapter + * @param entity PolicyEntity */ public void prePopulateBRMSParamPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { dynamicLayoutMap = new HashMap<>(); - if (policyAdapter.getPolicyData() instanceof PolicyType) { - PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); - 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); - if (policyLogger.isDebugEnabled()) { - policyLogger + if (! (policyAdapter.getPolicyData() instanceof PolicyType)) { + return; + } + PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); + 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); + if (policyLogger.isDebugEnabled()) { + policyLogger .debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName()); - } - policyAdapter.setPolicyName(policyNameValue); - String description; - try { - description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); - } catch (Exception e) { - policyLogger.info("Error getting description: " + e); - description = policy.getDescription(); - } - policyAdapter.setPolicyDescription(description); - setDataAdapterFromAdviceExpressions(policy, policyAdapter); + } + policyAdapter.setPolicyName(policyNameValue); + String description; + try { + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + } catch (Exception e) { + policyLogger.info("Error getting description: " + e); + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + setDataAdapterFromAdviceExpressions(policy, policyAdapter); - // Generate Param UI - try { - paramUIGenerate(policyAdapter, entity); - } catch (Exception e) { - policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e); - } + // Generate Param UI + try { + paramUiGenerate(policyAdapter, entity); + } catch (Exception e) { + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e); + } - // 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)); - policyAdapter.setRuleData(drlRule); - } - TargetType target = policy.getTarget(); - if (target != null) { - setDataToAdapterFromTarget(target, policyAdapter); - } + // 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)); + policyAdapter.setRuleData(drlRule); + } + TargetType target = policy.getTarget(); + if (target != null) { + setDataToAdapterFromTarget(target, policyAdapter); } } 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:")) { @@ -328,14 +336,11 @@ public class CreateBRMSParamController extends RestrictedBaseController { private void setDataToAdapterFromTarget(TargetType target, PolicyRestAdapter policyAdapter) { // Under target we have AnyOFType - List<AnyOfType> anyOfList = target.getAnyOf(); - if (anyOfList == null) { + if (target.getAnyOf() == null) { return; } - anyOfList.stream().map(AnyOfType::getAllOf) - .filter(Objects::nonNull) - .flatMap(Collection::stream) - .forEach(allOf -> setDataToAdapterFromMatchList(allOf.getMatch(), policyAdapter)); + target.getAnyOf().stream().map(AnyOfType::getAllOf).filter(Objects::nonNull).flatMap(Collection::stream) + .forEach(allOf -> setDataToAdapterFromMatchList(allOf.getMatch(), policyAdapter)); } private void setDataToAdapterFromMatchList(List<MatchType> matchList, PolicyRestAdapter policyAdapter) { @@ -351,25 +356,12 @@ public class CreateBRMSParamController extends RestrictedBaseController { String value = (String) attributeValue.getContent().get(0); AttributeDesignatorType designator = match.getAttributeDesignator(); String attributeId = designator.getAttributeId(); - 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); - } + policyAdapter.setupUsingAttribute(attributeId, value); } } // This method generates the UI from rule configuration - private void paramUIGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + private void paramUiGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) { String data = entity.getConfigurationData().getConfigBody(); if (data == null) { return; @@ -390,8 +382,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 +421,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 +459,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); @@ -482,28 +467,33 @@ public class CreateBRMSParamController extends RestrictedBaseController { return line; } - // set View Rule + /** + * setViewRule. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + */ @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,36 +508,31 @@ 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. - p = Pattern.compile("\\$\\{" + output + "\\}"); - m = p.matcher(body); - //Replacing the value with the inputs provided by the user in the editor. - body = m.replaceAll(copyMap.get(input)); - } - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(body); - JSONObject j = new JSONObject("{policyData: " + responseString + "}"); - out.write(j.toString()); + String output = Character.toLowerCase(input.charAt(0)) + (input.length() > 1 ? input.substring(1) : ""); + // Searching for a pattern in the String using the key. + Pattern pattern = Pattern.compile("\\$\\{" + output + "\\}"); + Matcher matcher = pattern.matcher(body); + // Replacing the value with the inputs provided by the user in the editor. + body = matcher.replaceAll(copyMap.get(input)); + } + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + response.setContentType(PolicyUtils.APPLICATION_JSON); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + + response.getWriter().write(new JSONObject("{policyData: " + mapper.writeValueAsString(body) + + "}").toString()); } catch (Exception e) { policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); } 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..487165b56 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; @@ -36,7 +36,6 @@ 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; 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.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; @@ -53,74 +52,65 @@ public class CreateBRMSRawController { protected PolicyRestAdapter policyAdapter = null; - @SuppressWarnings("unchecked") + /** + * prePopulateBRMSRawPolicyData. + * + * @param policyAdapter PolicyRestAdapter + * @param entity PolicyEntity + */ public void prePopulateBRMSRawPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - if (policyAdapter.getPolicyData() instanceof PolicyType) { - PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - - // Set PolicyAdapter name value - setPolicyAdapterNameValue(policyAdapter); + if (! (policyAdapter.getPolicyData() instanceof PolicyType)) { + return; + } + PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - // Set PolicyAdapter description. - setPolicyAdapterDescription(policyAdapter, policy); + // Set PolicyAdapter name value + setPolicyAdapterNameValue(policyAdapter); - // Set PolicyAdapter attributes. - setPolicyAdapterAttributes(policyAdapter, policy); + // Set PolicyAdapter description. + setPolicyAdapterDescription(policyAdapter, policy); - // Set PolicyAdapter configBodyData - policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody()); + // Set PolicyAdapter attributes. + setPolicyAdapterAttributes(policyAdapter, policy); - // Get the target data under policy. - TargetType target = policy.getTarget(); - if (target == null) { - return; - } - // Under target we have AnyOFType - List<AnyOfType> anyOfList = target.getAnyOf(); - if (anyOfList == null) { - return; - } + // Set PolicyAdapter configBodyData + policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody()); - // Set PolicyAdapter riskType, riskLevel, guard, ttlDate from match attributes - setPolicyAdapterMatchAttributes(policyAdapter, policy.getTarget().getAnyOf()); + // Get the target data under policy. + TargetType target = policy.getTarget(); + if (target == null) { + return; + } + // Under target we have AnyOFType + List<AnyOfType> anyOfList = target.getAnyOf(); + if (anyOfList == null) { + return; } + + // Set PolicyAdapter riskType, riskLevel, guard, ttlDate from match attributes + setPolicyAdapterMatchAttributes(policyAdapter, policy.getTarget().getAnyOf()); } 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. + policyAdapter.setupUsingAttribute(match.getAttributeDesignator().getAttributeId(), + (String) match.getAttributeValue().getContent().get(0)); + })); } 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()); } @@ -138,30 +128,31 @@ public class CreateBRMSRawController { policyAdapter.setPolicyDescription(description); } + @SuppressWarnings("unchecked") 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..58765ded1 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,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.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; @@ -29,9 +33,15 @@ 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 lombok.Getter; +import lombok.Setter; +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.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; @@ -40,26 +50,14 @@ import org.onap.policy.rest.adapter.ClosedLoopFaultTriggerUISignatures; import org.onap.policy.rest.adapter.ClosedLoopSignatures; import org.onap.policy.rest.adapter.PolicyRestAdapter; import org.onap.policy.rest.dao.CommonClassDao; -import org.onap.policy.rest.jpa.OnapName; import org.onap.policy.rest.jpa.PolicyEntity; import org.onap.policy.rest.jpa.VarbindDictionary; +import org.onap.policy.utils.PolicyUtils; import org.onap.portalsdk.core.controller.RestrictedBaseController; 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 { @@ -74,7 +72,6 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { private static final String CONNECT_TRAP_2 = "connectTrap2"; private static final String TRAP_COUNT_2 = "trapCount2"; private static final String TRIGGER_1 = "trigger1"; - private static final String ENC_UTF_8 = "UTF-8"; private static final String TRIGGER_2 = "trigger2"; protected PolicyRestAdapter policyAdapter = null; @@ -90,19 +87,25 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { // Empty constructor } + /** + * setDataToPolicyRestAdapter. + * + * @param policyData PolicyRestAdapter + * @param root JsonNode + * @return PolicyRestAdapter + */ public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) { 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); + final ClosedLoopFaultTrapDatas trapDatas = + mapper.readValue(root.get("trapData").toString(), ClosedLoopFaultTrapDatas.class); + final ClosedLoopFaultTrapDatas faultDatas = + mapper.readValue(root.get("faultData").toString(), ClosedLoopFaultTrapDatas.class); + final ClosedLoopGridJsonData policyJsonData = + mapper.readValue(root.get("policyData").get("policy").toString(), ClosedLoopGridJsonData.class); + final ClosedLoopFaultBody jsonBody = mapper.readValue( + root.get("policyData").get("policy").get("jsonBodyData").toString(), ClosedLoopFaultBody.class); // Build trapSignatureDatas list from faultData List<Object> trapSignatureDatas = new ArrayList<>(); @@ -118,10 +121,10 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { triggerSignatures.setTrapMaxAge(Integer.parseInt(policyData.getTrapMaxAge())); ClosedLoopFaultTriggerUISignatures uiTriggerSignatures = new ClosedLoopFaultTriggerUISignatures(); if (!trapSignatureDatas.isEmpty()) { - uiTriggerSignatures.setSignatures(getUITriggerSignature(TRAP, trapSignatureDatas.get(0))); + uiTriggerSignatures.setSignatures(getUiTriggerSignature(TRAP, trapSignatureDatas.get(0))); if (!policyJsonData.getConnecttriggerSignatures().isEmpty()) { uiTriggerSignatures - .setConnectSignatures(getUIConnectTraps(policyJsonData.getConnecttriggerSignatures())); + .setConnectSignatures(getUiConnectTraps(policyJsonData.getConnecttriggerSignatures())); } } jsonBody.setTriggerSignaturesUsedForUI(uiTriggerSignatures); @@ -144,19 +147,17 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { faultSignatures.setTimeWindow(Integer.parseInt(policyData.getVerificationclearTimeOut())); ClosedLoopFaultTriggerUISignatures uifaultSignatures = new ClosedLoopFaultTriggerUISignatures(); if (!faultSignatureDatas.isEmpty()) { - uifaultSignatures.setSignatures(getUITriggerSignature(FAULT, faultSignatureDatas.get(0))); + uifaultSignatures.setSignatures(getUiTriggerSignature(FAULT, faultSignatureDatas.get(0))); if (!policyJsonData.getConnectVerificationSignatures().isEmpty()) { - uifaultSignatures - .setConnectSignatures(getUIConnectTraps(policyJsonData.getConnectVerificationSignatures())); + uifaultSignatures.setConnectSignatures( + getUiConnectTraps(policyJsonData.getConnectVerificationSignatures())); } } jsonBody.setVerificationSignaturesUsedForUI(uifaultSignatures); jsonBody.setVerificationTimeWindowUsedForUI(Integer.parseInt(policyData.getVerificationclearTimeOut())); } jsonBody.setVerificationSignatures(faultSignatures); - ObjectWriter om = new ObjectMapper().writer(); - String json = om.writeValueAsString(jsonBody); - policyData.setJsonBody(json); + policyData.setJsonBody(new ObjectMapper().writer().writeValueAsString(jsonBody)); } catch (Exception e) { policyLogger.error("Exception Occured while setting data to Adapter", e); @@ -165,13 +166,14 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { } // TODO: Can getResultBody() and getFaultBody() be merged? - private String getResultBody(final ClosedLoopGridJSONData policyJsonData, final List<Object> trapSignatureDatas) { + private String getResultBody(final ClosedLoopGridJsonData policyJsonData, final List<Object> trapSignatureDatas) { StringBuilder resultBody = new StringBuilder(); 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()) { @@ -181,13 +183,14 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { return resultBody.toString(); } - private String getFaultBody(final ClosedLoopGridJSONData policyJsonData, final List<Object> faultSignatureDatas) { + private String getFaultBody(final ClosedLoopGridJsonData policyJsonData, final List<Object> faultSignatureDatas) { StringBuilder faultBody = new StringBuilder(); 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 +240,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); @@ -339,16 +342,18 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { attributesStr = attributesStr + "(" + readAttributes(objectList, iy) + ")"; } catch (NumberFormatException e) { try { - trap1Attrib = getVarbindOID(trap1Attrib); - attributesStr = attributesStr + "(" + URLEncoder.encode(trap1Attrib, ENC_UTF_8) + ")"; + trap1Attrib = getVarbindOid(trap1Attrib); + attributesStr = attributesStr + "(" + URLEncoder.encode(trap1Attrib, + PolicyUtils.CHARACTER_ENCODING) + ")"; } catch (UnsupportedEncodingException e1) { policyLogger.error("Caused Exception while Encoding Varbind Dictionary Values", e1); } } } else { try { - trap1Attrib = getVarbindOID(trap1Attrib); - attributesStr = attributesStr + "(" + URLEncoder.encode(trap1Attrib, ENC_UTF_8) + ")"; + trap1Attrib = getVarbindOid(trap1Attrib); + attributesStr = attributesStr + "(" + URLEncoder.encode(trap1Attrib, + PolicyUtils.CHARACTER_ENCODING) + ")"; } catch (UnsupportedEncodingException e) { policyLogger.error("Caused Exception while Encoding Varbind Dictionary Values", e); } @@ -356,21 +361,21 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { return attributesStr; } - private String getVarbindOID(String attrib) { + private String getVarbindOid(String attrib) { VarbindDictionary varbindId; try { - varbindId = (VarbindDictionary) commonclassdao - .getEntityItem(VarbindDictionary.class, "varbindName", attrib); - return varbindId.getVarbindOID(); + varbindId = + (VarbindDictionary) commonclassdao.getEntityItem(VarbindDictionary.class, "varbindName", attrib); + return varbindId.getVarbindOid(); } catch (Exception e) { policyLogger.error("Error during retrieving varbindName " + attrib, e); return attrib; } } - //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) { + private String getUiConnectTraps(List<Object> connectTrapSignatures) { StringBuilder resultBody = new StringBuilder(); String connectMainBody = ""; for (Object connectTrapSignature : connectTrapSignatures) { @@ -401,9 +406,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); } @@ -412,7 +416,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { } // get Trigger signature from JSON body - private String getUITriggerSignature(String trap, Object object2) { + private String getUiTriggerSignature(String trap, Object object2) { ClosedLoopFaultTrapDatas trapDatas = (ClosedLoopFaultTrapDatas) object2; List<Object> attributeList = new ArrayList<>(); // Read the Trap @@ -473,89 +477,69 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { return triggerBody.toString(); } + /** + * prePopulateClosedLoopFaultPolicyData. + * + * @param policyAdapter PolicyRestAdapter + * @param entity PolicyEntity + */ public void prePopulateClosedLoopFaultPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - if (policyAdapter.getPolicyData() instanceof PolicyType) { - PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); - - // Set PolicyAdapter policyName, description - setPolicyAdapterPolicyNameAndDescription(policyAdapter, policy); - - // Set PolicyAdapter JsonBodyData, timeout settings - setClosedLoopJSONFile(policyAdapter, entity); + if (! (policyAdapter.getPolicyData() instanceof PolicyType)) { + return; + } + PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); - // Get the target data under policy. - TargetType target = policy.getTarget(); - if (target == null) { - return; - } + // Set PolicyAdapter policyName, description + setPolicyAdapterPolicyNameAndDescription(policyAdapter, policy); - // Under target we have AnyOFType - List<AnyOfType> anyOfList = target.getAnyOf(); - if (anyOfList == null) { - return; - } + // Set PolicyAdapter JsonBodyData, timeout settings + setClosedLoopJsonFile(policyAdapter, entity); - // Set PolicyAdapter OnapNameField, riskType, riskLevel, guard, ttlDate from match attributes - setPolicyAdapterMatchAttributes(policyAdapter, anyOfList); + // Get the target data under policy. + TargetType target = policy.getTarget(); + if (target == null) { + return; } + + // Set PolicyAdapter OnapNameField, riskType, riskLevel, guard, ttlDate from match attributes + setPolicyAdapterMatchAttributes(policyAdapter, target.getAnyOf()); } 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. + policyAdapter.setupUsingAttribute(match.getAttributeDesignator().getAttributeId(), + (String) match.getAttributeValue().getContent().get(0)); + })); } 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); } - private void setClosedLoopJSONFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - ObjectMapper mapper = new ObjectMapper(); + private void setClosedLoopJsonFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) { try { - ClosedLoopFaultBody closedLoopBody = mapper - .readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopFaultBody.class); + ClosedLoopFaultBody closedLoopBody = + new ObjectMapper().readValue(entity.getConfigurationData().getConfigBody(), + ClosedLoopFaultBody.class); if ("ACTIVE".equalsIgnoreCase(closedLoopBody.getClosedLoopPolicyStatus())) { closedLoopBody.setClosedLoopPolicyStatus("Active"); } else { @@ -570,7 +554,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,7 +562,10 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { } } -class ClosedLoopGridJSONData { + +@Getter +@Setter +class ClosedLoopGridJsonData { private String clearTimeOut; private String trapMaxAge; @@ -586,44 +573,4 @@ class ClosedLoopGridJSONData { private List<Object> connecttriggerSignatures; private List<Object> connectVerificationSignatures; - public String getClearTimeOut() { - return clearTimeOut; - } - - public void setClearTimeOut(String clearTimeOut) { - this.clearTimeOut = clearTimeOut; - } - - public String getTrapMaxAge() { - return trapMaxAge; - } - - public void setTrapMaxAge(String trapMaxAge) { - this.trapMaxAge = trapMaxAge; - } - - public String getVerificationclearTimeOut() { - return verificationclearTimeOut; - } - - public void setVerificationclearTimeOut(String verificationclearTimeOut) { - this.verificationclearTimeOut = verificationclearTimeOut; - } - - - public List<Object> getConnecttriggerSignatures() { - return connecttriggerSignatures; - } - - public void setConnecttriggerSignatures(List<Object> connecttriggerSignatures) { - this.connecttriggerSignatures = connecttriggerSignatures; - } - - public List<Object> getConnectVerificationSignatures() { - return connectVerificationSignatures; - } - - public void setConnectVerificationSignatures(List<Object> connectVerificationSignatures) { - this.connectVerificationSignatures = connectVerificationSignatures; - } } 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..058542590 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); @@ -52,38 +52,40 @@ public class CreateClosedLoopPMController { protected PolicyRestAdapter policyAdapter = null; + /** + * prePopulateClosedLoopPMPolicyData. + * + * @param policyAdapter PolicyRestAdapter + * @param entity PolicyEntity + */ public void prePopulateClosedLoopPMPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - if (policyAdapter.getPolicyData() instanceof PolicyType) { - Object policyData = policyAdapter.getPolicyData(); - PolicyType policy = (PolicyType) policyData; + if (! (policyAdapter.getPolicyData() instanceof PolicyType)) { + return; + } + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; - // Set oldPolicyFileName to PolicyAdapter - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + // Set oldPolicyFileName to PolicyAdapter + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - // Set policyNameValue and description to PolicyAdapter - setPolicyAdapterNameValueAndDescription(policyAdapter, policy); + // Set policyNameValue and description to PolicyAdapter + setPolicyAdapterNameValueAndDescription(policyAdapter, policy); - // Set PolicyAdapter JsonBodyData - setClosedLoopJSONFile(policyAdapter, entity); + // Set PolicyAdapter JsonBodyData + setClosedLoopJsonFile(policyAdapter, entity); - // Get the target data under policy. - TargetType target = policy.getTarget(); - if (target == null) { - return; - } - // Under target we have AnyOFType - List<AnyOfType> anyOfList = target.getAnyOf(); - if (anyOfList == null) { - return; - } - // Set PolicyAdapter OnapNameField, riskType, riskLevel, guard, ttlDate, ServiceType from match attributes - setPolicyAdapterMatchAttributes(policyAdapter, anyOfList); + // Get the target data under policy. + TargetType target = policy.getTarget(); + if (target == null) { + return; } + // Set PolicyAdapter OnapNameField, riskType, riskLevel, guard, ttlDate, ServiceType from match attributes + setPolicyAdapterMatchAttributes(policyAdapter, target.getAnyOf()); } 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 { @@ -95,11 +97,10 @@ public class CreateClosedLoopPMController { policyAdapter.setPolicyDescription(description); } - private void setClosedLoopJSONFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - ObjectMapper mapper = new ObjectMapper(); + private void setClosedLoopJsonFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) { try { - ClosedLoopPMBody closedLoopBody = mapper - .readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopPMBody.class); + ClosedLoopPMBody closedLoopBody = + new ObjectMapper().readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopPMBody.class); policyAdapter.setJsonBodyData(closedLoopBody); } catch (IOException e) { LOGGER.error("Exception Occured" + e); @@ -107,51 +108,39 @@ 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. + policyAdapter.setupUsingAttribute(attributeId, value); + 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 +151,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 +162,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..4be31dd1e 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 @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2020 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,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; @@ -37,12 +36,13 @@ import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; -import java.io.PrintWriter; import java.io.StringReader; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; +import java.util.Base64; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; @@ -68,10 +68,10 @@ import javax.json.JsonReader; import javax.json.JsonValue; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import lombok.Getter; +import lombok.Setter; 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; @@ -82,20 +82,22 @@ import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringEscapeUtils; import org.json.JSONArray; import org.json.JSONObject; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.XacmlRestProperties; import org.onap.policy.rest.adapter.PolicyRestAdapter; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.GroupPolicyScopeList; import org.onap.policy.rest.jpa.MicroServiceModels; import org.onap.policy.rest.jpa.MicroserviceHeaderdeFaults; import org.onap.policy.rest.jpa.PolicyEntity; -import org.onap.policy.rest.util.MSAttributeObject; -import org.onap.policy.rest.util.MSModelUtils; -import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE; +import org.onap.policy.rest.util.MsAttributeObject; +import org.onap.policy.rest.util.MsModelUtils; +import org.onap.policy.rest.util.MsModelUtils.ModelType; +import org.onap.policy.utils.PolicyUtils; import org.onap.portalsdk.core.controller.RestrictedBaseController; import org.onap.portalsdk.core.web.support.JsonMessage; import org.springframework.beans.factory.annotation.Autowired; @@ -124,7 +126,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { private String directory; private List<String> modelList = new ArrayList<>(); private List<String> dirDependencyList = new ArrayList<>(); - private LinkedHashMap<String, MSAttributeObject> classMap = new LinkedHashMap<>(); + private LinkedHashMap<String, MsAttributeObject> classMap = new LinkedHashMap<>(); String referenceAttributes; String attributeString; Set<String> allManyTrueKeys = null; @@ -158,6 +160,13 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { private Map<String, LinkedList<String>> arrayTextList = new HashMap<>(); private Map<String, String> jsonStringValues = new HashMap<>(); + /** + * setDataToPolicyRestAdapter. + * + * @param policyData PolicyRestAdapter + * @param root JsonNode + * @return PolicyRestAdapter + */ public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) { String jsonContent = null; @@ -165,10 +174,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { LOGGER.info("policyJSON :" + (root.get(POLICYJSON)).toString()); String tempJson = root.get(POLICYJSON).toString(); - JSONObject policyJSON = new JSONObject(root.get(POLICYJSON).toString()); - if (policyJSON != null) { - tempJson = saveOriginalJsonObject(policyJSON, jsonStringValues).toString(); - } + JSONObject policyJson = new JSONObject(root.get(POLICYJSON).toString()); + tempJson = decodeJsonVal(tempJson, policyJson); // ---replace empty value with the value below before calling decodeContent method. String dummyValue = "*empty-value*" + UUID.randomUUID().toString(); LOGGER.info("dummyValue:" + dummyValue); @@ -189,12 +196,28 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { JSONObject content = contentJson.getJSONObject("content"); content = setOriginalJsonObject(content, jsonStringValues); contentJson.put("content", content); - policyData.setJsonBody(contentJson.toString()); + policyData.setJsonBody(StringEscapeUtils.unescapeJava(contentJson.toString())); } return policyData; } + private String decodeJsonVal(String tempJson, JSONObject policyJson) { + if (policyJson != null) { + for (Object key : policyJson.keySet()) { + String keyStr = (String) key; + Object keyvalue = policyJson.get(keyStr); + String decodedString = keyvalue.toString();//.replace("\"", ""); + if(!decodedString.equals("true") && !decodedString.equals("false")) { + String decodedJson = new String(Base64.getDecoder().decode(decodedString), StandardCharsets.UTF_8).replace("\"", "\\\""); + policyJson.put(keyStr, decodedJson); + } + } + tempJson = saveOriginalJsonObject(policyJson, jsonStringValues).toString(); + } + return tempJson; + } + private JSONObject saveOriginalJsonObject(JSONObject jsonObj, Map<String, String> jsonStringValues) { for (Object key : jsonObj.keySet()) { String keyStr = (String) key; @@ -259,7 +282,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { String json = ""; DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject(); MicroServiceModels returnModel = new MicroServiceModels(); - microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS)); + microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XacmlRestProperties.TEMPLATE_VERSION_MS)); if (policyAdapter.getServiceType() != null) { microServiceObject.setService(policyAdapter.getServiceType()); microServiceObject.setVersion(policyAdapter.getVersion()); @@ -309,15 +332,11 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { modelName + ":" + versionName); MicroServiceModels model = null; boolean ruleCheck = false; - boolean SymptomRuleCheck = false; if (!triggerData.isEmpty()) { model = (MicroServiceModels) triggerData.get(0); if (model.getRuleFormation() != null) { microServiceObject.setUiContent(jsonContent); ruleCheck = true; - if (model.getRuleFormation().contains("@")) { - SymptomRuleCheck = true; - } } } try { @@ -327,7 +346,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } LOGGER.info("input json: " + json); LOGGER.info("input jsonContent: " + jsonContent); - String cleanJson = cleanUPJson(json); + String cleanJson = cleanUpJson(json); // --- reset empty value back after called cleanUPJson method and before calling removeNullAttributes String tempJson = StringUtils.replaceEach(cleanJson, new String[] {"\"" + dummyValue + "\""}, new String[] {"\"\""}); @@ -340,40 +359,39 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { // for Triggers ObjectMapper mapper = new ObjectMapper(); JsonNode tempJsonNode = mapper.readTree(cleanJson); - if (ruleCheck) { - // JsonNode tempJsonNode = mapper.readTree(cleanJson); - ObjectNode finalJson = (ObjectNode) tempJsonNode; - JsonNode object = tempJsonNode.get("content"); - String primaryKey1 = model.getRuleFormation(); - String[] primaryKeyForSignatures = primaryKey1.split("@"); - for (String primaryKeyForSignature : primaryKeyForSignatures) { - String primarykeyAlarm = primaryKeyForSignature.substring(0, primaryKeyForSignature.indexOf('.')); - JsonNode triggerSig = object.get(primarykeyAlarm); - sigRules = new HashMap<>(); - String parseKey = primaryKeyForSignature.substring(primaryKeyForSignature.indexOf('.') + 1); - StringBuilder sb = null; - if (triggerSig instanceof ArrayNode) { - for (int i = 0; i < triggerSig.size(); i++) { - sb = new StringBuilder(); - parseData(triggerSig.get(i), parseKey); - sb.append("("); - List<?> keyList = new ArrayList<>(sigRules.keySet()); - for (int j = keyList.size() - 1; j >= 0; j--) { - String key = (String) keyList.get(j); - String jsonNode = sigRules.get(key); - constructRule(sb, jsonNode, sigRules); - } - sb.append(")").toString(); - putRuletoJson(tempJsonNode, i, sb, parseKey, primarykeyAlarm); - sigRules = new HashMap<>(); - } - } else { + if (! ruleCheck) { + return policyAdapter; + } + ObjectNode finalJson = (ObjectNode) tempJsonNode; + JsonNode object = tempJsonNode.get("content"); + String primaryKey1 = model.getRuleFormation(); + String[] primaryKeyForSignatures = primaryKey1.split("@"); + for (String primaryKeyForSignature : primaryKeyForSignatures) { + String primarykeyAlarm = primaryKeyForSignature.substring(0, primaryKeyForSignature.indexOf('.')); + JsonNode triggerSig = object.get(primarykeyAlarm); + sigRules = new HashMap<>(); + String parseKey = primaryKeyForSignature.substring(primaryKeyForSignature.indexOf('.') + 1); + StringBuilder sb = null; + if (triggerSig instanceof ArrayNode) { + for (int i = 0; i < triggerSig.size(); i++) { sb = new StringBuilder(); - parseData(triggerSig, parseKey); + parseData(triggerSig.get(i), parseKey); + sb.append("("); + List<?> keyList = new ArrayList<>(sigRules.keySet()); + for (int j = keyList.size() - 1; j >= 0; j--) { + String key = (String) keyList.get(j); + String jsonNode = sigRules.get(key); + constructRule(sb, jsonNode, sigRules); + } + sb.append(")").toString(); + putRuletoJson(tempJsonNode, i, sb, parseKey, primarykeyAlarm); + sigRules = new HashMap<>(); } + } else { + parseData(triggerSig, parseKey); } - policyAdapter.setJsonBody(finalJson.toString()); } + policyAdapter.setJsonBody(finalJson.toString()); return policyAdapter; } @@ -486,6 +504,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } } + /** + * removeNullAttributes. + * + * @param cleanJson String + * @returnString + */ public String removeNullAttributes(String cleanJson) { ObjectMapper mapper = new ObjectMapper(); @@ -529,9 +553,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { if (contentChanged) { // set modified content to cleanJson - JSONObject jObject = new JSONObject(cleanJson); - jObject.put("content", removed.toString()); - cleanJson = cleanUPJson(jObject.toString()); + JSONObject jsonObject = new JSONObject(cleanJson); + jsonObject.put("content", removed.toString()); + cleanJson = cleanUpJson(jsonObject.toString()); } } catch (IOException e) { @@ -554,90 +578,93 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { if (arrOfKeys[i].contains(".")) { arrOfKeys[i] = arrOfKeys[i].substring(arrOfKeys[i].indexOf(".") + 1); if (arrOfKeys[i].equals(key)) { - return StringUtils.replaceEach(jsonStringValues.get(k), new String[] {"\""}, - new String[] {"\\\""}); + return jsonStringValues.get(k); } } } } if (k.endsWith(key)) { - return StringUtils.replaceEach(jsonStringValues.get(k), new String[] {"\""}, new String[] {"\\\""}); + return jsonStringValues.get(k); } } return null; } + /** + * removeNull. + * + * @param array JsonArray + * @return JsonArray + */ public JsonArray removeNull(JsonArray array) { JsonArrayBuilder builder = Json.createArrayBuilder(); - int i = 0; - for (Iterator<JsonValue> it = array.iterator(); it.hasNext(); ++i) { + int index = 0; + for (Iterator<JsonValue> it = array.iterator(); it.hasNext(); ++index) { JsonValue value = it.next(); switch (value.getValueType()) { case ARRAY: - JsonArray a = removeNull(array.getJsonArray(i)); - if (!a.isEmpty()) - builder.add(a); + JsonArray tempArray = removeNull(array.getJsonArray(index)); + if (!tempArray.isEmpty()) { + builder.add(tempArray); + } break; case OBJECT: - JsonObject object = removeNull(array.getJsonObject(i)); - if (!object.isEmpty()) + JsonObject object = removeNull(array.getJsonObject(index)); + if (!object.isEmpty()) { builder.add(object); + } break; case STRING: - String s = array.getString(i); - if (s != null && !s.isEmpty()) - builder.add(s); + String str = array.getString(index); + if (str != null && !str.isEmpty()) { + builder.add(str); + } break; case NUMBER: - builder.add(array.getJsonNumber(i)); + builder.add(array.getJsonNumber(index)); break; case TRUE: case FALSE: - builder.add(array.getBoolean(i)); + builder.add(array.getBoolean(index)); break; case NULL: + default: break; } } return builder.build(); } + /** + * removeNull. + * + * @param obj JsonObject + * @return JsonObject + */ public JsonObject removeNull(JsonObject obj) { JsonObjectBuilder builder = Json.createObjectBuilder(); for (Iterator<Entry<String, JsonValue>> it = obj.entrySet().iterator(); it.hasNext();) { - Entry<String, JsonValue> e = it.next(); - String key = e.getKey(); - JsonValue value = e.getValue(); + Entry<String, JsonValue> entry = it.next(); + String key = entry.getKey(); + JsonValue value = entry.getValue(); switch (value.getValueType()) { case ARRAY: JsonArray array = removeNull(obj.getJsonArray(key)); - if (!array.isEmpty()) + if (!array.isEmpty()) { builder.add(key, array); + } break; case OBJECT: JsonObject object = removeNull(obj.getJsonObject(key)); if (!object.isEmpty()) { - if (!jsonStringValues.isEmpty()) { - String originalValue = getOriginalValue(key); - if (originalValue != null) { - builder.add(key, object.toString()); - break; - } - } builder.add(key, object); } break; case STRING: - String s = obj.getString(key); - if (s != null && !s.isEmpty()) { - if (!jsonStringValues.isEmpty()) { - String originalValue = getOriginalValue(key); - if (originalValue != null) { - s = getOriginalValue(key); - } - } - builder.add(key, s); + String str = obj.getString(key); + if (str != null && !str.isEmpty()) { + builder.add(key, str); } break; case NUMBER: @@ -648,13 +675,20 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { builder.add(key, obj.getBoolean(key)); break; case NULL: + default: break; } } return builder.build(); } - public String cleanUPJson(String json) { + /** + * cleanUpJson. + * + * @param json String + * @return String + */ + public String cleanUpJson(String json) { String cleanJson = StringUtils.replaceEach(json, new String[] {"\\\\", "\\\\\\", "\\\\\\\\"}, new String[] {"\\", "\\", "\\"}); cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\\\\"}, new String[] {"\\"}); @@ -675,6 +709,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { return cleanJson; } + /** + * decodeContent. + * + * @param jsonNode JsonNode + * @return JsonNode + */ public JSONObject decodeContent(JsonNode jsonNode) { Iterator<JsonNode> jsonElements = jsonNode.elements(); Iterator<String> jsonKeys = jsonNode.fieldNames(); @@ -825,7 +865,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 { @@ -862,8 +903,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { // Get all keys with "MANY-true" defined in their value from subAttribute Set<String> allkeys = null; - if (returnModel.getSub_attributes() != null && !returnModel.getSub_attributes().isEmpty()) { - JSONObject json = new JSONObject(returnModel.getSub_attributes()); + if (returnModel.getSubAttributes() != null && !returnModel.getSubAttributes().isEmpty()) { + JSONObject json = new JSONObject(returnModel.getSubAttributes()); getAllKeys(json); allkeys = allManyTrueKeys; allManyTrueKeys = new TreeSet<>(); @@ -882,7 +923,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { allMnyTrueKeys = allkeys.toString(); } - String jsonModel = createMicroSeriveJson(returnModel, allkeys); + String jsonModel = createMicroSeriveJson(returnModel); JSONObject jsonObject = new JSONObject(jsonModel); @@ -901,8 +942,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { jsonModel = finalJsonObject.toString(); } - // get all properties with "MANY-true" defined in Ref_attributes - Set<String> manyTrueProperties = getManyTrueProperties(returnModel.getRef_attributes()); + // get all properties with "MANY-true" defined in RefAttributes + Set<String> manyTrueProperties = getManyTrueProperties(returnModel.getRefAttributes()); if (manyTrueProperties != null) { JSONObject jsonObj = new JSONObject(jsonModel); for (String s : manyTrueProperties) { @@ -918,37 +959,36 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } } - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + response.setContentType(PolicyUtils.APPLICATION_JSON); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); List<Object> list = new ArrayList<>(); - PrintWriter out = response.getWriter(); String responseString = mapper.writeValueAsString(returnModel); - JSONObject j = null; + JSONObject json = null; if ("".equals(allMnyTrueKeys)) { - j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",dataOrderInfo:" + json = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData + "}"); } else { - j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",allManyTrueKeys: " - + allMnyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData - + "}"); + json = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + + ",allManyTrueKeys: " + allMnyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + + headDefautlsData + "}"); } - list.add(j); - out.write(list.toString()); + list.add(json); + response.getWriter().write(list.toString()); return null; } @SuppressWarnings({"unchecked", "rawtypes"}) - private String createMicroSeriveJson(MicroServiceModels returnModel, Set<String> allkeys) { + private String createMicroSeriveJson(MicroServiceModels returnModel) { Map<String, String> attributeMap = new HashMap<>(); Map<String, String> refAttributeMap = new HashMap<>(); String attribute = returnModel.getAttributes(); if (attribute != null) { attribute = attribute.trim(); } - String refAttribute = returnModel.getRef_attributes(); + String refAttribute = returnModel.getRefAttributes(); if (refAttribute != null) { refAttribute = refAttribute.trim(); } @@ -965,7 +1005,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { Gson gson = new Gson(); - String subAttributes = returnModel.getSub_attributes(); + String subAttributes = returnModel.getSubAttributes(); if (subAttributes != null) { subAttributes = subAttributes.trim(); } else { @@ -975,10 +1015,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class); JSONObject object = new JSONObject(); - JSONArray array = new JSONArray(); for (Entry<String, String> keySet : attributeMap.entrySet()) { - array = new JSONArray(); + JSONArray array = new JSONArray(); String value = keySet.getValue(); if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) { array.put(value); @@ -989,7 +1028,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } for (Entry<String, String> keySet : refAttributeMap.entrySet()) { - array = new JSONArray(); + JSONArray array = new JSONArray(); String value = keySet.getValue().split(":")[0]; if (gsonObject.containsKey(value)) { if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) { @@ -1042,7 +1081,6 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { return object; } - public JSONObject convertToArrayElement(JSONObject json, String keyValue) { return convertToArrayElement(json, new HashSet<>(), keyValue); } @@ -1070,14 +1108,25 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } if (obj instanceof JSONArray) { - convertToArrayElement(json.getJSONArray(key).getJSONObject(0), keyValue); + try { + if (json.getJSONArray(key).length() > 0) { + convertToArrayElement(json.getJSONArray(key).getJSONObject(0), keyValue); + } + } catch (Exception ex) { + LOGGER.info("XMI Model load issue : " + ex); + } } } return json; } - // call this method to get all MANY-true properties + /** + * getManyTrueProperties. + * + * @param referAttributes String + * @return a Set of String + */ public Set<String> getManyTrueProperties(String referAttributes) { LOGGER.info("referAttributes : " + referAttributes); Set<String> manyTrueProperties = new HashSet<>(); @@ -1108,10 +1157,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { private Set<String> getAllKeys(JSONArray arr, Set<String> keys) { for (int i = 0; i < arr.length(); i++) { Object obj = arr.get(i); - if (obj instanceof JSONObject) + if (obj instanceof JSONObject) { keys.addAll(getAllKeys(arr.getJSONObject(i))); - if (obj instanceof JSONArray) + } + if (obj instanceof JSONArray) { keys.addAll(getAllKeys(arr.getJSONArray(i))); + } } return keys; @@ -1126,37 +1177,42 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { LOGGER.info("obj : " + obj); allManyTrueKeys.add(key); } - if (obj instanceof JSONObject) + if (obj instanceof JSONObject) { keys.addAll(getAllKeys(json.getJSONObject(key))); - if (obj instanceof JSONArray) + } + if (obj instanceof JSONArray) { keys.addAll(getAllKeys(json.getJSONArray(key))); + } } return keys; } - - @RequestMapping(value = {"/policyController/getModelServiceVersioneData.htm"}, + /** + * getModelServiceVersionData. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + * @return ModelAndView + * @throws IOException IOException + */ + @RequestMapping( + value = {"/policyController/getModelServiceVersioneData.htm"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST}) public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - String value = root.get("policyData").toString().replaceAll("^\"|\"$", ""); + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + response.setContentType(PolicyUtils.APPLICATION_JSON); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + List<Object> list = new ArrayList<>(); + String value = mapper.readTree(request.getReader()).get("policyData").toString().replaceAll("^\"|\"$", ""); String servicename = value.split("-v")[0]; Set<String> returnList = getVersionList(servicename); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - List<Object> list = new ArrayList<>(); - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(returnList); - JSONObject j = new JSONObject("{dcaeModelVersionData: " + responseString + "}"); - list.add(j); - out.write(list.toString()); + list.add(new JSONObject("{dcaeModelVersionData: " + mapper.writeValueAsString(returnList) + "}")); + response.getWriter().write(list.toString()); return null; } @@ -1201,7 +1257,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) { @@ -1214,93 +1271,64 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { priorityList.add(String.valueOf(i)); } model.put("priorityDatas", mapper.writeValueAsString(priorityList)); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); + response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString()); } catch (Exception e) { LOGGER.error(e); } } + /** + * prePopulateDCAEMSPolicyData. + * + * @param policyAdapter PolicyRestAdapter + * @param entity PolicyEntity + */ public void prePopulateDCAEMSPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - if (policyAdapter.getPolicyData() instanceof PolicyType) { - Object policyData = policyAdapter.getPolicyData(); - PolicyType policy = (PolicyType) policyData; - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - String policyNameValue = - policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") + 3); - policyAdapter.setPolicyName(policyNameValue); - String description = ""; - try { - description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); - } catch (Exception e) { - LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e); - description = policy.getDescription(); - } - policyAdapter.setPolicyDescription(description); - // Get the target data under policy. - 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 (matchList.size() > 1 && 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 ("ConfigName".equals(attributeId)) { - policyAdapter.setConfigName(value); - } - if ("uuid".equals(attributeId)) { - policyAdapter.setUuid(value); - } - if ("location".equals(attributeId)) { - policyAdapter.setLocation(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); - } - } - readFile(policyAdapter, entity); - } - } - } - } + if (! (policyAdapter.getPolicyData() instanceof PolicyType)) { + return; + } + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = + policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") + 3); + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try { + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + } catch (Exception e) { + LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e); + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Get the target data under policy. + TargetType target = policy.getTarget(); + if (target == null) { + return; + } + for (AnyOfType anyOf : target.getAnyOf()) { + for (AllOfType allOf : anyOf.getAllOf()) { + // Under AllOFType we have Match + List<MatchType> matchList = allOf.getMatch(); + if (matchList == null) { + continue; } + Iterator<MatchType> iterMatch = matchList.iterator(); + // + // Can someone please explain why the matchList MUST have + // more than 1 matches??? + // + while (matchList.size() > 1 && iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attribute value and + // attributeDesignator. So,finally down to the actual attribute. + // + // First match in the target is OnapName, so set that value. + policyAdapter.setupUsingAttribute(match.getAttributeDesignator().getAttributeId(), + (String) match.getAttributeValue().getContent().get(0)); + } + readFile(policyAdapter, entity); } } } @@ -1321,7 +1349,6 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { return map; } - /** * Read file. * @@ -1330,12 +1357,11 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { */ @SuppressWarnings("unchecked") public void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - String policyScopeName = null; - ObjectMapper mapper = new ObjectMapper(); try { DCAEMicroServiceObject msBody = - mapper.readValue(entity.getConfigurationData().getConfigBody(), DCAEMicroServiceObject.class); - policyScopeName = getPolicyScope(msBody.getPolicyScope()); + new ObjectMapper().readValue(entity.getConfigurationData().getConfigBody(), + DCAEMicroServiceObject.class); + String policyScopeName = getPolicyScope(msBody.getPolicyScope()); policyAdapter.setPolicyScope(policyScopeName); policyAdapter.setPriority(msBody.getPriority()); @@ -1364,6 +1390,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } + /** + * readRecursivlyJSONContent. + * + * @param map Map of String to something + * @param data Map of String to Object + */ @SuppressWarnings({"rawtypes", "unchecked"}) public void readRecursivlyJSONContent(Map<String, ?> map, Map<String, Object> data) { for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) { @@ -1401,16 +1433,27 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } } + /** + * getPolicyScope. + * + * @param value String + * @return String + */ public String getPolicyScope(String value) { List<Object> groupList = commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value); if (groupList != null && !groupList.isEmpty()) { - GroupPolicyScopeList pScope = (GroupPolicyScopeList) groupList.get(0); - return pScope.getGroupName(); + return ((GroupPolicyScopeList) groupList.get(0)).getGroupName(); } return null; } - // Convert the map values and set into JSON body + /** + * Convert the map values and set into JSON body. + * + * @param attributesMap Map of attributes + * @param attributesRefMap Map of attribute references + * @return Map + */ public Map<String, String> convertMap(Map<String, String> attributesMap, Map<String, String> attributesRefMap) { Map<String, String> attribute = new HashMap<>(); StringBuilder temp; @@ -1448,7 +1491,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 { @@ -1490,35 +1534,31 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } if (!errorMsg.isEmpty()) { - - PrintWriter out = response.getWriter(); - response.setCharacterEncoding("UTF-8"); response.setContentType("application / json"); request.setCharacterEncoding("UTF-8"); - JSONObject j = new JSONObject(); - j.put("errorMsg", errorMsg); - out.write(j.toString()); + JSONObject json = new JSONObject(); + json.put("errorMsg", errorMsg); + response.getWriter().write(json.toString()); return; } List<File> fileList = new ArrayList<>(); - MSModelUtils msMLUtils = new MSModelUtils(commonClassDao); + MsModelUtils msModelUtils = new MsModelUtils(commonClassDao); this.directory = "model"; if (zip) { extractFolder(this.newFile); fileList = listModelFiles(this.directory); } else if (yml) { - errorMsg = msMLUtils.parseTosca(this.newFile); + errorMsg = msModelUtils.parseTosca(this.newFile); if (errorMsg != null) { - PrintWriter out = response.getWriter(); response.setCharacterEncoding("UTF-8"); response.setContentType("application / json"); request.setCharacterEncoding("UTF-8"); - JSONObject j = new JSONObject(); - j.put("errorMsg", errorMsg); - out.write(j.toString()); + JSONObject json = new JSONObject(); + json.put("errorMsg", errorMsg); + response.getWriter().write(json.toString()); return; } @@ -1533,7 +1573,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { classMap = new LinkedHashMap<>(); for (File file : fileList) { if (!file.isDirectory() && file.getName().endsWith(".xmi")) { - retreiveDependency(file.toString(), true); + retrieveDependency(file.toString()); } } @@ -1545,25 +1585,25 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { modelType = "yml"; modelList.add(this.newModel.getModelName()); String className = this.newModel.getModelName(); - MSAttributeObject msAttributes = new MSAttributeObject(); + MsAttributeObject msAttributes = new MsAttributeObject(); msAttributes.setClassName(className); LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>(); - returnAttributeList.put(className, msMLUtils.getAttributeString()); + returnAttributeList.put(className, msModelUtils.getAttributeString()); msAttributes.setAttribute(returnAttributeList); - msAttributes.setSubClass(msMLUtils.getRetmap()); + msAttributes.setSubClass(msModelUtils.getRetmap()); - msAttributes.setMatchingSet(msMLUtils.getMatchableValues()); + msAttributes.setMatchingSet(msModelUtils.getMatchableValues()); LinkedHashMap<String, String> returnReferenceList = new LinkedHashMap<>(); - returnReferenceList.put(className, msMLUtils.getReferenceAttributes()); + returnReferenceList.put(className, msModelUtils.getReferenceAttributes()); msAttributes.setRefAttribute(returnReferenceList); - if (msMLUtils.getListConstraints() != "") { + if (msModelUtils.getListConstraints() != "") { LinkedHashMap<String, String> enumList = new LinkedHashMap<>(); - String[] listArray = msMLUtils.getListConstraints().split("#"); + String[] listArray = msModelUtils.getListConstraints().split("#"); for (String str : listArray) { String[] strArr = str.split("="); if (strArr.length > 1) { @@ -1577,22 +1617,19 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { classMap.put(className, msAttributes); } - - PrintWriter out = response.getWriter(); - response.setCharacterEncoding("UTF-8"); response.setContentType("application / json"); request.setCharacterEncoding("UTF-8"); ObjectMapper mapper = new ObjectMapper(); - JSONObject j = new JSONObject(); - j.put("classListDatas", modelList); - j.put("modelDatas", mapper.writeValueAsString(classMap)); - j.put("modelType", modelType); - j.put("dataOrderInfo", msMLUtils.getDataOrderInfo()); - j.put("ruleFormation", msMLUtils.getJsonRuleFormation()); - - out.write(j.toString()); + JSONObject json = new JSONObject(); + json.put("classListDatas", modelList); + json.put("modelDatas", mapper.writeValueAsString(classMap)); + json.put("modelType", modelType); + json.put("dataOrderInfo", msModelUtils.getDataOrderInfo()); + json.put("ruleFormation", msModelUtils.getJsonRuleFormation()); + + response.getWriter().write(json.toString()); } /* @@ -1600,7 +1637,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { */ @SuppressWarnings("rawtypes") private void extractFolder(String zipFile) { - int BUFFER = 2048; + final int buffer = 2048; File file = new File(zipFile); try (ZipFile zip = new ZipFile(file)) { @@ -1623,10 +1660,10 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { if (!entry.isDirectory()) { BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry)); int currentByte; - byte[] data = new byte[BUFFER]; + byte[] data = new byte[buffer]; try (FileOutputStream fos = new FileOutputStream(destFile); - BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) { - while ((currentByte = is.read(data, 0, BUFFER)) != -1) { + BufferedOutputStream dest = new BufferedOutputStream(fos, buffer)) { + while ((currentByte = is.read(data, 0, buffer)) != -1) { dest.write(data, 0, currentByte); } dest.flush(); @@ -1648,25 +1685,21 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } } - private void retreiveDependency(String workingFile, Boolean modelClass) { + private void retrieveDependency(String workingFile) { - MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName()); - Map<String, MSAttributeObject> tempMap; + MsModelUtils utils = new MsModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName()); + Map<String, MsAttributeObject> tempMap; - tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI); + tempMap = utils.processEpackage(workingFile, ModelType.XMI); classMap.putAll(tempMap); LOGGER.info(tempMap); - - return; - } private List<File> listModelFiles(String directoryName) { File fileDirectory = new File(directoryName); List<File> resultList = new ArrayList<>(); - File[] fList = fileDirectory.listFiles(); - for (File file : fList) { + for (File file : fileDirectory.listFiles()) { if (file.isFile()) { resultList.add(file); } else if (file.isDirectory()) { @@ -1677,6 +1710,11 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { return resultList; } + /** + * cleanUp. + * + * @param path String + */ public void cleanUp(String path) { if (path != null) { try { @@ -1687,6 +1725,11 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } } + /** + * checkZipDirectory. + * + * @param zipDirectory String + */ public void checkZipDirectory(String zipDirectory) { Path path = Paths.get(zipDirectory); @@ -1697,9 +1740,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { private List<String> createList() { List<String> list = new ArrayList<>(); - for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()) { - if (cMap.getValue().isPolicyTempalate()) { - list.add(cMap.getKey()); + for (Entry<String, MsAttributeObject> entrySet : classMap.entrySet()) { + if (entrySet.getValue().isPolicyTempalate()) { + list.add(entrySet.getKey()); } } @@ -1732,7 +1775,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } - +@Getter +@Setter class DCAEMicroServiceObject { private String service; @@ -1749,128 +1793,5 @@ class DCAEMicroServiceObject { private String riskLevel; private String guard = null; private Object uiContent; - - public String getGuard() { - return guard; - } - - public void setGuard(String guard) { - this.guard = guard; - } - - public String getRiskType() { - return riskType; - } - - public void setRiskType(String riskType) { - this.riskType = riskType; - } - - public String getRiskLevel() { - return riskLevel; - } - - public void setRiskLevel(String riskLevel) { - this.riskLevel = riskLevel; - } - - public String getPolicyScope() { - return policyScope; - } - - public void setPolicyScope(String policyScope) { - this.policyScope = policyScope; - } - - public String getPriority() { - return priority; - } - - public void setPriority(String priority) { - this.priority = priority; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - private Object content; - - - public String getPolicyName() { - return policyName; - } - - public void setPolicyName(String policyName) { - this.policyName = policyName; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getConfigName() { - return configName; - } - - public void setConfigName(String configName) { - this.configName = configName; - } - - public Object getContent() { - return content; - } - - public void setContent(Object content) { - this.content = content; - } - - public String getService() { - return service; - } - - public void setService(String service) { - this.service = service; - } - - public String getLocation() { - return location; - } - - public void setLocation(String location) { - this.location = location; - } - - public String getUuid() { - return uuid; - } - - public void setUuid(String uuid) { - this.uuid = uuid; - } - - public String getTemplateVersion() { - return templateVersion; - } - - public void setTemplateVersion(String templateVersion) { - this.templateVersion = templateVersion; - } - - public Object getUiContent() { - return uiContent; - } - - public void setUiContent(Object uiContent) { - this.uiContent = uiContent; - } - } 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..3da703ab2 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,14 +2,14 @@ * ============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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -19,11 +19,16 @@ */ package org.onap.policy.controller; -import java.io.PrintWriter; + +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 java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -32,6 +37,12 @@ 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.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.lang3.StringUtils; import org.hibernate.SessionFactory; import org.json.JSONObject; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -55,13 +66,14 @@ import org.onap.policy.rest.adapter.TermCollector; import org.onap.policy.rest.adapter.VendorSpecificData; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.AddressGroup; -import org.onap.policy.rest.jpa.FWTagPicker; +import org.onap.policy.rest.jpa.FwTagPicker; import org.onap.policy.rest.jpa.GroupServiceList; import org.onap.policy.rest.jpa.PolicyEntity; import org.onap.policy.rest.jpa.PrefixList; import org.onap.policy.rest.jpa.SecurityZone; import org.onap.policy.rest.jpa.ServiceList; import org.onap.policy.rest.jpa.TermList; +import org.onap.policy.utils.PolicyUtils; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.onap.portalsdk.core.controller.RestrictedBaseController; import org.springframework.beans.factory.annotation.Autowired; @@ -69,886 +81,832 @@ 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_"; + private static CommonClassDao commonClassDao; + private List<String> tagCollectorList; + private List<String> termCollectorList; + + List<String> expandablePrefixIpList = new ArrayList<>(); + List<String> expandableServicesList = new ArrayList<>(); + + @Autowired + SessionFactory sessionFactory; + + public CreateFirewallController() { + // Empty constructor + } + + public static CommonClassDao getCommonClassDao() { + return commonClassDao; + } + + public static void setCommonClassDao(CommonClassDao commonClassDao) { + CreateFirewallController.commonClassDao = commonClassDao; + } + + @Autowired + private CreateFirewallController(CommonClassDao commonClassDao) { + CreateFirewallController.commonClassDao = commonClassDao; + } + + /** + * setDataToPolicyRestAdapter. + * + * @param policyData PolicyRestAdapter + * @return PolicyRestAdapter + */ + public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData) { + 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); + } + } + } + String jsonBody = constructJson(policyData); + if (StringUtils.isBlank(jsonBody)) { + policyData.setJsonBody(jsonBody); + } else { + policyData.setJsonBody("{}"); + } + // + // Hmmm - seems to be overriding the previous if statement + // + 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)) { + return; + } + 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) { + return; + } + // Under target we have AnyOFType + // NOTE: target.getAnyOf() will never be null + for (AnyOfType anyOf : target.getAnyOf()) { + for (AllOfType allOf : anyOf.getAllOf()) { + for (MatchType match : allOf.getMatch()) { + // + // Under the match we have attribute value and + // attributeDesignator. So,finally down to the actual attribute. + // + policyAdapter.setupUsingAttribute(match.getAttributeDesignator().getAttributeId(), + (String) match.getAttributeValue().getContent().get(0)); + } + } + } + } + + /** + * setFWViewRule. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + * @return ModelAndView + */ + @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.getServiceTransportProtocol()); + 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.getServiceTransportProtocol()); + 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(PolicyUtils.CHARACTER_ENCODING); + response.setContentType(PolicyUtils.APPLICATION_JSON); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + + String responseString = mapper.writeValueAsString(displayString); + response.getWriter().write(new JSONObject("{policyData: " + responseString + "}").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> mapSrcIp = null; + Map<Integer, String> mapDestIP = null; + Map<Integer, String> mapSrcPort = null; + Map<Integer, String> mapDestPort = null; + Map<Integer, String> mapAction = null; + Map<Integer, String> mapFromZone = null; + Map<Integer, String> mapToZone = 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 intCounter = 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(intCounter)); + tags.setNetworkRole(networkRole); + tagsList.add(tags); + intCounter++; + } + 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.getDescription(); + if ((ruleDesc != null) && (!ruleDesc.isEmpty())) { + targetTerm.setDescription(ruleDesc); + } + ruleFromZone = jpaTermList.getFromZone(); + + if ((ruleFromZone != null) && (!ruleFromZone.isEmpty())) { + mapFromZone = new HashMap<>(); + mapFromZone.put(tl, ruleFromZone); + } + ruleToZone = jpaTermList.getToZone(); + + if ((ruleToZone != null) && (!ruleToZone.isEmpty())) { + mapToZone = new HashMap<>(); + mapToZone.put(tl, ruleToZone); + } + ruleSrcPrefixList = jpaTermList.getSrcIpList(); + + if ((ruleSrcPrefixList != null) && (!ruleSrcPrefixList.isEmpty())) { + mapSrcIp = new HashMap<>(); + mapSrcIp.put(tl, ruleSrcPrefixList); + } + + ruleDestPrefixList = jpaTermList.getDestIpList(); + if ((ruleDestPrefixList != null) && (!ruleDestPrefixList.isEmpty())) { + mapDestIP = new HashMap<>(); + mapDestIP.put(tl, ruleDestPrefixList); + } + + ruleSrcPort = jpaTermList.getSrcPortList(); + + if (ruleSrcPort != null && (!ruleSrcPort.isEmpty())) { + mapSrcPort = new HashMap<>(); + mapSrcPort.put(tl, ruleSrcPort); + } + + ruleDestPort = jpaTermList.getDestPortList(); + + if (ruleDestPort != null && (!jpaTermList.getDestPortList().isEmpty())) { + mapDestPort = new HashMap<>(); + mapDestPort.put(tl, ruleDestPort); + } + + ruleAction = jpaTermList.getAction(); + + if ((ruleAction != null) && (!ruleAction.isEmpty())) { + mapAction = new HashMap<>(); + mapAction.put(tl, ruleAction); + } + } + } + targetTerm.setEnabled(true); + targetTerm.setLog(true); + targetTerm.setNegateSource(false); + targetTerm.setNegateDestination(false); + + if (mapAction != null) { + targetTerm.setAction(mapAction.get(tl)); + } + + // FromZone arrays + if (mapFromZone != null) { + List<String> fromZone = new ArrayList<>(); + for (String fromZoneStr : mapFromZone.get(tl).split(",")) { + fromZone.add(fromZoneStr); + } + targetTerm.setFromZones(fromZone); + } + + // ToZone arrays + if (mapToZone != null) { + List<String> toZone = new ArrayList<>(); + for (String toZoneStr : mapToZone.get(tl).split(",")) { + toZone.add(toZoneStr); + } + targetTerm.setToZones(toZone); + } + + // Destination Services. + if (mapDestPort != null) { + Set<ServicesJson> destServicesJsonList = new HashSet<>(); + for (String destServices : mapDestPort.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 ((mapSrcPort != null) && (mapDestPort != null)) { + String servicesCollateString = mapSrcPort.get(tl) + "," + mapDestPort.get(tl); + expandableServicesList.add(servicesCollateString); + } else if (mapSrcPort != null) { + expandableServicesList.add(mapSrcPort.get(tl)); + } else if (mapDestPort != null) { + expandableServicesList.add(mapDestPort.get(tl)); + } + + if (mapSrcIp != null) { + // Source List + List<AddressJson> sourceListArrayJson = new ArrayList<>(); + for (String srcList : mapSrcIp.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 (mapDestIP != null) { + // Destination List + List<AddressJson> destListArrayJson = new ArrayList<>(); + for (String destList : mapDestIP.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 ((mapSrcIp != null) && (mapDestIP != null)) { + String collateString = mapSrcIp.get(tl) + "," + mapDestIP.get(tl); + expandablePrefixIpList.add(collateString); + } else if (mapSrcIp != null) { + expandablePrefixIpList.add(mapSrcIp.get(tl)); + } else if (mapDestIP != null) { + expandablePrefixIpList.add(mapDestIP.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.getServiceTransportProtocol()); + 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.getServiceTransportProtocol()); + 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<String> valueDesc; + PrefixIPList targetAddressList = new PrefixIPList(); + 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 addressMembers = new AddressMembers(); + addressMembers.setType("SUBNET"); + if (!valueDesc.isEmpty()) { + addressMembers.setValue(valueDesc.get(0)); + } + List<AddressMembers> addMembersList = new ArrayList<>(); + 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(",")) { + AddressMembersJson addressMembers = new AddressMembersJson(); + addressMembers.setType("REFERENCES"); + addressMembers.setName(groupString); + addrMembersList.add(addressMembers); + // Expand the group Name + addressMembersJson = new AddressMembers(); + List<String> 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); + + try { + json = new ObjectMapper().writer().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..37f543f35 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,13 +27,13 @@ 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; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; -import java.io.PrintWriter; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; @@ -49,15 +48,17 @@ 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 lombok.Getter; +import lombok.Setter; 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.apache.commons.compress.utils.IOUtils; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; @@ -68,15 +69,16 @@ import org.json.JSONArray; import org.json.JSONObject; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.XacmlRestProperties; import org.onap.policy.rest.adapter.PolicyRestAdapter; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.MicroserviceHeaderdeFaults; import org.onap.policy.rest.jpa.OptimizationModels; import org.onap.policy.rest.jpa.PolicyEntity; -import org.onap.policy.rest.util.MSAttributeObject; -import org.onap.policy.rest.util.MSModelUtils; -import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE; +import org.onap.policy.rest.util.MsAttributeObject; +import org.onap.policy.rest.util.MsModelUtils; +import org.onap.policy.rest.util.MsModelUtils.ModelType; +import org.onap.policy.utils.PolicyUtils; import org.onap.portalsdk.core.controller.RestrictedBaseController; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; @@ -87,6 +89,9 @@ import org.springframework.web.servlet.ModelAndView; @RequestMapping("/") public class CreateOptimizationController extends RestrictedBaseController { private static final Logger LOGGER = FlexLogger.getLogger(CreateOptimizationController.class); + + private static final int BUFFER = 2048; + private static CommonClassDao commonClassDao; public static CommonClassDao getCommonClassDao() { @@ -98,7 +103,7 @@ public class CreateOptimizationController extends RestrictedBaseController { private String directory; private List<String> modelList = new ArrayList<>(); private List<String> dirDependencyList = new ArrayList<>(); - private LinkedHashMap<String, MSAttributeObject> classMap = new LinkedHashMap<>(); + private LinkedHashMap<String, MsAttributeObject> classMap = new LinkedHashMap<>(); String referenceAttributes; String attributeString; Set<String> allManyTrueKeys = new HashSet<>(); @@ -115,10 +120,7 @@ public class CreateOptimizationController extends RestrictedBaseController { public static final String MANYFALSE = ":MANY-false"; public static final String MODEL = "model"; public static final String MANY = "MANY-"; - public static final String UTF8 = "UTF-8"; public static final String MODELNAME = "modelName"; - public static final String APPLICATIONJSON = "application / json"; - @Autowired private CreateOptimizationController(CommonClassDao commonClassDao) { @@ -138,6 +140,13 @@ public class CreateOptimizationController extends RestrictedBaseController { private Map<String, LinkedList<String>> arrayTextList = new HashMap<>(); CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController(); + /** + * setDataToPolicyRestAdapter. + * + * @param policyData PolicyRestAdapter + * @param root JsonNode + * @return PolicyRestAdapter + */ public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) { String jsonContent = null; try { @@ -175,7 +184,7 @@ public class CreateOptimizationController extends RestrictedBaseController { } LOGGER.info("input json: " + json); LOGGER.info("input jsonContent: " + jsonContent); - String cleanJson = msController.cleanUPJson(json); + String cleanJson = msController.cleanUpJson(json); // --- reset empty value back after called cleanUPJson method and before calling removeNullAttributes String tempJson = @@ -186,7 +195,16 @@ public class CreateOptimizationController extends RestrictedBaseController { return policyAdapter; } - @RequestMapping(value = {"/policyController/getOptimizationTemplateData.htm"}, + /** + * getOptimizationTemplateData. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + * @return ModelAndView + * @throws IOException IOException + */ + @RequestMapping( + value = {"/policyController/getOptimizationTemplateData.htm"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST}) public ModelAndView getOptimizationTemplateData(HttpServletRequest request, HttpServletResponse response) throws IOException { @@ -196,10 +214,10 @@ public class CreateOptimizationController extends RestrictedBaseController { JsonNode root = mapper.readTree(request.getReader()); String value = root.get("policyData").toString().replaceAll("^\"|\"$", ""); - String servicename = value.toString().split("-v")[0]; + String servicename = value.split("-v")[0]; String version = null; - if (value.toString().contains("-v")) { - version = value.toString().split("-v")[1]; + if (value.contains("-v")) { + version = value.split("-v")[1]; } OptimizationModels returnModel = getAttributeObject(servicename, version); @@ -226,8 +244,7 @@ public class CreateOptimizationController extends RestrictedBaseController { // Get all keys with "MANY-true" defined in their value from subAttribute Set<String> allkeys = null; if (returnModel.getSubattributes() != null && !returnModel.getSubattributes().isEmpty()) { - JSONObject json = new JSONObject(returnModel.getSubattributes()); - getAllKeys(json); + getAllKeys(new JSONObject(returnModel.getSubattributes())); allkeys = allManyTrueKeys; allManyTrueKeys = new HashSet<>(); LOGGER.info("allkeys : " + allkeys); @@ -276,23 +293,22 @@ public class CreateOptimizationController extends RestrictedBaseController { jsonModel = finalJsonObject.toString(); } - response.setCharacterEncoding(UTF8); - response.setContentType(APPLICATIONJSON); - request.setCharacterEncoding(UTF8); + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + response.setContentType(PolicyUtils.APPLICATION_JSON); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); List<Object> list = new ArrayList<>(); - PrintWriter out = response.getWriter(); String responseString = mapper.writeValueAsString(returnModel); - JSONObject j = null; + JSONObject json = null; if ("".equals(nameOfTrueKeys)) { - j = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel + json = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData + "}"); } else { - j = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel + json = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel + ",allManyTrueKeys: " + allManyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData + "}"); } - list.add(j); - out.write(list.toString()); + list.add(json); + response.getWriter().write(list.toString()); return null; } @@ -415,10 +431,12 @@ public class CreateOptimizationController extends RestrictedBaseController { private Set<String> getAllKeys(JSONArray arr, Set<String> keys) { for (int i = 0; i < arr.length(); i++) { Object obj = arr.get(i); - if (obj instanceof JSONObject) + if (obj instanceof JSONObject) { keys.addAll(getAllKeys(arr.getJSONObject(i))); - if (obj instanceof JSONArray) + } + if (obj instanceof JSONArray) { keys.addAll(getAllKeys(arr.getJSONArray(i))); + } } return keys; @@ -433,16 +451,27 @@ public class CreateOptimizationController extends RestrictedBaseController { LOGGER.info("obj : " + obj); allManyTrueKeys.add(key); } - if (obj instanceof JSONObject) + if (obj instanceof JSONObject) { keys.addAll(getAllKeys(json.getJSONObject(key))); - if (obj instanceof JSONArray) + } + if (obj instanceof JSONArray) { keys.addAll(getAllKeys(json.getJSONArray(key))); + } } return keys; } - @RequestMapping(value = {"/policyController/getModelServiceVersionData.htm"}, + /** + * getModelServiceVersionData. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + * @return ModelAndView + * @throws IOException IOException + */ + @RequestMapping( + value = {"/policyController/getModelServiceVersionData.htm"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST}) public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response) throws IOException { @@ -450,19 +479,16 @@ public class CreateOptimizationController extends RestrictedBaseController { mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); - String value = root.get("policyData").toString().replaceAll("^\"|\"$", ""); - String servicename = value.split("-v")[0]; - Set<String> returnList = getVersionList(servicename); + final String value = root.get("policyData").toString().replaceAll("^\"|\"$", ""); + final String servicename = value.split("-v")[0]; - response.setCharacterEncoding(UTF8); - response.setContentType(APPLICATIONJSON); - request.setCharacterEncoding(UTF8); + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + response.setContentType(PolicyUtils.APPLICATION_JSON); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); List<Object> list = new ArrayList<>(); - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(returnList); - JSONObject j = new JSONObject("{optimizationModelVersionData: " + responseString + "}"); - list.add(j); - out.write(list.toString()); + list.add(new JSONObject("{optimizationModelVersionData: " + + mapper.writeValueAsString(getVersionList(servicename)) + "}")); + response.getWriter().write(list.toString()); return null; } @@ -507,76 +533,46 @@ public class CreateOptimizationController extends RestrictedBaseController { modelName); } + /** + * prePopulatePolicyData. + * + * @param policyAdapter PolicyRestAdapter + * @param entity PolicyEntity + */ public void prePopulatePolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - if (policyAdapter.getPolicyData() instanceof PolicyType) { - Object policyData = policyAdapter.getPolicyData(); - PolicyType policy = (PolicyType) policyData; - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - String policyNameValue = - policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("OOF_") + 4); - policyAdapter.setPolicyName(policyNameValue); - String description = ""; - try { - description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); - } catch (Exception e) { - LOGGER.error("Error while collecting the description tag in " + 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(); - 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 (matchList.size() > 1 && 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); - } - } - readFile(policyAdapter, entity); - } - } - } - } + if (! (policyAdapter.getPolicyData() instanceof PolicyType)) { + return; + } + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = + policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("OOF_") + 4); + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try { + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + } catch (Exception e) { + LOGGER.error("Error while collecting the description tag in " + policyNameValue, e); + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Get the target data under policy. + TargetType target = policy.getTarget(); + if (target == null) { + return; + } + for (AnyOfType anyOf : target.getAnyOf()) { + for (AllOfType allOf : anyOf.getAllOf()) { + for (MatchType match : allOf.getMatch()) { + // + // Under the match we have attribute value and + // attributeDesignator. So,finally down to the actual attribute. + // + policyAdapter.setupUsingAttribute(match.getAttributeDesignator().getAttributeId(), + (String) match.getAttributeValue().getContent().get(0)); } + readFile(policyAdapter, entity); } } } @@ -612,7 +608,16 @@ public class CreateOptimizationController extends RestrictedBaseController { } - @RequestMapping(value = {"/oof_dictionary/set_ModelData"}, + /** + * setModelData. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + * @throws IOException IOException + * @throws FileUploadException FileUploadException + */ + @RequestMapping( + value = {"/oof_dictionary/set_ModelData"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST}) public void setModelData(HttpServletRequest request, HttpServletResponse response) throws IOException, FileUploadException { @@ -655,21 +660,15 @@ public class CreateOptimizationController extends RestrictedBaseController { } if (!errorMsg.isEmpty()) { - - PrintWriter out = response.getWriter(); - - response.setCharacterEncoding(UTF8); - response.setContentType(APPLICATIONJSON); - request.setCharacterEncoding(UTF8); - - JSONObject j = new JSONObject(); - j.put("errorMsg", errorMsg); - out.write(j.toString()); + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + response.setContentType(PolicyUtils.APPLICATION_JSON); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + response.getWriter().write(new JSONObject().put("errorMsg", errorMsg).toString()); return; } List<File> fileList = new ArrayList<>(); - MSModelUtils modelUtil = new MSModelUtils(); + MsModelUtils modelUtil = new MsModelUtils(); this.directory = MODEL; if (zip) { extractFolder(this.newFile); @@ -699,7 +698,7 @@ public class CreateOptimizationController extends RestrictedBaseController { modelType = "yml"; modelList.add(this.newModel.getModelName()); String className = this.newModel.getModelName(); - MSAttributeObject optimizationAttributes = new MSAttributeObject(); + MsAttributeObject optimizationAttributes = new MsAttributeObject(); optimizationAttributes.setClassName(className); LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>(); @@ -731,20 +730,18 @@ public class CreateOptimizationController extends RestrictedBaseController { } - PrintWriter out = response.getWriter(); - - response.setCharacterEncoding(UTF8); - response.setContentType(APPLICATIONJSON); - request.setCharacterEncoding(UTF8); + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + response.setContentType(PolicyUtils.APPLICATION_JSON); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); ObjectMapper mapper = new ObjectMapper(); - JSONObject j = new JSONObject(); - j.put("classListDatas", modelList); - j.put("modelDatas", mapper.writeValueAsString(classMap)); - j.put("modelType", modelType); - j.put("dataOrderInfo", modelUtil.getDataOrderInfo()); + JSONObject json = new JSONObject(); + json.put("classListDatas", modelList); + json.put("modelDatas", mapper.writeValueAsString(classMap)); + json.put("modelType", modelType); + json.put("dataOrderInfo", modelUtil.getDataOrderInfo()); - out.write(j.toString()); + response.getWriter().write(json.toString()); } /* @@ -752,7 +749,6 @@ public class CreateOptimizationController extends RestrictedBaseController { */ @SuppressWarnings("rawtypes") private void extractFolder(String zipFile) { - int BUFFER = 2048; File file = new File(zipFile); try (ZipFile zip = new ZipFile(file)) { @@ -802,23 +798,19 @@ public class CreateOptimizationController extends RestrictedBaseController { private void retrieveDependency(String workingFile) { - MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName()); - Map<String, MSAttributeObject> tempMap; + MsModelUtils utils = new MsModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName()); + Map<String, MsAttributeObject> tempMap; - tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI); + tempMap = utils.processEpackage(workingFile, ModelType.XMI); classMap.putAll(tempMap); LOGGER.info(tempMap); - - return; - } private List<File> listModelFiles(String directoryName) { File fileDirectory = new File(directoryName); List<File> resultList = new ArrayList<>(); - File[] fList = fileDirectory.listFiles(); - for (File file : fList) { + for (File file : fileDirectory.listFiles()) { if (file.isFile()) { resultList.add(file); } else if (file.isDirectory()) { @@ -831,9 +823,9 @@ public class CreateOptimizationController extends RestrictedBaseController { private List<String> createList() { List<String> list = new ArrayList<>(); - for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()) { - if (cMap.getValue().isPolicyTempalate()) { - list.add(cMap.getKey()); + for (Entry<String, MsAttributeObject> entrySet : classMap.entrySet()) { + if (entrySet.getValue().isPolicyTempalate()) { + list.add(entrySet.getKey()); } } @@ -858,7 +850,7 @@ public class CreateOptimizationController extends RestrictedBaseController { private OptimizationObject setOptimizationObjectValues(PolicyRestAdapter policyAdapter) { OptimizationObject optimizationObject = new OptimizationObject(); - optimizationObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_OOF)); + optimizationObject.setTemplateVersion(XACMLProperties.getProperty(XacmlRestProperties.TEMPLATE_VERSION_OOF)); if (policyAdapter.getServiceType() != null) { optimizationObject.setService(policyAdapter.getServiceType()); @@ -888,7 +880,8 @@ public class CreateOptimizationController extends RestrictedBaseController { } } - +@Getter +@Setter class OptimizationObject { private String service; @@ -901,95 +894,5 @@ class OptimizationObject { private String riskType; private String riskLevel; private String guard = null; - - public String getGuard() { - return guard; - } - - public void setGuard(String guard) { - this.guard = guard; - } - - public String getRiskType() { - return riskType; - } - - public void setRiskType(String riskType) { - this.riskType = riskType; - } - - public String getRiskLevel() { - return riskLevel; - } - - public void setRiskLevel(String riskLevel) { - this.riskLevel = riskLevel; - } - - public String getPriority() { - return priority; - } - - public void setPriority(String priority) { - this.priority = priority; - } - - public String getPolicyScope() { - return policyScope; - } - - public void setPolicyScope(String policyScope) { - this.policyScope = policyScope; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - private Object content; - - public String getPolicyName() { - return policyName; - } - - public void setPolicyName(String policyName) { - this.policyName = policyName; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public Object getContent() { - return content; - } - - public void setContent(Object content) { - this.content = content; - } - - public String getService() { - return service; - } - - public void setService(String service) { - this.service = service; - } - - public String getTemplateVersion() { - return templateVersion; - } - - public void setTemplateVersion(String templateVersion) { - this.templateVersion = templateVersion; - } - } 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..a2cf20834 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,14 +2,14 @@ * ============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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,13 +20,18 @@ 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 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.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.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.rest.adapter.PolicyRestAdapter; @@ -35,117 +40,87 @@ 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; -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 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; - - 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++; - } - } - } - } - } - } + protected PolicyRestAdapter policyAdapter = null; + private ArrayList<Object> attributeList; + boolean isValidForm = false; - 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()); - } - } - } - } + /** + * prePopulateBaseConfigPolicyData. + * + * @param policyAdapter PolicyRestAdapter + * @param entity PolicyEntity + */ + public void prePopulateBaseConfigPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + attributeList = new ArrayList<>(); + if (! (policyAdapter.getPolicyData() instanceof PolicyType)) { + return; + } + 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(); + // + // NOTE: target.getAnyOf() will NEVER return null + // + if (target != null) { + // Under target we have AnyOFType + for (AnyOfType anyOf : target.getAnyOf()) { + // Under AnyOFType we have AllOFType + // + // NOTE: anyOf.getAllOf() will NEVER return null + // + int index = 0; + for (AllOfType allOf : anyOf.getAllOf()) { + // Under AllOFType we have Match + // NOTE: allOf.getMatch() will NEVER be NULL + // + for (MatchType match : allOf.getMatch()) { + // + // Under the match we have attribute value and + // attributeDesignator. So,finally down to the actual attribute. + // + String value = (String) match.getAttributeValue().getContent().get(0); + String attributeId = match.getAttributeDesignator().getAttributeId(); + // First match in the target is OnapName, so set that value. + policyAdapter.setupUsingAttribute(attributeId, 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 object : ruleList) { + if (object instanceof RuleType) { + // get the condition data under the rule for rule Algorithms. + policyAdapter.setRuleID(((RuleType) object).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..0ca315bf1 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,12 +55,13 @@ 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; import org.onap.policy.dao.SystemLogDbDao; import org.onap.policy.model.PDPGroupContainer; -import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.XacmlRestProperties; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.PolicyEntity; import org.onap.policy.utils.PolicyUtils; @@ -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) { @@ -135,9 +137,7 @@ public class DashboardController extends RestrictedBaseController { mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); addPolicyCrudInfoToTable(); model.put("papStatusCRUDData", mapper.writeValueAsString(policyStatusCrudData)); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); + response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString()); } catch (Exception e) { policyLogger.error(exceptionOccured, e); } @@ -145,11 +145,12 @@ public class DashboardController extends RestrictedBaseController { /** * This method retrieves data based on input criteria. - * + * * @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; @@ -185,11 +186,9 @@ public class DashboardController extends RestrictedBaseController { getPolicyData(lscope, lstage, isDelected, ttlDateAfter, ttlDateBefore); Map<String, Object> model = new HashMap<>(); model.put("policyStatusCRUDData", mapper.writeValueAsString(policyStatusCrudData)); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); + response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString()); } catch (Exception e) { - response.setCharacterEncoding("UTF-8"); + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); PrintWriter out = response.getWriter(); out.write(PolicyUtils.CATCH_EXCEPTION); } @@ -198,11 +197,12 @@ public class DashboardController extends RestrictedBaseController { /** * This method is to retrieve data from PolicyEntity table. - * + * * @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) { @@ -211,15 +211,20 @@ public class DashboardController extends RestrictedBaseController { ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); model.put("pdpStatusCRUDData", mapper.writeValueAsString(pdpStatusCrudData)); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); + response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString()); } catch (Exception e) { policyLogger.error(exceptionOccured, e); } } - @RequestMapping(value = {"/get_DashboardLoggingData"}, + /** + * getData. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + */ + @RequestMapping( + value = {"/get_DashboardLoggingData"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getData(HttpServletRequest request, HttpServletResponse response) { @@ -227,15 +232,20 @@ public class DashboardController extends RestrictedBaseController { Map<String, Object> model = new HashMap<>(); ObjectMapper mapper = new ObjectMapper(); model.put("availableLoggingDatas", mapper.writeValueAsString(systemDAO.getLoggingData())); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); + response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString()); } catch (Exception e) { policyLogger.error(exceptionOccured + e); } } - @RequestMapping(value = {"/get_DashboardSystemAlertData"}, + /** + * getSystemAlertData. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + */ + @RequestMapping( + value = {"/get_DashboardSystemAlertData"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getSystemAlertData(HttpServletRequest request, HttpServletResponse response) { @@ -243,15 +253,20 @@ public class DashboardController extends RestrictedBaseController { Map<String, Object> model = new HashMap<>(); ObjectMapper mapper = new ObjectMapper(); model.put("systemAlertsTableDatas", mapper.writeValueAsString(systemDAO.getSystemAlertData())); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); + response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString()); } catch (Exception e) { policyLogger.error(exceptionOccured + e); } } - @RequestMapping(value = {"/get_DashboardPAPStatusData"}, + /** + * getPAPStatusData. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + */ + @RequestMapping( + value = {"/get_DashboardPAPStatusData"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPAPStatusData(HttpServletRequest request, HttpServletResponse response) { @@ -261,20 +276,25 @@ public class DashboardController extends RestrictedBaseController { mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); addPAPToTable(); model.put("papTableDatas", mapper.writeValueAsString(papStatusData)); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); + response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString()); } catch (Exception e) { policyLogger.error(exceptionOccured + e); } } - @RequestMapping(value = {"/get_DashboardPDPStatusData"}, + /** + * getPDPStatusData. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + */ + @RequestMapping( + value = {"/get_DashboardPDPStatusData"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPDPStatusData(HttpServletRequest request, HttpServletResponse response) { try { - Map<String, Object> model = new HashMap<>(); + final Map<String, Object> model = new HashMap<>(); ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); PolicyController controller = getPolicyControllerInstance(); @@ -282,28 +302,32 @@ public class DashboardController extends RestrictedBaseController { addPDPToTable(); model.put("pdpTableDatas", mapper.writeValueAsString(pdpStatusData)); JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); + response.getWriter().write(new JSONObject(msg).toString()); } catch (Exception e) { policyLogger.error(exceptionOccured + e); } } - @RequestMapping(value = {"/get_DashboardPolicyActivityData"}, + /** + * getPolicyActivityData. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + */ + @RequestMapping( + value = {"/get_DashboardPolicyActivityData"}, method = {org.springframework.web.bind.annotation.RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPolicyActivityData(HttpServletRequest request, HttpServletResponse response) { try { - Map<String, Object> model = new HashMap<>(); + final Map<String, Object> model = new HashMap<>(); ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); PolicyController controller = getPolicyControllerInstance(); this.pdpConatiner = new PDPGroupContainer(controller.getPapEngine()); addPolicyToTable(); model.put("policyActivityTableDatas", mapper.writeValueAsString(policyActivityData)); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); + response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString()); } catch (Exception e) { policyLogger.error(exceptionOccured + e); } @@ -327,9 +351,9 @@ public class DashboardController extends RestrictedBaseController { papStatus = "CANNOT_CONNECT"; policyLogger.error("Error getting PAP status, PAP not responding to requests", e1); } - String papURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); + String papUrl = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URL); JSONObject object = new JSONObject(); - object.put("system", papURL); + object.put("system", papUrl); object.put("status", papStatus); List<Object> data = commonClassDao.getDataByQuery("from PolicyEntity", new SimpleBindings()); object.put("noOfPolicy", data.size()); @@ -337,9 +361,8 @@ public class DashboardController extends RestrictedBaseController { papStatusData.add(0, object); } - - /* - * Add the PAP Policy information to the PAP Table + /** + * Add the PAP Policy information to the PAP Table. */ public void addPolicyCrudInfoToTable() { policyStatusCrudData = new ArrayList<>(); @@ -362,7 +385,7 @@ public class DashboardController extends RestrictedBaseController { object.put(scope, ((PolicyEntity) data).getScope()); object.put("policyName", ((PolicyEntity) data).getPolicyName()); object.put("version", ((PolicyEntity) data).getVersion()); - if (isPushedToPDP(((PolicyEntity) data).getPolicyId())) { + if (isPushedToPdp(((PolicyEntity) data).getPolicyId())) { object.put(stage, "PDP"); } else { object.put(stage, "PAP"); @@ -388,13 +411,13 @@ public class DashboardController extends RestrictedBaseController { /* * Add the PDP Policy information to the PDP Table */ - private boolean isPushedToPDP(long policyId) { + private boolean isPushedToPdp(long policyId) { try { String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId"; SimpleBindings geParams = new SimpleBindings(); geParams.put("policyEntityId", policyId); List<Object> groupobject = commonClassDao.getDataByQuery(groupEntityquery, geParams); - if (groupobject != null && groupobject.size() > 0) { + if (groupobject != null && ! groupobject.isEmpty()) { return true; } } catch (Exception e) { @@ -407,7 +430,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(); @@ -479,7 +503,7 @@ public class DashboardController extends RestrictedBaseController { object.put(scope, data.getScope()); object.put("policyName", data.getPolicyName()); object.put("version", data.getVersion()); - if (isPushedToPDP(data.getPolicyId())) { + if (isPushedToPdp(data.getPolicyId())) { object.put(stage, "PDP"); } else { object.put(stage, "PAP"); @@ -503,7 +527,7 @@ public class DashboardController extends RestrictedBaseController { } /** - * Add PDP Information to the PDP Table + * Add PDP Information to the PDP Table. * */ public void addPDPToTable() { @@ -516,7 +540,7 @@ public class DashboardController extends RestrictedBaseController { for (PDP pdp : group.getPdps()) { naCount = -1; if ("UP_TO_DATE".equals(pdp.getStatus().getStatus().toString()) && ((OnapPDP) pdp).getJmxPort() != 0) { - String pdpIpAddress = parseIPSystem(pdp.getId()); + String pdpIpAddress = parseIpSystem(pdp.getId()); int port = ((OnapPDP) pdp).getJmxPort(); if (port != 0) { policyLogger.debug("Getting JMX Response Counts from " + pdpIpAddress + " at JMX port " + port); @@ -553,7 +577,7 @@ public class DashboardController extends RestrictedBaseController { } } - private static String parseIPSystem(String line) { + private static String parseIpSystem(String line) { Pattern pattern = Pattern.compile("://(.+?):"); Matcher ip = pattern.matcher(line); if (ip.find()) { @@ -570,13 +594,12 @@ public class DashboardController extends RestrictedBaseController { policyLogger.debug("Create an RMI connector client and connect it to the JMX connector server"); HashMap map = null; - try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map)) { + try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionUrl(host, port), map)) { jmxConnection.connect(); - Object o = - jmxConnection.getMBeanServerConnection().getAttribute( - new ObjectName("PdpRest:type=PdpRestMonitor"), jmxAttribute); - policyLogger.debug("pdpEvaluationNA value retreived: " + o); - return (long) o; + Object obj = jmxConnection.getMBeanServerConnection() + .getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), jmxAttribute); + policyLogger.debug("pdpEvaluationNA value retreived: " + obj); + return (long) obj; } catch (MalformedURLException e) { policyLogger.error("MalformedURLException for JMX connection", e); } catch (IOException e) { @@ -597,11 +620,10 @@ public class DashboardController extends RestrictedBaseController { return -1; } - private static JMXServiceURL createConnectionURL(String host, int port) throws MalformedURLException { + private static JMXServiceURL createConnectionUrl(String host, int port) throws MalformedURLException { return new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi"); } - /* * Add the information to the Policy Table */ @@ -626,8 +648,8 @@ public class DashboardController extends RestrictedBaseController { // Add rows to the Policy Table policyList = null; if ("UP_TO_DATE".equals(pdp.getStatus().getStatus().toString()) && ((OnapPDP) pdp).getJmxPort() != 0) { - String pdpIpAddress = parseIPSystem(pdp.getId()); - policyList = getPolicy(pdpIpAddress, ((OnapPDP) pdp).getJmxPort(), "policyCount"); + String pdpIpAddress = parseIpSystem(pdp.getId()); + policyList = getPolicy(pdpIpAddress, ((OnapPDP) pdp).getJmxPort()); } if (policyList != null && policyList.toString().length() > 3) { String[] splitPolicy = policyList.toString().split(","); @@ -643,19 +665,15 @@ public class DashboardController extends RestrictedBaseController { } } } else { + JSONObject object = new JSONObject(); if (policyList != null) { - JSONObject object = new JSONObject(); object.put("policyId", "Unable to retrieve policy information"); - object.put("fireCount", "NA"); - object.put("system", pdp.getId()); - policyActivityData.add(object); } else { - JSONObject object = new JSONObject(); object.put("policyId", "Unable to access PDP JMX Server"); - object.put("fireCount", "NA"); - object.put("system", pdp.getId()); - policyActivityData.add(object); } + object.put("fireCount", "NA"); + object.put("system", pdp.getId()); + policyActivityData.add(object); } } } @@ -665,17 +683,16 @@ public class DashboardController extends RestrictedBaseController { * Contact JMX Connector Sever and return the list of {policy id , count} */ @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); + private Object getPolicy(String host, int port) { + 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)) { + try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionUrl(host, port), map)) { jmxConnection.connect(); - Object o = - jmxConnection.getMBeanServerConnection().getAttribute( - new ObjectName("PdpRest:type=PdpRestMonitor"), "policyMap"); - policyLogger.debug("policyMap value retreived: " + o); - return o; + Object obj = jmxConnection.getMBeanServerConnection() + .getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), "policyMap"); + policyLogger.debug("policyMap value retreived: " + obj); + return obj; } catch (MalformedURLException e) { policyLogger.error("MalformedURLException for JMX connection", e); } catch (IOException e) { @@ -705,8 +722,7 @@ public class DashboardController extends RestrictedBaseController { private static Integer countPolicyID(String line) { String[] splitLine = line.split("="); - String sCount = splitLine[1].replace("}", ""); - return Integer.parseInt(sCount); + return Integer.parseInt(splitLine[1].replace("}", "")); } } 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..c3b474521 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,14 +2,14 @@ * ============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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -25,24 +25,13 @@ import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; -import java.util.Iterator; 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,28 +48,47 @@ 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) { + + /** + * rawXacmlPolicy. Should this method be private? + * + * @param policyAdapter PolicyRestAdapter + * @param entity PolicyEntity + */ + public void rawXacmlPolicy(PolicyRestAdapter policyAdapter, PolicyEntity entity) { try (InputStream policyXmlStream = XACMLPolicyWriter.getXmlAsInputStream(policyAdapter.getPolicyData())) { String name = StringUtils.substringAfter(entity.getPolicyName(), "Decision_"); policyAdapter.setPolicyName(name.substring(0, name.indexOf('.'))); @@ -91,6 +99,12 @@ public class DecisionPolicyController extends RestrictedBaseController { } } + /** + * prePopulateDecisionPolicyData. + * + * @param policyAdapter PolicyRestAdapter + * @param entity PolicyEntity + */ @SuppressWarnings("unchecked") public void prePopulateDecisionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { List<Object> attributeList = new ArrayList<>(); @@ -106,237 +120,222 @@ public class DecisionPolicyController extends RestrictedBaseController { } if (rawPolicyCheck) { - rawXACMLPolicy(policyAdapter, entity); - } else { - RainyDayParams rainydayParams = new RainyDayParams(); - Object policyData = policyAdapter.getPolicyData(); - PolicyType policy = (PolicyType) policyData; - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - - policyAdapter.setPolicyName(StringUtils.substringAfter(policyAdapter.getPolicyName(), "Decision_")); - String description = ""; - String blackListEntryType = "Use Manual Entry"; - try { - if (policy.getDescription().contains(BLENTRY)) { - blackListEntryType = policy.getDescription().substring(policy.getDescription().indexOf(BLENTRY) + 9, - policy.getDescription().lastIndexOf(BLENTRY)); - } - policyAdapter.setBlackListEntryType(blackListEntryType); - description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + rawXacmlPolicy(policyAdapter, entity); + return; + } + RainyDayParams rainydayParams = new RainyDayParams(); + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - } catch (Exception e) { - policyLogger.info("General error", e); - description = policy.getDescription(); + policyAdapter.setPolicyName(StringUtils.substringAfter(policyAdapter.getPolicyName(), "Decision_")); + String description = ""; + String blackListEntryType = "Use Manual Entry"; + try { + if (policy.getDescription().contains(BLENTRY)) { + blackListEntryType = policy.getDescription().substring(policy.getDescription().indexOf(BLENTRY) + 9, + policy.getDescription().lastIndexOf(BLENTRY)); } - policyAdapter.setPolicyDescription(description); - // Get the target data under policy for Action. - TargetType target = policy.getTarget(); - if (target != null) { - // under target we have AnyOFType - List<AnyOfType> anyOfList = target.getAnyOf(); - if (anyOfList != null) { - Iterator<AnyOfType> iterAnyOf = anyOfList.iterator(); - while (iterAnyOf.hasNext()) { - AnyOfType anyOf = iterAnyOf.next(); - // Under AntOfType we have AllOfType - List<AllOfType> allOfList = anyOf.getAllOf(); - if (allOfList != null) { - Iterator<AllOfType> iterAllOf = allOfList.iterator(); - while (iterAllOf.hasNext()) { - AllOfType allOf = iterAllOf.next(); - // Under AllOfType we have Mathch. - List<MatchType> matchList = allOf.getMatch(); - int index = 0; - if (matchList != null) { - Iterator<MatchType> iterMatch = matchList.iterator(); - while (iterMatch.hasNext()) { - MatchType match = iterMatch.next(); - // - // Under the match we have attributevalue and - // attributeDesignator. So,finally down to the actual attribute. - // - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - if (value != null) { - value = value.replaceAll("\\(\\?i\\)", ""); - } - 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); - } - // Component attributes are saved under Target here we are fetching them back. - // One row is default so we are not adding dynamic component at index 0. - if (index >= 1) { - Map<String, String> attribute = new HashMap<>(); - attribute.put("key", attributeId); - attribute.put("value", value); - attributeList.add(attribute); - } - index++; - } - } - policyAdapter.setAttributes(attributeList); - } - } - } - // Setting rainy day attributes to the parameters object if they exist - boolean rainy = false; - if (!attributeList.isEmpty()) { - for (int i = 0; i < attributeList.size(); i++) { - Map<String, String> map = (Map<String, String>) attributeList.get(i); - if ("WorkStep".equals(map.get("key"))) { - rainydayParams.setWorkstep(map.get("value")); - rainy = true; - } else if ("BB_ID".equals(map.get("key"))) { - rainydayParams.setBbid(map.get("value")); - rainy = true; - } else if ("ServiceType".equals(map.get("key"))) { - rainydayParams.setServiceType(map.get("value")); - rainy = true; - } else if ("VNFType".equals(map.get("key"))) { - rainydayParams.setVnfType(map.get("value")); - rainy = true; - } - } + policyAdapter.setBlackListEntryType(blackListEntryType); + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + + } catch (Exception e) { + policyLogger.info("General error", e); + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Get the target data under policy for Action. + TargetType target = policy.getTarget(); + if (target == null) { + rainydayParams.setTreatmentTableChoices(treatmentList); + policyAdapter.setRainyday(rainydayParams); + policyAdapter.setSettings(decisionList); + return; + } + // under target we have AnyOFType + for (AnyOfType anyOf : target.getAnyOf()) { + for (AllOfType allOf : anyOf.getAllOf()) { + int index = 0; + for (MatchType match : allOf.getMatch()) { + // + // Under the match we have attributevalue and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + if (value != null) { + value = value.replaceAll("\\(\\?i\\)", ""); } - if (rainy) { - policyAdapter.setRuleProvider("Rainy_Day"); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + // First match in the target is OnapName, so set that value. + policyAdapter.setupUsingAttribute(attributeId, value); + // Component attributes are saved under Target here we are fetching them back. + // One row is default so we are not adding dynamic component at index 0. + if (index >= 1) { + Map<String, String> attribute = new HashMap<>(); + attribute.put("key", attributeId); + attribute.put("value", value); + attributeList.add(attribute); } + index++; + } + policyAdapter.setAttributes(attributeList); + } + } + // Setting rainy day attributes to the parameters object if they exist + boolean rainy = false; + if (!attributeList.isEmpty()) { + for (int i = 0; i < attributeList.size(); i++) { + Map<String, String> map = (Map<String, String>) attributeList.get(i); + String key = map.get("key"); + if ("WorkStep".equals(key)) { + rainydayParams.setWorkstep(map.get("value")); + rainy = true; + } else if ("BB_ID".equals(key)) { + rainydayParams.setBbid(map.get("value")); + rainy = true; + } else if ("ServiceType".equals(key)) { + rainydayParams.setServiceType(map.get("value")); + rainy = true; + } else if ("VNFType".equals(key)) { + rainydayParams.setVnfType(map.get("value")); + rainy = true; } + } + } + if (rainy) { + policyAdapter.setRuleProvider("Rainy_Day"); + } - List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); - int index = 0; - for (Object object : ruleList) { - if (object instanceof VariableDefinitionType) { - VariableDefinitionType variableDefinitionType = (VariableDefinitionType) object; - Map<String, String> settings = new HashMap<>(); - settings.put("key", variableDefinitionType.getVariableId()); - JAXBElement<AttributeValueType> attributeValueTypeElement = - (JAXBElement<AttributeValueType>) variableDefinitionType.getExpression(); - if (attributeValueTypeElement != null) { - AttributeValueType attributeValueType = attributeValueTypeElement.getValue(); - settings.put("value", attributeValueType.getContent().get(0).toString()); + List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); + int index = 0; + for (Object object : ruleList) { + if (object instanceof VariableDefinitionType) { + VariableDefinitionType variableDefinitionType = (VariableDefinitionType) object; + Map<String, String> settings = new HashMap<>(); + settings.put("key", variableDefinitionType.getVariableId()); + JAXBElement<AttributeValueType> attributeValueTypeElement = + (JAXBElement<AttributeValueType>) variableDefinitionType.getExpression(); + if (attributeValueTypeElement != null) { + AttributeValueType attributeValueType = attributeValueTypeElement.getValue(); + settings.put("value", attributeValueType.getContent().get(0).toString()); + } + decisionList.add(settings); + } else if (object instanceof RuleType) { + // get the condition data under the rule for rule Algorithms. + if (((RuleType) object).getEffect().equals(EffectType.DENY)) { + if (((RuleType) object).getAdviceExpressions() != null) { + if ("AAF".equalsIgnoreCase(((RuleType) object).getAdviceExpressions() + .getAdviceExpression().get(0).getAdviceId())) { + policyAdapter.setRuleProvider("AAF"); + break; + } else if (GUARD_YAML.equalsIgnoreCase(((RuleType) object).getAdviceExpressions() + .getAdviceExpression().get(0).getAdviceId())) { + policyAdapter.setRuleProvider(GUARD_YAML); + } else if (GUARD_BL_YAML.equalsIgnoreCase(((RuleType) object).getAdviceExpressions() + .getAdviceExpression().get(0).getAdviceId())) { + policyAdapter.setRuleProvider(GUARD_BL_YAML); + } else if (GUARD_MIN_MAX.equalsIgnoreCase(((RuleType) object).getAdviceExpressions() + .getAdviceExpression().get(0).getAdviceId())) { + policyAdapter.setRuleProvider(GUARD_MIN_MAX); } - decisionList.add(settings); - } else if (object instanceof RuleType) { - // get the condition data under the rule for rule Algorithms. - if (((RuleType) object).getEffect().equals(EffectType.DENY)) { - if (((RuleType) object).getAdviceExpressions() != null) { - if ("AAF".equalsIgnoreCase(((RuleType) object).getAdviceExpressions() - .getAdviceExpression().get(0).getAdviceId())) { - policyAdapter.setRuleProvider("AAF"); - break; - } else if (GUARD_YAML.equalsIgnoreCase(((RuleType) object).getAdviceExpressions() - .getAdviceExpression().get(0).getAdviceId())) { - policyAdapter.setRuleProvider(GUARD_YAML); - } else if (GUARD_BL_YAML.equalsIgnoreCase(((RuleType) object).getAdviceExpressions() - .getAdviceExpression().get(0).getAdviceId())) { - policyAdapter.setRuleProvider(GUARD_BL_YAML); - } else if (GUARD_MIN_MAX.equalsIgnoreCase(((RuleType) object).getAdviceExpressions() - .getAdviceExpression().get(0).getAdviceId())) { - policyAdapter.setRuleProvider(GUARD_MIN_MAX); + } else { + policyAdapter.setRuleProvider("Custom"); + } + ConditionType condition = ((RuleType) object).getCondition(); + if (condition != null) { + ApplyType decisionApply = (ApplyType) condition.getExpression().getValue(); + decisionApply = (ApplyType) decisionApply.getExpression().get(0).getValue(); + ruleAlgoirthmTracker = new LinkedList<>(); + if (policyAdapter.getRuleProvider() != null + && (GUARD_YAML.equals(policyAdapter.getRuleProvider()) + || (GUARD_BL_YAML.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); + String key = map.get("key"); + if ("actor".equals(key)) { + yamlParams.setActor(map.get("value")); + } else if ("recipe".equals(key)) { + yamlParams.setRecipe(map.get("value")); + } else if ("target".equals(key)) { + yamlParams.setTargets(Arrays.asList(map.get("value").split("\\|"))); + } else if ("clname".equals(key)) { + yamlParams.setClname(map.get("value")); + } else if ("min".equals(key)) { + yamlParams.setMin(map.get("value")); + } else if ("max".equals(key)) { + yamlParams.setMax(map.get("value")); } - } else { - policyAdapter.setRuleProvider("Custom"); } - ConditionType condition = ((RuleType) object).getCondition(); - if (condition != null) { - ApplyType decisionApply = (ApplyType) condition.getExpression().getValue(); - decisionApply = (ApplyType) decisionApply.getExpression().get(0).getValue(); - ruleAlgoirthmTracker = new LinkedList<>(); - if (policyAdapter.getRuleProvider() != null - && (GUARD_YAML.equals(policyAdapter.getRuleProvider()) - || (GUARD_BL_YAML.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); - if ("actor".equals(map.get("key"))) { - yamlParams.setActor(map.get("value")); - } else if ("recipe".equals(map.get("key"))) { - yamlParams.setRecipe(map.get("value")); - } else if ("target".equals(map.get("key"))) { - yamlParams.setTargets(Arrays.asList(map.get("value").split("\\|"))); - } else if ("clname".equals(map.get("key"))) { - yamlParams.setClname(map.get("value")); - } else if ("min".equals(map.get("key"))) { - yamlParams.setMin(map.get("value")); - } else if ("max".equals(map.get("key"))) { - yamlParams.setMax(map.get("value")); - } - } - ApplyType apply = - (ApplyType) ((ApplyType) decisionApply.getExpression().get(0).getValue()) - .getExpression().get(0).getValue(); - yamlParams.setGuardActiveStart( - ((AttributeValueType) apply.getExpression().get(1).getValue()).getContent() - .get(0).toString()); - yamlParams.setGuardActiveEnd( - ((AttributeValueType) apply.getExpression().get(2).getValue()).getContent() - .get(0).toString()); - if (GUARD_BL_YAML.equals(policyAdapter.getRuleProvider())) { - apply = (ApplyType) ((ApplyType) ((ApplyType) decisionApply.getExpression() - .get(0).getValue()).getExpression().get(1).getValue()).getExpression() - .get(2).getValue(); - Iterator<JAXBElement<?>> attributes = apply.getExpression().iterator(); - List<String> blackList = new ArrayList<>(); - while (attributes.hasNext()) { - blackList.add(((AttributeValueType) attributes.next().getValue()) - .getContent().get(0).toString()); - } - yamlParams.setBlackList(blackList); - if ("Use File Upload".equals(policyAdapter.getBlackListEntryType())) { - policyAdapter.setBlackListEntries(blackList); - } - } else { - ApplyType timeWindowSection = (ApplyType) ((ApplyType) decisionApply - .getExpression().get(0).getValue()).getExpression().get(1).getValue(); - yamlParams.setLimit(((AttributeValueType) timeWindowSection.getExpression() - .get(1).getValue()).getContent().get(0).toString()); - String timeWindow = ((AttributeDesignatorType) ((ApplyType) timeWindowSection - .getExpression().get(0).getValue()).getExpression().get(0).getValue()) - .getIssuer(); - yamlParams.setTimeUnits(timeWindow.substring(timeWindow.lastIndexOf(':') + 1)); - yamlParams.setTimeWindow(timeWindow.substring(timeWindow.indexOf(":tw:") + 4, - timeWindow.lastIndexOf(':'))); - } - policyAdapter.setYamlparams(yamlParams); - policyAdapter.setAttributes(new ArrayList<Object>()); - policyAdapter.setRuleAlgorithmschoices(new ArrayList<Object>()); - break; + ApplyType apply = + (ApplyType) ((ApplyType) decisionApply.getExpression().get(0).getValue()) + .getExpression().get(0).getValue(); + yamlParams.setGuardActiveStart( + ((AttributeValueType) apply.getExpression().get(1).getValue()).getContent() + .get(0).toString()); + yamlParams.setGuardActiveEnd( + ((AttributeValueType) apply.getExpression().get(2).getValue()).getContent() + .get(0).toString()); + if (GUARD_BL_YAML.equals(policyAdapter.getRuleProvider())) { + apply = (ApplyType) ((ApplyType) ((ApplyType) decisionApply.getExpression() + .get(0).getValue()).getExpression().get(1).getValue()).getExpression() + .get(2).getValue(); + List<String> blackList = new ArrayList<>(); + for (JAXBElement<?> attr : apply.getExpression()) { + blackList.add(((AttributeValueType) attr.getValue()) + .getContent().get(0).toString()); } - // Populating Rule Algorithms starting from compound. - prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply); - policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList); + yamlParams.setBlackList(blackList); + if ("Use File Upload".equals(policyAdapter.getBlackListEntryType())) { + policyAdapter.setBlackListEntries(blackList); + } + } else { + ApplyType timeWindowSection = (ApplyType) ((ApplyType) decisionApply + .getExpression().get(0).getValue()).getExpression().get(1).getValue(); + yamlParams.setLimit(((AttributeValueType) timeWindowSection.getExpression() + .get(1).getValue()).getContent().get(0).toString()); + String timeWindow = ((AttributeDesignatorType) ((ApplyType) timeWindowSection + .getExpression().get(0).getValue()).getExpression().get(0).getValue()) + .getIssuer(); + yamlParams.setTimeUnits(timeWindow.substring(timeWindow.lastIndexOf(':') + 1)); + yamlParams.setTimeWindow(timeWindow.substring(timeWindow.indexOf(":tw:") + 4, + timeWindow.lastIndexOf(':'))); } - } else if (policyAdapter.getRuleProvider() != null - && "Rainy_Day".equals(policyAdapter.getRuleProvider()) - && ((RuleType) object).getEffect().equals(EffectType.PERMIT)) { + policyAdapter.setYamlparams(yamlParams); + policyAdapter.setAttributes(new ArrayList<Object>()); + policyAdapter.setRuleAlgorithmschoices(new ArrayList<Object>()); + break; + } + // Populating Rule Algorithms starting from compound. + prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply); + policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList); + } + } else if (policyAdapter.getRuleProvider() != null + && "Rainy_Day".equals(policyAdapter.getRuleProvider()) + && ((RuleType) object).getEffect().equals(EffectType.PERMIT)) { - TargetType ruleTarget = ((RuleType) object).getTarget(); - AdviceExpressionsType adviceExpression = ((RuleType) object).getAdviceExpressions(); + TargetType ruleTarget = ((RuleType) object).getTarget(); + AdviceExpressionsType adviceExpression = ((RuleType) object).getAdviceExpressions(); - String errorcode = ruleTarget.getAnyOf().get(0).getAllOf().get(0).getMatch().get(1) - .getAttributeValue().getContent().get(0).toString(); - JAXBElement<AttributeValueType> tempTreatmentObj = - (JAXBElement<AttributeValueType>) adviceExpression.getAdviceExpression().get(0) - .getAttributeAssignmentExpression().get(0).getExpression(); - String treatment = tempTreatmentObj.getValue().getContent().get(0).toString(); + String errorcode = ruleTarget.getAnyOf().get(0).getAllOf().get(0).getMatch().get(1) + .getAttributeValue().getContent().get(0).toString(); + JAXBElement<AttributeValueType> tempTreatmentObj = + (JAXBElement<AttributeValueType>) adviceExpression.getAdviceExpression().get(0) + .getAttributeAssignmentExpression().get(0).getExpression(); + String treatment = tempTreatmentObj.getValue().getContent().get(0).toString(); - prePopulateRainyDayTreatments(errorcode, treatment); + prePopulateRainyDayTreatments(errorcode, treatment); - } - } } } - - rainydayParams.setTreatmentTableChoices(treatmentList); - policyAdapter.setRainyday(rainydayParams); - policyAdapter.setSettings(decisionList); } + rainydayParams.setTreatmentTableChoices(treatmentList); + policyAdapter.setRainyday(rainydayParams); + policyAdapter.setSettings(decisionList); } private void prePopulateRainyDayTreatments(String errorcode, String treatment) { @@ -377,7 +376,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); @@ -402,36 +400,36 @@ public class DecisionPolicyController extends RestrictedBaseController { index++; } } - if (isCompoundRule) { - // As it's compound rule, Get the Apply types - for (JAXBElement<?> jaxbElement : jaxbDecisionTypes) { - ApplyType innerDecisionApply = (ApplyType) jaxbElement.getValue(); - index = prePopulateDecisionCompoundRuleAlgorithm(index, innerDecisionApply); - } - // Populate combo box - if (policyLogger.isDebugEnabled()) { - policyLogger.debug("Prepopulating Compound rule algorithm: " + index); - } - Map<String, String> rule = new HashMap<>(); - for (String key : PolicyController.getDropDownMap().keySet()) { - String keyValue = PolicyController.getDropDownMap().get(key); - if (keyValue.equals(decisionApply.getFunctionId())) { - rule.put("dynamicRuleAlgorithmCombo", key); - break; - } + if (! isCompoundRule) { + return index; + } + // As it's compound rule, Get the Apply types + for (JAXBElement<?> jaxbElement : jaxbDecisionTypes) { + ApplyType innerDecisionApply = (ApplyType) jaxbElement.getValue(); + index = prePopulateDecisionCompoundRuleAlgorithm(index, innerDecisionApply); + } + // Populate combo box + if (policyLogger.isDebugEnabled()) { + policyLogger.debug("Prepopulating Compound rule algorithm: " + index); + } + Map<String, String> rule = new HashMap<>(); + for (String key : PolicyController.getDropDownMap().keySet()) { + String keyValue = PolicyController.getDropDownMap().get(key); + if (keyValue.equals(decisionApply.getFunctionId())) { + rule.put("dynamicRuleAlgorithmCombo", key); + break; } - - rule.put("id", "A" + (index + 1)); - // Populate Key and values for Compound Rule - rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1)); - ruleAlgoirthmTracker.removeLast(); - rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1)); - ruleAlgoirthmTracker.removeLast(); - ruleAlgoirthmTracker.addLast(index); - ruleAlgorithmList.add(rule); - index++; } - return index; + rule.put("id", "A" + (index + 1)); + // Populate Key and values for Compound Rule + rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1)); + ruleAlgoirthmTracker.removeLast(); + rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1)); + ruleAlgoirthmTracker.removeLast(); + ruleAlgoirthmTracker.addLast(index); + ruleAlgorithmList.add(rule); + + return ++index; } } 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..0c0c15f05 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,14 +2,14 @@ * ============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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -39,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; @@ -59,6 +61,7 @@ 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.ReturnBlackList; +import org.onap.policy.utils.PolicyUtils; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.onap.portalsdk.core.controller.RestrictedBaseController; import org.onap.portalsdk.core.web.support.JsonMessage; @@ -66,7 +69,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. @@ -84,7 +86,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr /** * This method is used to Export the Black List entries data from Decision BlackList Guard YAML Policy. So, user can * update the file on adding or removing the entries, for updating the policies or using in other Environments. - * + * * @param request the request contains the policy data. So, based on that we can populate and read and write the * entries. * @param response after reading and writing the blacklist list entries to file, the file is copied to tmp directory @@ -117,7 +119,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr /* * Export FileName is the combination of BlacList+Scope+PolicyName+Version+PolicyCreatedDate. - * + * */ SimpleDateFormat parseFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @@ -126,7 +128,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); @@ -145,9 +147,9 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr workBook.write(fos); fos.flush(); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + response.setContentType(PolicyUtils.APPLICATION_JSON); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); PrintWriter out = response.getWriter(); String successMap = file.substring(file.lastIndexOf("webapps") + 8); @@ -163,7 +165,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr /** * This method is used to import the BlackList excel file into the system. Which is used to create Decision * Blacklist Guard YAML Policy. - * + * * @param request the HTTP request contains file upload stream form GUI. * @param response the response is send to the GUI after reading the file input stream. */ @@ -181,9 +183,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr } else { readItems(items, errorLogs, model); } - JsonMessage msg = new JsonMessage(mapper.toJson(model)); - JSONObject jsonResposne = new JSONObject(msg); - response.getWriter().write(jsonResposne.toString()); + response.getWriter().write(new JSONObject(new JsonMessage(mapper.toJson(model))).toString()); } catch (FileUploadException | IOException e) { policyLogger.error("Exception Occured while importing the BlackListEntry", e); } @@ -191,7 +191,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr /** * This method is used to read the first item, as we expect only one entry in the file upload. - * + * * @param items The file entries which were uploaded from GUI. * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed. * @param model Map which stores key value (blacklist and append list data) @@ -218,7 +218,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr /** * This method is used to read the workbook in xls file item. - * + * * @param fileName fileName as input parameter * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed. * @param model Map which stores key value (blacklist and append list data) @@ -246,7 +246,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr /** * This method is used to read all the rows from imported Excel sheet and set to respective objects. - * + * * @param rowIterator Excel Sheet rows are passed as input parameters. * @param blackListEntries the data is set to this object, which is going to be added. * @param appendBlackListEntries the data is set to this object which is going to be removed. @@ -266,7 +266,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr /** * This method is used to read all the cells in the row. - * + * * @param cellIterator iterating the cells and will parse based on the cell type. * @param blackListEntries the data is set to this object, which is going to be added. * @param appendBlackListEntries the data is set to this object which is going to be removed. @@ -300,7 +300,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr /** * This method is used to read the Action cell entry. - * + * * @param cell reading the action entry cell. * @param lineNo counts the number of the cell. * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed. @@ -328,7 +328,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr /** * This method is used to read the BlackList cell entry. - * + * * @param cell reading the blacklist entry cell. * @param lineNo counts the number of the cell. * @param errorLogs on adding all incorrect entries, we can let user know what need to fixed. @@ -353,7 +353,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr /** * This method is used to add the data to blacklist and append list after parsing each and every row. - * + * * @param actionEntry it has the input to add or not and holds either 0 or 1. * @param blackListEntries list to add blacklist entries based on action entry = 1. * @param appendBlackListEntries list to add append list entries based on action entry = 0. @@ -370,7 +370,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr /** * This method is used to identify the header of the cell. - * + * * @param cell Excel sheet cell is passed as input parameter. * @return the column header name value */ 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..f2f7d57af 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,14 +2,14 @@ * ============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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,9 +20,13 @@ 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; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; @@ -32,16 +36,17 @@ import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - +import lombok.Getter; +import lombok.Setter; import org.json.JSONObject; import org.onap.policy.admin.RESTfulPAPEngine; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.model.PDPGroupContainer; +import org.onap.policy.utils.PolicyUtils; import org.onap.policy.utils.UserUtils.Pair; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.onap.policy.xacml.api.pap.OnapPDPGroup; -import org.onap.policy.xacml.api.pap.PAPPolicyEngine; import org.onap.policy.xacml.std.pap.StdPDP; import org.onap.policy.xacml.std.pap.StdPDPGroup; import org.onap.portalsdk.core.controller.RestrictedBaseController; @@ -51,370 +56,377 @@ 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; + } + + /** + * refreshGroups. + * + * @param request HttpServletRequest + */ + 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.second; + scopes = pair.first; + + 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) { 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); + PolicyController.setPapEngine(new RESTfulPAPEngine(request.getRequestURL().toString())); + } catch (Exception e) { + policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception Occured while loading PAP", e); + } + } + + /** + * getPDPGroupEntityData. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + */ + @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 { + refreshGroups(request); + response.getWriter().write(new JSONObject(new JsonMessage( + new ObjectMapper().writeValueAsString(groups))).toString()); + } catch (Exception e) { + policyLogger.error( + XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while retrieving the PDP Group data" + e); + } + } + + /** + * savePDPGroup. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + */ + @RequestMapping( + value = {"/pdp_Group/save_pdp_group"}, + method = {org.springframework.web.bind.annotation.RequestMethod.POST}) + public void savePDPGroup(HttpServletRequest request, HttpServletResponse response) { + try { + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + // + // + // + 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.setContentType(PolicyUtils.APPLICATION_JSON); + + refreshGroups(request); + response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString()); + } catch (Exception e) { + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Saving the PDP Group" + e); + try { + response.getWriter().write(e.getMessage()); + } catch (Exception e1) { + policyLogger + .error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Saving the PDP Group" + e1); + } + } + } + + /** + * removePDPGroup. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + */ + @RequestMapping( + value = {"/pdp_Group/remove_pdp_group"}, + method = {org.springframework.web.bind.annotation.RequestMethod.POST}) + public void removePDPGroup(HttpServletRequest request, HttpServletResponse response) { + try { + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + // + // + // + 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.setContentType(PolicyUtils.APPLICATION_JSON); + refreshGroups(request); + response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString()); + } catch (Exception e) { + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Removing the PDP Group" + e); + try { + response.getWriter().write(e.getMessage()); + } catch (Exception e1) { + policyLogger.error("Exception Occured" + e1); + } + } + } + + /** + * savePDPToGroup. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + */ + @RequestMapping( + value = {"/pdp_Group/save_pdpTogroup"}, + method = {org.springframework.web.bind.annotation.RequestMethod.POST}) + public void savePDPToGroup(HttpServletRequest request, HttpServletResponse response) { + try { + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + // + // + // + 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.setContentType(PolicyUtils.APPLICATION_JSON); + refreshGroups(request); + response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString()); + } catch (Exception e) { + policyLogger + .error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Creating Pdp in PDP Group" + e); + try { + response.getWriter().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; - } + /** + * removePDPFromGroup. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + */ + @RequestMapping( + value = {"/pdp_Group/remove_pdpFromGroup"}, + method = {org.springframework.web.bind.annotation.RequestMethod.POST}) + public void removePDPFromGroup(HttpServletRequest request, HttpServletResponse response) { + try { + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + // + // + // + 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 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( + "************************************************************************************************"); + + StdPDP deletePdp = mapper.readValue(root.get("data").toString(), StdPDP.class); + StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class); + this.container.removePDP(deletePdp, activeGroupData); + response.setContentType(PolicyUtils.APPLICATION_JSON); + + refreshGroups(request); + response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString()); + } catch (Exception e) { + policyLogger.error( + XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Removing Pdp from PDP Group" + e); + try { + response.getWriter().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; - } - +@Getter +@Setter +class PdpData { + String id; + int jmxPort; + String name; + String 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..dbf744829 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; @@ -52,7 +56,7 @@ import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.model.PDPGroupContainer; import org.onap.policy.model.Roles; -import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.XacmlRestProperties; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.Datatype; import org.onap.policy.rest.jpa.FunctionDefinition; @@ -60,6 +64,7 @@ import org.onap.policy.rest.jpa.PolicyEntity; import org.onap.policy.rest.jpa.PolicyVersion; import org.onap.policy.rest.jpa.UserInfo; import org.onap.policy.utils.PeCryptoUtils; +import org.onap.policy.utils.PolicyUtils; import org.onap.policy.utils.UserUtils.Pair; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.onap.policy.xacml.api.pap.PAPPolicyEngine; @@ -99,7 +104,7 @@ public class PolicyController extends RestrictedBaseController { } public static String getDomain() { - return XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_DOMAIN, "urn"); + return XACMLProperties.getProperty(XacmlRestProperties.PROP_ADMIN_DOMAIN, "urn"); } private static final Object mapAccess = new Object(); @@ -108,8 +113,6 @@ public class PolicyController extends RestrictedBaseController { // Constant variables used across Policy-sdk private static final String policyData = "policyData"; - private static final String characterEncoding = "UTF-8"; - private static final String contentType = "application/json"; private static final String file = "file"; private static final String SUPERADMIN = "super-admin"; private static final String POLICYGUEST = "Policy Guest"; @@ -160,8 +163,8 @@ public class PolicyController extends RestrictedBaseController { return jUnit; } - public static void setjUnit(boolean jUnit) { - PolicyController.jUnit = jUnit; + public static void setjUnit(boolean isJunit) { + PolicyController.jUnit = isJunit; } @Autowired @@ -183,9 +186,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 +238,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 +298,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 +310,20 @@ 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"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); + model.put("functionDefinitionDatas", + mapper.writeValueAsString(commonClassDao.getDataByColumn(FunctionDefinition.class, "shortname"))); + response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).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 +365,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) { @@ -377,9 +375,7 @@ public class PolicyController extends RestrictedBaseController { Map<String, Object> model = new HashMap<>(); ObjectMapper mapper = new ObjectMapper(); model.put("userRolesDatas", mapper.writeValueAsString(getRolesOfUser(userId))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); + response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString()); } catch (Exception e) { policyLogger.error("Exception Occured" + e); } @@ -402,8 +398,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,9 +433,8 @@ public class PolicyController extends RestrictedBaseController { savePolicyRoles(name, filteredRole, userId); } else { userRoles = getRoles(userId); - Pair<Set<String>, List<String>> pair = - org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles); - roles = pair.u; + Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles); + roles = pair.second; if (!roles.contains(filteredRole)) { savePolicyRoles(name, filteredRole, userId); } @@ -511,8 +505,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 +569,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) { @@ -604,11 +596,11 @@ public class PolicyController extends RestrictedBaseController { /** * Switch Version Policy Content. * - * @param pName which is used to find associated versions. + * @param thePolicyName which is used to find associated versions. * @return list of available versions based on policy name. */ - public JSONObject switchVersionPolicyContent(String pName) { - String policyName = pName; + public JSONObject switchVersionPolicyContent(String thePolicyName) { + String policyName = thePolicyName; String dbCheckName = policyName.replace("/", "."); if (dbCheckName.contains("Config_")) { dbCheckName = dbCheckName.replace(".Config_", ":Config_"); @@ -620,25 +612,23 @@ 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]); - List<Object> policyEntity = commonClassDao.getDataByQuery(query, params); List<String> av = new ArrayList<>(); - for (Object entity : policyEntity) { - PolicyEntity pEntity = (PolicyEntity) entity; - String removeExtension = pEntity.getPolicyName().replace(".xml", ""); + for (Object entity : commonClassDao.getDataByQuery(query, params)) { + PolicyEntity policyEntity = (PolicyEntity) entity; + String removeExtension = policyEntity.getPolicyName().replace(".xml", ""); String version = removeExtension.substring(removeExtension.lastIndexOf('.') + 1); - String userName = getUserId(pEntity, "@ModifiedBy:"); - av.add(version + " | " + pEntity.getModifiedDate() + " | " + userName); + String userName = getUserId(policyEntity, "@ModifiedBy:"); + av.add(version + " | " + policyEntity.getModifiedDate() + " | " + userName); } if (policyName.contains("/")) { policyName = policyName.replace("/", File.separator); } - PolicyVersion entity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, - "policyName", policyName); + PolicyVersion entity = + (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", policyName); JSONObject el = new JSONObject(); el.put("activeVersion", entity.getActiveVersion()); el.put("availableVersions", av); @@ -646,13 +636,20 @@ public class PolicyController extends RestrictedBaseController { return el; } + /** + * getUserId. + * + * @param data PolicyEntity + * @param value String + * @return String + */ public String getUserId(PolicyEntity data, String value) { String userId = ""; - String uValue = value; + String userValue = value; // Why? String description = getDescription(data); - if (description.contains(uValue)) { - userId = description.substring(description.indexOf(uValue) + uValue.length(), - description.lastIndexOf(uValue)); + if (description.contains(userValue)) { + userId = description.substring(description.indexOf(userValue) + userValue.length(), + description.lastIndexOf(userValue)); } UserInfo userInfo = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", userId); if (userInfo == null) { @@ -661,35 +658,43 @@ public class PolicyController extends RestrictedBaseController { return userInfo.getUserName(); } + /** + * getDescription. + * + * @param data PolicyEntity + * @return String + */ 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: " - + policy.getClass().getCanonicalName()); - return null; } + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Expecting a PolicySet/Policy/Rule object. Got: " + + policy.getClass().getCanonicalName()); + return null; } + /** + * getUserInfo. + * + * @param data PolicyEntity + * @param activePolicies list of active policies + * @return array of String + */ 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 +731,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; } @@ -940,11 +944,11 @@ public class PolicyController extends RestrictedBaseController { } public static String getCharacterencoding() { - return characterEncoding; + return PolicyUtils.CHARACTER_ENCODING; } public static String getContenttype() { - return contentType; + return PolicyUtils.APPLICATION_JSON; } public static String getFile() { @@ -969,17 +973,4 @@ public class PolicyController extends RestrictedBaseController { return fileSizeLimit; } - /** - * Function to convert date. - * - * @param dateTTL input date value. - * @return - */ - public String convertDate(String dateTTL) { - String formateDate = null; - if (dateTTL.contains("-")) { - formateDate = dateTTL.replace("-", "/"); - } - return formateDate; - } } 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..cf7e62b46 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,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2020 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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -38,6 +38,7 @@ import java.util.Set; import javax.script.SimpleBindings; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.apache.commons.lang3.StringUtils; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; @@ -52,7 +53,7 @@ import org.onap.policy.rest.adapter.PolicyExportAdapter; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.ActionBodyEntity; import org.onap.policy.rest.jpa.ConfigurationDataEntity; -import org.onap.policy.rest.jpa.DCAEuuid; +import org.onap.policy.rest.jpa.DcaeUuid; import org.onap.policy.rest.jpa.GroupPolicyScopeList; import org.onap.policy.rest.jpa.MicroServiceConfigName; import org.onap.policy.rest.jpa.MicroServiceLocation; @@ -61,10 +62,12 @@ import org.onap.policy.rest.jpa.PolicyEditorScopes; import org.onap.policy.rest.jpa.PolicyEntity; import org.onap.policy.rest.jpa.PolicyVersion; import org.onap.policy.rest.jpa.UserInfo; +import org.onap.policy.utils.PolicyUtils; import org.onap.policy.utils.UserUtils.Pair; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.onap.portalsdk.core.controller.RestrictedBaseController; import org.onap.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @@ -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() { @@ -113,14 +115,20 @@ public class PolicyExportAndImportController extends RestrictedBaseController { // Empty constructor } + @Autowired + private PolicyExportAndImportController(CommonClassDao commonClassDao) { + PolicyExportAndImportController.commonClassDao = commonClassDao; + } + /** * This is for downloading existing policy. - * + * * @param request HttpServletRequest * @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 +142,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 +159,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"; @@ -173,14 +179,14 @@ public class PolicyExportAndImportController extends RestrictedBaseController { workBook2.write(fos); fos.flush(); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); + response.setContentType(PolicyUtils.APPLICATION_JSON); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); PrintWriter out = response.getWriter(); String successMap = file.substring(file.lastIndexOf("webapps") + 8); String responseString = mapper.writeValueAsString(successMap); - JSONObject j = new JSONObject("{data: " + responseString + "}"); - out.write(j.toString()); + JSONObject json = new JSONObject("{data: " + responseString + "}"); + out.write(json.toString()); } catch (Exception e) { logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception Occured while Exporting Policies" + e); } @@ -233,8 +239,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,17 +253,15 @@ public class PolicyExportAndImportController extends RestrictedBaseController { return row; } - - /** * This is to upload a policy and save it to database. - * + * * @param file String * @param request HttpServletRequest * @return JSONObject * @throws IOException error out */ - public JSONObject importRepositoryFile(String file, HttpServletRequest request) throws IOException { + public String importRepositoryFile(String file, HttpServletRequest request) throws IOException { boolean configExists = false; boolean actionExists = false; String configName = null; @@ -269,14 +273,14 @@ public class PolicyExportAndImportController extends RestrictedBaseController { // Check if the Role and Scope Size are Null get the values from db. List<Object> userRoles = controller.getRoles(userId); Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles); - List<String> roles = pair.u; - Set<String> scopes = pair.t; + List<String> roles = pair.second; + Set<String> scopes = pair.first; try (FileInputStream excelFile = new FileInputStream(new File(file)); HSSFWorkbook workbook = new HSSFWorkbook(excelFile)) { Sheet datatypeSheet = workbook.getSheetAt(0); Iterator<Row> rowIterator = datatypeSheet.iterator(); - + String sendResult = null; while (rowIterator.hasNext()) { finalColumn = false; PolicyEntity policyEntity = new PolicyEntity(); @@ -291,6 +295,7 @@ public class PolicyExportAndImportController extends RestrictedBaseController { int bodySize = 0; int setBodySize = 0; boolean configurationBodySet = false; + boolean errorFlag = false; while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); if (policyName.equalsIgnoreCase(getCellHeaderName(cell))) { @@ -314,13 +319,18 @@ public class PolicyExportAndImportController extends RestrictedBaseController { configurationDataEntity = populateConfigurationDataEntity(policyEntity, configurationDataEntity, cell); actionBodyEntity = populateActionBodyObject(policyEntity, actionBodyEntity, cell); - JSONObject response = validatRequiredValue(policyEntity, body, finalColumn, configurationBodySet); - if (response != null) { - return response; + String response = null; + response = validatRequiredValue(policyEntity, body, finalColumn, configurationBodySet); + if (!StringUtils.isBlank(response)) { + sendResult = sendResult + "\n" + response; + errorFlag = true; + } + if (!StringUtils.isBlank(response) && !rowIterator.hasNext()) { + return sendResult; } savePolicyEntiies(finalColumn, configurationBodySet, configurationDataEntity, policyEntity, controller, roles, userInfo, scopes, configName, userId, configExists, actionExists, - actionBodyEntity, body); + actionBodyEntity, body, errorFlag); } } @@ -331,9 +341,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 +352,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(); @@ -360,49 +369,46 @@ public class PolicyExportAndImportController extends RestrictedBaseController { /** * This is to validate all matching required fields. - * + * * @param policyName String * @param jsonString String * @return String */ public String validatMatchRequiredFields(String policyName, String jsonString) { - + String errorMsg = ""; try { JSONObject jsonObject = new JSONObject(jsonString); - String configName = jsonObject.getString("configName"); - String uuid = jsonObject.getString("uuid"); - String erorMsg = validConfigName(configName); - if (erorMsg != null) { - return erorMsg; + String confErorMsg = validConfigName(jsonObject.getString("configName")); + if (!confErorMsg.isEmpty()) { + errorMsg = errorMsg + "\n POLICY :" + policyName + " at " + confErorMsg; } - erorMsg = validUuid(uuid); - if (erorMsg != null) { - return erorMsg; + String uuidErorMsg = validUuid(jsonObject.getString("uuid")); + if (!uuidErorMsg.isEmpty()) { + errorMsg = errorMsg + "\n POLICY :" + policyName + " at " + uuidErorMsg; } - String location = jsonObject.getString("location"); - erorMsg = validLocation(location); - if (erorMsg != null) { - return erorMsg; + String locErorMsg = validLocation(jsonObject.getString("location")); + if (!locErorMsg.isEmpty()) { + errorMsg = errorMsg + "\n POLICY :" + policyName + " at " + locErorMsg; } - String policyScope = jsonObject.getString("policyScope"); - erorMsg = validPolicyScope(policyScope); - if (erorMsg != null) { - return erorMsg; + String pScopeErorMsg = validPolicyScope(jsonObject.getString("policyScope")); + if (!pScopeErorMsg.isEmpty()) { + errorMsg = errorMsg + "\n POLICY :" + policyName + " at " + pScopeErorMsg; } String msVersion = jsonObject.getString("version"); String msService = jsonObject.getString("service"); if (!isAttributeObjectFound(msService, msVersion)) { - return POLICY + policyName + " MS Service: " + msService + " and MS Version: " + msVersion + NOTVALID; + errorMsg = errorMsg + "\n POLICY :" + policyName + " at MS Service: " + msService + " and MS Version: " + + msVersion + NOTVALID; } } catch (Exception e) { logger.error("Exception Occured While validating required fields", e); } - return null; + return errorMsg; } - private JSONObject validatRequiredValue(PolicyEntity policyEntity, StringBuilder body, boolean finalColumn, + private String validatRequiredValue(PolicyEntity policyEntity, StringBuilder body, boolean finalColumn, boolean configurationBodySet) { if (finalColumn && configurationBodySet && (policyEntity.getPolicyName().contains(CONFIG_MS))) { String errorMsg = validatMatchRequiredFields(policyEntity.getPolicyName(), body.toString()); @@ -410,7 +416,7 @@ public class PolicyExportAndImportController extends RestrictedBaseController { logger.error("errorMsg => " + errorMsg); JSONObject response = new JSONObject(); response.append("error", errorMsg); - return response; + return errorMsg; } } return null; @@ -433,7 +439,7 @@ public class PolicyExportAndImportController extends RestrictedBaseController { private String validUuid(String uuid) { String message = null; if (uuid != null) { - List<String> uuids = commonClassDao.getDataByColumn(DCAEuuid.class, "name"); + List<String> uuids = commonClassDao.getDataByColumn(DcaeUuid.class, "name"); if (uuids != null && !(uuids.stream().filter(o -> o.equals(uuid)).findFirst().isPresent())) { message = POLICY + policyName + " uuid: " + uuid + NOTVALID; } @@ -565,6 +571,7 @@ public class PolicyExportAndImportController extends RestrictedBaseController { return false; } + @SuppressWarnings("rawtypes") private boolean isContinue(List<String> roles, String scope, UserInfo userInfo, Set scopes) { if (roles.contains(admin) || roles.contains(editor)) { if (scopes.isEmpty()) { @@ -605,14 +612,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 +644,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 +670,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 +711,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 +740,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; @@ -751,9 +758,9 @@ public class PolicyExportAndImportController extends RestrictedBaseController { private void savePolicyEntiies(boolean finalColumn, boolean configurationBodySet, ConfigurationDataEntity configurationDataEntity, PolicyEntity policyEntity, PolicyController controller, List<String> roles, UserInfo userInfo, Set<String> scopes, String configName, String userId, - boolean configExists, boolean actionExists, ActionBodyEntity actionBodyEntity, StringBuilder body) { + boolean configExists, boolean actionExists, ActionBodyEntity actionBodyEntity, StringBuilder body, boolean errorFlagSent) { - if (finalColumn && configurationBodySet) { + if (finalColumn && configurationBodySet && !errorFlagSent) { configurationDataEntity.setConfigBody(body.toString()); String scope = policyEntity.getScope().replace(".", File.separator); String query = "FROM PolicyEntity where policyName = :policyName and scope = :policyScope"; @@ -771,7 +778,7 @@ public class PolicyExportAndImportController extends RestrictedBaseController { saveVersion(policyEntity, scope, userId); // // Notify Other paps regarding Export Policy. PolicyRestController restController = new PolicyRestController(); - restController.notifyOtherPAPSToUpdateConfigurations("exportPolicy", configName, null); + restController.notifyOtherPapsToUpdateConfigurations("exportPolicy", configName, null); } } } 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..ebd24dce3 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,14 +2,14 @@ * ============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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,13 +20,16 @@ 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; import java.util.List; import javax.script.SimpleBindings; @@ -46,87 +49,87 @@ 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; + + /** + * watchPolicy. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + * @return ModelAndView + * @throws IOException IOException + */ + @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 { + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + // + // + // + 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.setContentType(PolicyUtils.APPLICATION_JSON); - 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; - } + response.getWriter().write(new JSONObject("{watchData: " + + mapper.writeValueAsString(responseValue) + "}").toString()); + } catch (Exception e) { + logger.error("Error druing watchPolicy function " + e); + response.getWriter().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..c1c784083 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 @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,7 +20,12 @@ package org.onap.policy.controller; -import java.io.PrintWriter; +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.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -28,7 +33,8 @@ import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - +import lombok.Getter; +import lombok.Setter; import org.json.JSONObject; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; @@ -36,6 +42,7 @@ import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.PolicyEditorScopes; import org.onap.policy.rest.jpa.PolicyRoles; import org.onap.policy.rest.jpa.UserInfo; +import org.onap.policy.utils.PolicyUtils; import org.onap.portalsdk.core.controller.RestrictedBaseController; import org.onap.portalsdk.core.web.support.JsonMessage; import org.onap.portalsdk.core.web.support.UserUtils; @@ -45,12 +52,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,19 +70,19 @@ 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<>(); ObjectMapper mapper = new ObjectMapper(); model.put("rolesDatas", mapper.writeValueAsString(commonClassDao.getUserRoles())); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); + response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString()); } catch (Exception e) { LOGGER.error("Exception Occured" + e); } @@ -90,12 +91,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(); @@ -112,11 +114,11 @@ public class PolicyRolesController extends RestrictedBaseController { } } LOGGER.info( - "****************************************Logging UserID for Roles Function********************************************************"); + "*************************Logging UserID for Roles Function***********************************"); LOGGER.info("UserId: " + userId + "Updating the Scope for following user" + adapter.getLoginId() + "ScopeNames" + adapter.getScope()); LOGGER.info( - "*********************************************************************************************************************************"); + "*********************************************************************************************"); UserInfo userInfo = new UserInfo(); userInfo.setUserLoginId(adapter.getLoginId().getUserName()); userInfo.setUserName(adapter.getLoginId().getUserName()); @@ -125,11 +127,11 @@ public class PolicyRolesController extends RestrictedBaseController { if (adapter.getId() == 0 && "mechid".equals(adapter.getRole())) { // Save new mechid scopes entity data. LOGGER.info( - "****************************************Logging UserID for New Mechid Function***************************************************"); + "*********************Logging UserID for New Mechid Function********************************"); LOGGER.info("UserId:" + userId + "Adding new mechid-scopes for following user" + adapter.getLoginId() + "ScopeNames " + adapter.getScope()); LOGGER.info( - "*********************************************************************************************************************************"); + "*******************************************************************************************"); // First add the mechid to userinfo commonClassDao.save(userInfo); checkNew = true; @@ -146,15 +148,11 @@ public class PolicyRolesController extends RestrictedBaseController { } else { commonClassDao.update(roles); } - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(commonClassDao.getUserRoles()); - JSONObject j = new JSONObject("{rolesDatas: " + responseString + "}"); - - out.write(j.toString()); + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + response.setContentType(PolicyUtils.APPLICATION_JSON); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + response.getWriter().write(new JSONObject("{rolesDatas: " + + mapper.writeValueAsString(commonClassDao.getUserRoles()) + "}").toString()); } catch (Exception e) { LOGGER.error("Exception Occured" + e); } @@ -164,11 +162,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<>(); @@ -177,51 +177,18 @@ public class PolicyRolesController extends RestrictedBaseController { mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); List<String> scopesData = commonClassDao.getDataByColumn(PolicyEditorScopes.class, "scopeName"); model.put("scopeDatas", mapper.writeValueAsString(scopesData)); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); + response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString()); } catch (Exception e) { LOGGER.error("Exception Occured" + e); } } } +@Setter +@Getter class ReadScopes { private int id; private UserInfo loginId; private String role; private List<String> scope; - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public UserInfo getLoginId() { - return loginId; - } - - public void setLoginId(UserInfo loginId) { - this.loginId = loginId; - } - - public String getRole() { - return role; - } - - public void setRole(String role) { - this.role = role; - } - - public List<String> getScope() { - return scope; - } - - public void setScope(List<String> scope) { - this.scope = scope; - } - } 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..05264c8b6 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,14 +2,14 @@ * ============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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,9 +20,9 @@ package org.onap.policy.controller; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; -import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -40,40 +40,42 @@ 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); + + /** + * validatePolicy. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + * @return ModelAndView + * @throws IOException IOException + */ + @RequestMapping( + value = {"/policyController/validate_policy.htm"}, + method = {org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView validatePolicy(HttpServletRequest request, HttpServletResponse response) throws IOException { + try { - @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(); + PolicyValidation validation = new PolicyValidation(); + PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper(); + StringBuilder responseString; + ObjectMapper mapper = new ObjectMapper(); - 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()); + PolicyRestAdapter policyData = wrapper.populateRequestParameters(request); + responseString = validation.validatePolicy(policyData); - 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 + response.getWriter().write(new JSONObject( + new JsonMessage(mapper.writeValueAsString(responseString.toString()))).toString()); + } catch (Exception e) { + LOGGER.error("Exception Occured During Policy Validation" + e); + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + response.getWriter().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..8883475b8 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; - - +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..a4b2c88d2 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,14 +2,14 @@ * ============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. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -48,368 +48,358 @@ 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 { + final Criteria cr = session.createCriteria(PolicyRoles.class); + final 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) { + // why is there no code here? + } - @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) { + // why is there no code here? + } + @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..46aed213f 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.rest.jpa.SystemLogDb; +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..6c4fd7e91 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; @@ -112,6 +113,9 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier return itemId instanceof OnapPDPGroup; } + /** + * refreshGroups. + */ public synchronized void refreshGroups() { synchronized (this.groups) { this.groups.clear(); @@ -133,6 +137,11 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier return Collections.unmodifiableList(this.groups); } + /** + * makeDefault. + * + * @param group OnapPDPGroup + */ public void makeDefault(OnapPDPGroup group) { try { this.papEngine.setDefaultGroup(group); @@ -143,6 +152,13 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier return; } + /** + * removeGroup. + * + * @param group OnapPDPGroup + * @param newGroup OnapPDPGroup + * @throws PAPException PAPException + */ public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup) throws PAPException { if (LOGGER.isTraceEnabled()) { LOGGER.trace("removeGroup: " + group + " new group for PDPs: " + newGroup); @@ -158,6 +174,13 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier } } + /** + * removePDP. + * + * @param pdp OnapPDP + * @param group OnapPDPGroup + * @throws PAPException PAPException + */ public void removePDP(OnapPDP pdp, OnapPDPGroup group) throws PAPException { if (LOGGER.isTraceEnabled()) { LOGGER.trace("removePDP: " + pdp + " from group: " + group); @@ -170,6 +193,11 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier } } + /** + * updatePDP. + * + * @param pdp OnapPDP + */ public void updatePDP(OnapPDP pdp) { try { papEngine.updatePDP(pdp); @@ -178,6 +206,11 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier } } + /** + * updateGroup. + * + * @param group OnapPDPGroup + */ public void updateGroup(OnapPDPGroup group) { try { papEngine.updateGroup(group); @@ -216,6 +249,17 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier } @Override + public List<?> getItemIds(int startIndex, int numberOfItems) { + synchronized (this.groups) { + int endIndex = startIndex + numberOfItems; + if (endIndex > this.groups.size()) { + endIndex = this.groups.size() - 1; + } + return this.groups.subList(startIndex, endIndex); + } + } + + @Override public Class<?> getType(Object propertyId) { if (propertyId.equals(PROPERTY_ID)) { return String.class; @@ -268,6 +312,13 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier throw new UnsupportedOperationException("PDP Container cannot add a given item."); } + /** + * addNewGroup. + * + * @param name String + * @param description String + * @throws PAPException PAPException + */ public void addNewGroup(String name, String description) throws PAPException { if (LOGGER.isTraceEnabled()) { LOGGER.trace("addNewGroup " + name + " " + description); @@ -275,6 +326,16 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier this.papEngine.newGroup(name, description); } + /** + * addNewPDP. + * + * @param id String + * @param group OnapPDPGroup + * @param name String + * @param description String + * @param jmxport int + * @throws PAPException PAPException + */ public void addNewPDP(String id, OnapPDPGroup group, String name, String description, int jmxport) throws PAPException { if (LOGGER.isTraceEnabled()) { @@ -283,6 +344,12 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier this.papEngine.newPDP(id, group, name, description, jmxport); } + /** + * movePDP. + * + * @param pdp OnapPDP + * @param group OnapPDPGroup + */ public void movePDP(OnapPDP pdp, OnapPDPGroup group) { try { this.papEngine.movePDP(pdp, group); @@ -427,17 +494,6 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier } @Override - public List<?> getItemIds(int startIndex, int numberOfItems) { - synchronized (this.groups) { - int endIndex = startIndex + numberOfItems; - if (endIndex > this.groups.size()) { - endIndex = this.groups.size() - 1; - } - return this.groups.subList(startIndex, endIndex); - } - } - - @Override public Object addItemAt(int index) { throw new UnsupportedOperationException("Cannot addItemAt"); } 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..f9f93c0ff 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 @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.utils; import java.util.ArrayList; @@ -35,18 +36,18 @@ public final class UserUtils { } public static class Pair<T, U> { - public final T t; - public final U u; + public final T first; + public final U second; - public Pair(T t, U u) { - this.t = t; - this.u = u; + public Pair(T first, U second) { + this.first = first; + this.second = second; } } /** * Check Role and its Scopes. - * + * * @param userRoles list of UserRoles. * @return return role and scope from UserRole Object. */ @@ -75,7 +76,7 @@ public final class UserUtils { /** * Get Role by Scope based on UserRole Object. - * + * * @param userRoles list of UserRoles. * @return return the map<scope, role>. */ @@ -94,8 +95,8 @@ 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>. */ @@ -115,7 +116,7 @@ public final class UserUtils { /** * Trim Scope Value. - * + * * @param scope string scope name. * @return trim scope. */ |