From 5a5842e77e4e0f0b6207192b374d99753db26c7e Mon Sep 17 00:00:00 2001 From: liamfallon Date: Thu, 31 Oct 2019 16:39:37 +0000 Subject: ONAP-REST DAO Sonar/Checkstyle clean and knock-on Clean up the ONAP-REST DAO package and also deal with knock-on chages in other packages. Issue-ID: POLICY-2131 Change-Id: I381d514d37ffbddb7a91b8f8a018c7354fc437b3 Signed-off-by: liamfallon --- .../pap/xacml/rest/ConsoleAndApiService.java | 125 ++- .../policy/pap/xacml/rest/XACMLPapServlet.java | 25 +- .../components/CreateNewMicroServiceModel.java | 3 +- .../components/HandleIncomingNotifications.java | 166 ++-- .../pap/xacml/rest/components/NotifyOtherPaps.java | 11 +- .../pap/xacml/rest/components/PolicyDBDao.java | 820 ----------------- .../rest/components/PolicyDBDaoTransaction.java | 197 ---- .../pap/xacml/rest/components/PolicyDbDao.java | 993 +++++++++++++++++++++ .../rest/components/PolicyDbDaoTransaction.java | 194 ++++ .../components/PolicyDbDaoTransactionInstance.java | 422 ++++----- .../pap/xacml/rest/handler/DeleteHandler.java | 5 +- .../rest/policycontroller/PolicyCreation.java | 209 +++-- 12 files changed, 1709 insertions(+), 1461 deletions(-) delete mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java delete mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTransaction.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDao.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransaction.java (limited to 'ONAP-PAP-REST/src/main/java') diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiService.java index 6e7977419..16340e5fe 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiService.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiService.java @@ -3,6 +3,7 @@ * ONAP-PAP-REST * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,8 +44,8 @@ import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.pap.xacml.rest.components.PolicyDBDao; -import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTransaction; +import org.onap.policy.pap.xacml.rest.components.PolicyDbDao; +import org.onap.policy.pap.xacml.rest.components.PolicyDbDaoTransaction; import org.onap.policy.pap.xacml.rest.handler.PushPolicyHandler; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.onap.policy.xacml.api.pap.OnapPDP; @@ -56,6 +57,15 @@ import org.onap.policy.xacml.std.pap.StdPDPPolicy; public class ConsoleAndApiService { + private static final String SPACE_UNIMPLEMENTED = " UNIMPLEMENTED"; + private static final String XACMLPAPSERVLET_DO_AC_PUT_COMMIT_TRANS = "XACMLPapServlet doACPut commitTransaction"; + private static final String UNIMPLEMENTED = "UNIMPLEMENTED"; + private static final String APPLICATION_JSON = "application/json"; + private static final String CONTENT_TYPE = "content-type"; + private static final String TO_GROUP = ",to group="; + private static final String PDP_ID = "pdpId"; + private static final String XACML_PAP_SERVLET_DO_AC_PUT = "XACMLPapServlet.doACPut"; + private static final String UNKNOWN_GROUP_ID = "Unknown groupId '"; private static final Logger LOGGER = FlexLogger.getLogger(ConsoleAndApiService.class); private static final Logger auditLogger = FlexLogger.getLogger("auditLogger"); private static final String ADD_GROUP_ERROR = "addGroupError"; @@ -83,7 +93,7 @@ public class ConsoleAndApiService { */ public void doAcPost(HttpServletRequest request, HttpServletResponse response, String groupId, OnapLoggingContext loggingContext, PAPPolicyEngine papEngine) throws IOException { - PolicyDBDaoTransaction doAcPostTransaction = null; + PolicyDbDaoTransaction doAcPostTransaction = null; try { String groupName = request.getParameter("groupName"); String groupDescription = request.getParameter("groupDescription"); @@ -101,9 +111,9 @@ public class ConsoleAndApiService { } catch (UnsupportedEncodingException e) { LOGGER.error(e); } - PolicyDBDaoTransaction newGroupTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); + PolicyDbDaoTransaction newGroupTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); try { - newGroupTransaction.createGroup(PolicyDBDao.createNewPDPGroupId(unescapedName), unescapedName, + newGroupTransaction.createGroup(PolicyDbDao.createNewPdpGroupId(unescapedName), unescapedName, unescapedDescription, PAPSERVLETDOACPOST); papEngine.newGroup(unescapedName, unescapedDescription); loggingContext.metricStarted(); @@ -137,7 +147,7 @@ public class ConsoleAndApiService { LOGGER.error(e); } if (group == null) { - String message = "Unknown groupId '" + groupId + "'"; + String message = UNKNOWN_GROUP_ID + groupId + "'"; // for fixing Header Manipulation of Fortify issue if (!message.matches(REGEX)) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); @@ -171,7 +181,7 @@ public class ConsoleAndApiService { StdPDPGroup updatedGroup = null; StdPDPPolicy policyForSafetyCheck = new StdPDPPolicy(); for (String policyId : policyIdList) { - PolicyDBDaoTransaction addPolicyToGroupTransaction = + PolicyDbDaoTransaction addPolicyToGroupTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); try { // Copying the policy to the file system and updating groups @@ -227,13 +237,13 @@ public class ConsoleAndApiService { */ // Get new transaction to perform updateGroup() - PolicyDBDaoTransaction acPutTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); + PolicyDbDaoTransaction acPutTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); try { // Assume that this is an update of an existing PDP // Group loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup"); try { - acPutTransaction.updateGroup(updatedGroup, "XACMLPapServlet.doACPut", userId); + acPutTransaction.updateGroup(updatedGroup, XACML_PAP_SERVLET_DO_AC_PUT, userId); } catch (Exception e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, XACMLPAPSERVLET, " Error occurred when notifying PAPs of a group change: " + e); @@ -279,8 +289,6 @@ public class ConsoleAndApiService { loggingContext.transactionEnded(); auditLogger.info(SUCCESS); LOGGER.info(TRANSENDED); - - return; } else if (request.getParameter("default") != null) { // Args: group= default=true <= make default // change the current default group to be the one identified in @@ -292,7 +300,7 @@ public class ConsoleAndApiService { // It should never be the case that multiple groups are // currently marked as the default, but protect against that // anyway. - PolicyDBDaoTransaction setDefaultGroupTransaction = + PolicyDbDaoTransaction setDefaultGroupTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); try { setDefaultGroupTransaction.changeDefaultGroup(group, PAPSERVLETDOACPOST); @@ -316,20 +324,19 @@ public class ConsoleAndApiService { } auditLogger.info(SUCCESS); LOGGER.info(TRANSENDED); - return; - } else if (request.getParameter("pdpId") != null) { + } else if (request.getParameter(PDP_ID) != null) { doAcPostTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); // Args: group= pdpId= <= move PDP to group loggingContext.setServiceName("AC:PAP.movePDP"); - String pdpId = request.getParameter("pdpId"); + String pdpId = request.getParameter(PDP_ID); OnapPDP pdp = papEngine.getPDP(pdpId); - OnapPDPGroup originalGroup = papEngine.getPDPGroup(pdp); + final OnapPDPGroup originalGroup = papEngine.getPDPGroup(pdp); try { doAcPostTransaction.movePdp(pdp, group, PAPSERVLETDOACPOST); } catch (Exception e) { doAcPostTransaction.rollbackTransaction(); PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, XACMLPAPSERVLET, - " Error while moving pdp in the database: " + "pdp=" + pdp.getId() + ",to group=" + " Error while moving pdp in the database: " + "pdp=" + pdp.getId() + TO_GROUP + group.getId()); throw new PAPException(e.getMessage()); } @@ -351,14 +358,12 @@ public class ConsoleAndApiService { loggingContext.transactionEnded(); auditLogger.info(SUCCESS); PolicyLogger.audit(TRANSENDED); - return; } } catch (PAPException e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, XACMLPAPSERVLET, " AC POST exception"); loggingContext.transactionEnded(); PolicyLogger.audit(TRANSACTIONFAILED); setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); - return; } } @@ -376,7 +381,7 @@ public class ConsoleAndApiService { OnapLoggingContext loggingContext, PAPPolicyEngine papEngine) throws IOException { try { String parameterDefault = request.getParameter("default"); - String pdpId = request.getParameter("pdpId"); + String pdpId = request.getParameter(PDP_ID); String pdpGroup = request.getParameter("getPDPGroup"); if ("".equals(groupId)) { // request IS from AC but does not identify a group by name @@ -391,7 +396,7 @@ public class ConsoleAndApiService { LOGGER.debug("GET Default group req from '" + request.getRequestURL() + "'"); } response.setStatus(HttpServletResponse.SC_OK); - response.setHeader("content-type", "application/json"); + response.setHeader(CONTENT_TYPE, APPLICATION_JSON); try { response.getOutputStream().close(); } catch (IOException e) { @@ -420,7 +425,7 @@ public class ConsoleAndApiService { LOGGER.debug("GET pdp '" + pdpId + "' req from '" + request.getRequestURL() + "'"); } response.setStatus(HttpServletResponse.SC_OK); - response.setHeader("content-type", "application/json"); + response.setHeader(CONTENT_TYPE, APPLICATION_JSON); try { response.getOutputStream().close(); } catch (IOException e) { @@ -447,7 +452,7 @@ public class ConsoleAndApiService { LOGGER.debug("GET PDP '" + pdpId + "' Group req from '" + request.getRequestURL() + "'"); } response.setStatus(HttpServletResponse.SC_OK); - response.setHeader("content-type", "application/json"); + response.setHeader(CONTENT_TYPE, APPLICATION_JSON); try { response.getOutputStream().close(); } catch (IOException e) { @@ -478,7 +483,7 @@ public class ConsoleAndApiService { LOGGER.debug("GET All groups req"); } response.setStatus(HttpServletResponse.SC_OK); - response.setHeader("content-type", "application/json"); + response.setHeader(CONTENT_TYPE, APPLICATION_JSON); try { response.getOutputStream().close(); } catch (IOException e) { @@ -499,7 +504,7 @@ public class ConsoleAndApiService { LOGGER.error(e); } if (group == null) { - String message = "Unknown groupId '" + groupId + "'"; + String message = UNKNOWN_GROUP_ID + groupId + "'"; // for fixing Header Manipulation of Fortify issue if (!message.matches(REGEX)) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); @@ -532,7 +537,7 @@ public class ConsoleAndApiService { LOGGER.debug("GET group '" + group.getId() + "' req from '" + request.getRequestURL() + "'"); } response.setStatus(HttpServletResponse.SC_OK); - response.setHeader("content-type", "application/json"); + response.setHeader(CONTENT_TYPE, APPLICATION_JSON); try { response.getOutputStream().close(); } catch (IOException e) { @@ -554,13 +559,12 @@ public class ConsoleAndApiService { PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " UNIMPLEMENTED "); loggingContext.transactionEnded(); PolicyLogger.audit(TRANSACTIONFAILED); - setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); + setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, UNIMPLEMENTED); } catch (PAPException e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, XACMLPAPSERVLET, " AC Get exception"); loggingContext.transactionEnded(); PolicyLogger.audit(TRANSACTIONFAILED); setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); - return; } } @@ -576,7 +580,7 @@ public class ConsoleAndApiService { */ public void doAcPut(HttpServletRequest request, HttpServletResponse response, String groupId, OnapLoggingContext loggingContext, PAPPolicyEngine papEngine) throws IOException { - PolicyDBDaoTransaction acPutTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); + PolicyDbDaoTransaction acPutTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); try { String userId = request.getParameter("userId"); // for PUT operations the group may or may not need to exist before @@ -587,7 +591,7 @@ public class ConsoleAndApiService { // for remaining operations the group must exist before the // operation can be done if (group == null) { - String message = "Unknown groupId '" + groupId + "'"; + String message = UNKNOWN_GROUP_ID + groupId + "'"; PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit(TRANSACTIONFAILED); @@ -608,11 +612,10 @@ public class ConsoleAndApiService { auditLogger.info(SUCCESS); PolicyLogger.audit(TRANSENDED); acPutTransaction.rollbackTransaction(); - return; - } else if (request.getParameter("pdpId") != null) { + } else if (request.getParameter(PDP_ID) != null) { // ARGS: group= pdpId= <= create a new PDP // or Update an Existing one - String pdpId = request.getParameter("pdpId"); + String pdpId = request.getParameter(PDP_ID); if (papEngine.getPDP(pdpId) == null) { loggingContext.setServiceName("AC:PAP.createPDP"); } else { @@ -661,18 +664,18 @@ public class ConsoleAndApiService { // this is a request to create a new PDP object try { acPutTransaction.addPdpToGroup(pdp.getId(), group.getId(), pdp.getName(), - pdp.getDescription(), pdp.getJmxPort(), "XACMLPapServlet.doACPut"); + pdp.getDescription(), pdp.getJmxPort(), XACML_PAP_SERVLET_DO_AC_PUT); papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription(), pdp.getJmxPort()); } catch (Exception e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, XACMLPAPSERVLET, " Error while adding pdp to group in the database: " + "pdp=" + (pdp.getId()) - + ",to group=" + group.getId()); + + TO_GROUP + group.getId()); throw new PAPException(e.getMessage()); } } else { // this is a request to update the pdp try { - acPutTransaction.updatePdp(pdp, "XACMLPapServlet.doACPut"); + acPutTransaction.updatePdp(pdp, XACML_PAP_SERVLET_DO_AC_PUT); papEngine.updatePDP(pdp); } catch (Exception e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, XACMLPAPSERVLET, @@ -691,15 +694,14 @@ public class ConsoleAndApiService { loggingContext.metricStarted(); acPutTransaction.commitTransaction(); loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction"); + PolicyLogger.metrics(XACMLPAPSERVLET_DO_AC_PUT_COMMIT_TRANS); loggingContext.transactionEnded(); auditLogger.info(SUCCESS); PolicyLogger.audit(TRANSENDED); - return; } else { try { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, XACMLPAPSERVLET, - " Error while adding pdp to group in the database: " + "pdp=null" + ",to group=" + " Error while adding pdp to group in the database: " + "pdp=null" + TO_GROUP + group.getId()); throw new PAPException("PDP is null"); } catch (Exception e) { @@ -711,12 +713,11 @@ public class ConsoleAndApiService { // <= add a PIP to pip config, or replace it if it already // exists (lenient operation) loggingContext.setServiceName("AC:PAP.putPIP"); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED"); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + UNIMPLEMENTED); loggingContext.transactionEnded(); PolicyLogger.audit(TRANSACTIONFAILED); - setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); + setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, UNIMPLEMENTED); acPutTransaction.rollbackTransaction(); - return; } else { // Assume that this is an update of an existing PDP Group // ARGS: group= <= Update an Existing Group @@ -742,7 +743,7 @@ public class ConsoleAndApiService { } catch (Exception e) { LOGGER.error(e); } - if (objectFromJson == null || !(objectFromJson instanceof StdPDPGroup) + if (!(objectFromJson instanceof StdPDPGroup) || !((StdPDPGroup) objectFromJson).getId().equals(group.getId())) { PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + group.getId() + " objectFromJSON=" + objectFromJson); @@ -763,7 +764,7 @@ public class ConsoleAndApiService { if ("delete".equals(((StdPDPGroup) objectFromJson).getOperation())) { acPutTransaction.updateGroup((StdPDPGroup) objectFromJson, "XACMLPapServlet.doDelete", userId); } else { - acPutTransaction.updateGroup((StdPDPGroup) objectFromJson, "XACMLPapServlet.doACPut", userId); + acPutTransaction.updateGroup((StdPDPGroup) objectFromJson, XACML_PAP_SERVLET_DO_AC_PUT, userId); } } catch (Exception e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database: " @@ -789,13 +790,12 @@ public class ConsoleAndApiService { loggingContext.metricStarted(); acPutTransaction.commitTransaction(); loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction"); + PolicyLogger.metrics(XACMLPAPSERVLET_DO_AC_PUT_COMMIT_TRANS); // Group changed, which might include changing the policies getPapInstance().groupChanged(group, loggingContext); loggingContext.transactionEnded(); auditLogger.info(SUCCESS); PolicyLogger.audit(TRANSENDED); - return; } } catch (PAPException e) { LOGGER.debug(e); @@ -804,7 +804,6 @@ public class ConsoleAndApiService { loggingContext.transactionEnded(); PolicyLogger.audit(TRANSACTIONFAILED); setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); - return; } } @@ -820,18 +819,18 @@ public class ConsoleAndApiService { */ public void doAcDelete(HttpServletRequest request, HttpServletResponse response, String groupId, OnapLoggingContext loggingContext, PAPPolicyEngine papEngine) throws IOException { - PolicyDBDaoTransaction removePdpOrGroupTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); + PolicyDbDaoTransaction removePdpOrGroupTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); try { // for all DELETE operations the group must exist before the // operation can be done loggingContext.setServiceName("AC:PAP.delete"); OnapPDPGroup group = papEngine.getGroup(groupId); if (group == null) { - String message = "Unknown groupId '" + groupId + "'"; + String message = UNKNOWN_GROUP_ID + groupId + "'"; PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit(TRANSACTIONFAILED); - setResponseError(response, HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId + "'"); + setResponseError(response, HttpServletResponse.SC_NOT_FOUND, UNKNOWN_GROUP_ID + groupId + "'"); removePdpOrGroupTransaction.rollbackTransaction(); return; } @@ -841,15 +840,14 @@ public class ConsoleAndApiService { // group= policy= [delete=] <= // delete policy file from group loggingContext.setServiceName("AC:PAP.deletePolicy"); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED"); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + SPACE_UNIMPLEMENTED); loggingContext.transactionEnded(); PolicyLogger.audit(TRANSACTIONFAILED); - setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); + setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, UNIMPLEMENTED); removePdpOrGroupTransaction.rollbackTransaction(); - return; - } else if (request.getParameter("pdpId") != null) { + } else if (request.getParameter(PDP_ID) != null) { // ARGS: group= pdpId= <= delete PDP - String pdpId = request.getParameter("pdpId"); + String pdpId = request.getParameter(PDP_ID); OnapPDP pdp = papEngine.getPDP(pdpId); removePdpFromGroup(removePdpOrGroupTransaction, pdp, papEngine); // adjust the status of the group, which may have changed when @@ -862,21 +860,19 @@ public class ConsoleAndApiService { loggingContext.metricStarted(); removePdpOrGroupTransaction.commitTransaction(); loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction"); + PolicyLogger.metrics(XACMLPAPSERVLET_DO_AC_PUT_COMMIT_TRANS); loggingContext.transactionEnded(); auditLogger.info(SUCCESS); PolicyLogger.audit(TRANSENDED); - return; } else if (request.getParameter("pipId") != null) { // group= pipId= <= delete PIP config for // given engine loggingContext.setServiceName("AC:PAP.deletePIPConfig"); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED"); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + SPACE_UNIMPLEMENTED); loggingContext.transactionEnded(); PolicyLogger.audit(TRANSACTIONFAILED); - setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); + setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, UNIMPLEMENTED); removePdpOrGroupTransaction.rollbackTransaction(); - return; } else { // ARGS: group= movePDPsToGroupId= // <= delete a group and move all its PDPs to the given group @@ -904,11 +900,10 @@ public class ConsoleAndApiService { loggingContext.metricStarted(); removePdpOrGroupTransaction.commitTransaction(); loggingContext.metricEnded(); - PolicyLogger.metrics("XACMLPapServlet doACPut commitTransaction"); + PolicyLogger.metrics(XACMLPAPSERVLET_DO_AC_PUT_COMMIT_TRANS); loggingContext.transactionEnded(); auditLogger.info(SUCCESS); PolicyLogger.audit(TRANSENDED); - return; } } catch (PAPException e) { removePdpOrGroupTransaction.rollbackTransaction(); @@ -916,11 +911,10 @@ public class ConsoleAndApiService { loggingContext.transactionEnded(); PolicyLogger.audit(TRANSACTIONFAILED); setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); - return; } } - private void deleteGroup(PolicyDBDaoTransaction removePdpOrGroupTransaction, OnapPDPGroup group, + private void deleteGroup(PolicyDbDaoTransaction removePdpOrGroupTransaction, OnapPDPGroup group, OnapPDPGroup moveToGroup, PAPPolicyEngine papEngine) throws PAPException { try { removePdpOrGroupTransaction.deleteGroup(group, moveToGroup, "XACMLPapServlet.doACDelete"); @@ -932,7 +926,7 @@ public class ConsoleAndApiService { } } - private void removePdpFromGroup(PolicyDBDaoTransaction removePdpOrGroupTransaction, OnapPDP pdp, + private void removePdpFromGroup(PolicyDbDaoTransaction removePdpOrGroupTransaction, OnapPDP pdp, PAPPolicyEngine papEngine) throws PAPException { try { removePdpOrGroupTransaction.removePdpFromGroup(pdp.getId(), "XACMLPapServlet.doACDelete"); @@ -962,6 +956,5 @@ public class ConsoleAndApiService { } catch (IOException e) { LOGGER.error("Error setting Error response Header ", e); } - return; } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java index 32b1eb770..a74dd6bbc 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java @@ -3,6 +3,7 @@ * ONAP-PAP-REST * ================================================================================ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,15 +70,15 @@ import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.pap.xacml.rest.components.HandleIncomingNotifications; -import org.onap.policy.pap.xacml.rest.components.PolicyDBDao; -import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTransaction; +import org.onap.policy.pap.xacml.rest.components.PolicyDbDao; +import org.onap.policy.pap.xacml.rest.components.PolicyDbDaoTransaction; import org.onap.policy.pap.xacml.rest.handler.APIRequestHandler; import org.onap.policy.pap.xacml.rest.handler.PushPolicyHandler; import org.onap.policy.pap.xacml.rest.handler.SavePolicyHandler; import org.onap.policy.pap.xacml.restAuth.CheckPDP; import org.onap.policy.rest.XacmlRest; import org.onap.policy.rest.XacmlRestProperties; -import org.onap.policy.rest.dao.PolicyDBException; +import org.onap.policy.rest.dao.PolicyDbException; import org.onap.policy.utils.PeCryptoUtils; import org.onap.policy.utils.PolicyUtils; import org.onap.policy.xacml.api.XACMLErrorConstants; @@ -135,7 +136,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // The heartbeat thread. private static Heartbeat heartbeat = null; private static Thread heartbeatThread = null; - private static PolicyDBDao policyDbDao; + private static PolicyDbDao policyDbDao; /* * papEngine - This is our engine workhorse that manages the PDP Groups and Nodes. */ @@ -290,7 +291,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList */ // get an AuditTransaction to lock out all other transactions - PolicyDBDaoTransaction auditTrans = policyDbDao.getNewAuditTransaction(); + PolicyDbDaoTransaction auditTrans = policyDbDao.getNewAuditTransaction(); LOGGER.info("PapServlet: calling auditLocalFileSystem for PDP group audit"); LOGGER.info("PapServlet: old group is " + papEngine.getDefaultGroup().toString()); @@ -333,7 +334,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } private void createDefaultGroupOnInit() { - PolicyDBDaoTransaction addNewGroup = null; + PolicyDbDaoTransaction addNewGroup = null; try { addNewGroup = policyDbDao.getNewTransaction(); OnapPDPGroup group = papEngine.getDefaultGroup(); @@ -372,13 +373,13 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList private static void setPolicyDbDao() throws ServletException { try { - policyDbDao = PolicyDBDao.getPolicyDBDaoInstance(); + policyDbDao = PolicyDbDao.getPolicyDbDaoInstance(); } catch (Exception e) { throw new ServletException("Unable to Create Policy DBDao Instance", e); } } - public static PolicyDBDao getPolicyDbDao() { + public static PolicyDbDao getPolicyDbDao() { return policyDbDao; } @@ -532,7 +533,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList throws ServletException, IOException { OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); setLoggingContext(loggingContext, "doPost", "PAP.post"); - PolicyDBDaoTransaction pdpTransaction = null; + PolicyDbDaoTransaction pdpTransaction = null; try { loggingContext.metricStarted(); im.startTransaction(); @@ -618,7 +619,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList XACMLPapServlet.papEngine.newPDP(id, XACMLPapServlet.papEngine.getDefaultGroup(), id, "Registered on first startup", Integer.parseInt(jmxport)); } catch (NullPointerException | PAPException | IllegalArgumentException | IllegalStateException - | PersistenceException | PolicyDBException e) { + | PersistenceException | PolicyDbException e) { pdpTransaction.rollbackTransaction(); String message = "Failed to create new PDP for id: " + id; PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " " + message); @@ -1340,7 +1341,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList */ public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId, OnapLoggingContext loggingContext) throws IOException { - PolicyDBDaoTransaction acPutTransaction = policyDbDao.getNewTransaction(); + PolicyDbDaoTransaction acPutTransaction = policyDbDao.getNewTransaction(); PolicyLogger.audit("PolicyDBDaoTransaction started for updateGroupsFromAPI"); try { String userId = request.getParameter("userId"); @@ -1717,7 +1718,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList return papEngine; } - public static PolicyDBDaoTransaction getDbDaoTransaction() { + public static PolicyDbDaoTransaction getDbDaoTransaction() { return policyDbDao.getNewTransaction(); } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java index 9b8854ff8..573f274f2 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -164,7 +165,7 @@ public class CreateNewMicroServiceModel { returnReferenceList.put(modelName, utils.getReferenceAttributes()); msAttributes.setRefAttribute(returnReferenceList); - if (!PolicyDBDao.isNullOrEmpty(utils.getListConstraints())) { + if (!PolicyDbDao.isNullOrEmpty(utils.getListConstraints())) { LinkedHashMap enumList = new LinkedHashMap<>(); String[] listArray = utils.getListConstraints().split("#"); for (String str : listArray) { diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotifications.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotifications.java index aca43510d..4e4c02672 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotifications.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotifications.java @@ -3,6 +3,7 @@ * ONAP-PAP-REST * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,7 +49,7 @@ import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.pap.xacml.rest.XACMLPapServlet; import org.onap.policy.rest.XacmlRestProperties; -import org.onap.policy.rest.dao.PolicyDBException; +import org.onap.policy.rest.dao.PolicyDbException; import org.onap.policy.rest.jpa.GroupEntity; import org.onap.policy.rest.jpa.PdpEntity; import org.onap.policy.rest.jpa.PolicyEntity; @@ -84,10 +85,19 @@ public class HandleIncomingNotifications { // Default Constructor } + /** + * Handle the incoming HTTP notification. + * + * @param url the URL + * @param entityId the entity id + * @param entityType the entity type + * @param extraData extra data + * @param xacmlPapServlet the servlet to use + */ public void handleIncomingHttpNotification(String url, String entityId, String entityType, String extraData, XACMLPapServlet xacmlPapServlet) { logger.info("DBDao url: " + url + " has reported an update on " + entityType + " entity " + entityId); - PolicyDBDaoTransaction transaction = PolicyDBDao.getPolicyDBDaoInstance().getNewTransaction(); + PolicyDbDaoTransaction transaction = PolicyDbDao.getPolicyDbDaoInstance().getNewTransaction(); // although its named retries, this is the total number of tries int retries; try { @@ -103,6 +113,7 @@ public class HandleIncomingNotifications { retries = 1; } int pauseBetweenRetries = 1000; + switch (entityType) { case POLICY_NOTIFICATION: @@ -112,7 +123,7 @@ public class HandleIncomingNotifications { break; } catch (Exception e) { logger.debug(e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught exception on handleIncomingPolicyChange(" + url + ", " + entityId + ", " + extraData + ")"); } @@ -131,7 +142,7 @@ public class HandleIncomingNotifications { break; } catch (Exception e) { logger.debug(e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught exception on handleIncomingPdpChange(" + url + ", " + entityId + ", " + transaction + ")"); } @@ -150,7 +161,7 @@ public class HandleIncomingNotifications { break; } catch (Exception e) { logger.debug(e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught exception on handleIncomingGroupChange(" + url + ", " + entityId + ", " + extraData + ", " + transaction + ", " + xacmlPapServlet + ")"); } @@ -162,14 +173,25 @@ public class HandleIncomingNotifications { } } break; + + default: } // no changes should be being made in this function, we still need to // close transaction.rollbackTransaction(); } - private void handleIncomingGroupChange(String groupId, String extraData, PolicyDBDaoTransaction transaction) - throws PAPException, PolicyDBException { + /** + * Handle an incoming group change. + * + * @param groupId the group ID + * @param extraData extra data + * @param transaction the transaction + * @throws PAPException on PAP exceptions + * @throws PolicyDbException on Policy DB exceptions + */ + private void handleIncomingGroupChange(String groupId, String extraData, PolicyDbDaoTransaction transaction) + throws PAPException, PolicyDbException { GroupEntity groupRecord = null; long groupIdLong = -1; try { @@ -180,7 +202,7 @@ public class HandleIncomingNotifications { try { groupRecord = transaction.getGroup(groupIdLong); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to get pdp group record with transaction.getGroup(" + groupIdLong + ");"); throw new PAPException("Could not get local group " + groupIdLong); } @@ -191,7 +213,7 @@ public class HandleIncomingNotifications { // does group folder exist OnapPDPGroup localGroup = null; try { - localGroup = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(groupRecord.getGroupId()); + localGroup = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(groupRecord.getGroupId()); } catch (Exception e) { logger.warn("Caught PAPException trying to get local pdp group with papEngine.getGroup(" + groupId + ");", e); @@ -199,7 +221,7 @@ public class HandleIncomingNotifications { if (localGroup == null && extraData != null) { // here we can try to load an old group id from the extraData try { - localGroup = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(extraData); + localGroup = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(extraData); } catch (Exception e) { logger.warn( "Caught PAPException trying to get local pdp group with papEngine.getGroup(" + extraData + ");", @@ -210,17 +232,17 @@ public class HandleIncomingNotifications { OnapPDPGroup newLocalGroup = null; if (extraData != null) { try { - newLocalGroup = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(extraData); + newLocalGroup = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(extraData); } catch (PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught PAPException trying to get new pdp group with papEngine.getGroup(" + extraData + ");"); } } try { - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().removeGroup(localGroup, newLocalGroup); + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().removeGroup(localGroup, newLocalGroup); } catch (NullPointerException | PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught PAPException trying to get remove pdp group with papEngine.removeGroup(" + localGroup + ", " + newLocalGroup + ");"); throw new PAPException("Could not remove group " + groupId); @@ -228,18 +250,21 @@ public class HandleIncomingNotifications { } else if (localGroup == null) { // creating a new group try { - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().newGroup(groupRecord.getgroupName(), + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().newGroup(groupRecord.getgroupName(), groupRecord.getDescription()); } catch (NullPointerException | PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, - "Caught PAPException trying to create pdp group with papEngine.newGroup(groupRecord.getgroupName(), groupRecord.getDescription());"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, + "Caught PAPException trying to create pdp group with " + + "papEngine.newGroup(groupRecord.getgroupName(), groupRecord.getDescription());"); throw new PAPException("Could not create group " + groupRecord); } try { - localGroup = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(groupRecord.getGroupId()); + localGroup = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(groupRecord.getGroupId()); } catch (PAPException e1) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDBDao.POLICYDBDAO_VAR, - "Caught PAPException trying to get pdp group we just created with papEngine.getGroup(groupRecord.getGroupId());\nAny PDPs or policies in the new group may not have been added"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDbDao.POLICYDBDAO_VAR, + "Caught PAPException trying to get pdp group we just created with " + + "papEngine.getGroup(groupRecord.getGroupId());\nAny PDPs " + + "or policies in the new group may not have been added"); return; } // add possible pdps to group @@ -247,11 +272,12 @@ public class HandleIncomingNotifications { for (Object pdpO : pdpsInGroup) { PdpEntity pdp = (PdpEntity) pdpO; try { - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().newPDP(pdp.getPdpId(), localGroup, + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().newPDP(pdp.getPdpId(), localGroup, pdp.getPdpName(), pdp.getDescription(), pdp.getJmxPort()); } catch (NullPointerException | PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, - "Caught PAPException trying to get create pdp with papEngine.newPDP(pdp.getPdpId(), localGroup, pdp.getPdpName(), pdp.getDescription(), pdp.getJmxPort());"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, + "Caught PAPException trying to get create pdp with papEngine.newPDP(pdp.getPdpId(), " + + "localGroup, pdp.getPdpName(), pdp.getDescription(), pdp.getJmxPort());"); throw new PAPException("Could not create pdp " + pdp); } } @@ -271,36 +297,36 @@ public class HandleIncomingNotifications { // set default if it should be if (!localGroupClone.isDefaultGroup() && groupRecord.isDefaultGroup()) { try { - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().setDefaultGroup(localGroup); + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().setDefaultGroup(localGroup); return; } catch (PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught PAPException trying to set default group with papEngine.SetDefaultGroup(" + localGroupClone + ");"); throw new PAPException("Could not set default group to " + localGroupClone); } } boolean needToUpdate = false; - if (updateGroupPoliciesInFileSystem(localGroupClone, localGroup, groupRecord, transaction)) { + if (updateGroupPoliciesInFileSystem(localGroupClone, localGroup, groupRecord)) { needToUpdate = true; } - if (!PolicyDBDao.stringEquals(localGroupClone.getId(), groupRecord.getGroupId()) - || !PolicyDBDao.stringEquals(localGroupClone.getName(), groupRecord.getgroupName())) { + if (!PolicyDbDao.stringEquals(localGroupClone.getId(), groupRecord.getGroupId()) + || !PolicyDbDao.stringEquals(localGroupClone.getName(), groupRecord.getgroupName())) { // changing ids // we do not want to change the id, the papEngine will do this // for us, it needs to know the old id localGroupClone.setName(groupRecord.getgroupName()); needToUpdate = true; } - if (!PolicyDBDao.stringEquals(localGroupClone.getDescription(), groupRecord.getDescription())) { + if (!PolicyDbDao.stringEquals(localGroupClone.getDescription(), groupRecord.getDescription())) { localGroupClone.setDescription(groupRecord.getDescription()); needToUpdate = true; } if (needToUpdate) { try { - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().updateGroup(localGroupClone); + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().updateGroup(localGroupClone); } catch (PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught PAPException trying to update group with papEngine.updateGroup(" + localGroupClone + ");"); throw new PAPException("Could not update group " + localGroupClone); @@ -312,7 +338,7 @@ public class HandleIncomingNotifications { // this will also handle removes, since incoming pdpGroup has no policies // internally, we are just going to add them all in from the db private boolean updateGroupPoliciesInFileSystem(OnapPDPGroup pdpGroup, OnapPDPGroup oldPdpGroup, - GroupEntity groupRecord, PolicyDBDaoTransaction transaction) throws PAPException, PolicyDBException { + GroupEntity groupRecord) throws PAPException, PolicyDbException { if (!(pdpGroup instanceof StdPDPGroup)) { throw new PAPException("group is not a StdPDPGroup"); } @@ -327,7 +353,7 @@ public class HandleIncomingNotifications { } for (PolicyEntity policy : groupRecord.getPolicies()) { String pdpPolicyName = - PolicyDBDao.getPolicyDBDaoInstance().getPdpPolicyName(policy.getPolicyName(), policy.getScope()); + PolicyDbDao.getPolicyDbDaoInstance().getPdpPolicyName(policy.getPolicyName(), policy.getScope()); if (group.getPolicy(pdpPolicyName) == null) { didUpdate = true; if (currentPolicySet.containsKey(pdpPolicyName)) { @@ -337,7 +363,7 @@ public class HandleIncomingNotifications { "PolicyDBDao: Adding the new policy to the PDP group after notification: " + pdpPolicyName); InputStream policyStream = new ByteArrayInputStream(policy.getPolicyData().getBytes()); group.copyPolicyToFile(pdpPolicyName, policyStream); - ((StdPDPPolicy) (group.getPolicy(pdpPolicyName))).setName(PolicyDBDao.getPolicyDBDaoInstance() + ((StdPDPPolicy) (group.getPolicy(pdpPolicyName))).setName(PolicyDbDao.getPolicyDbDaoInstance() .removeExtensionAndVersionFromPolicyName(pdpPolicyName)); try { policyStream.close(); @@ -356,7 +382,7 @@ public class HandleIncomingNotifications { return didUpdate; } - private void handleIncomingPdpChange(String pdpId, PolicyDBDaoTransaction transaction) throws PAPException { + private void handleIncomingPdpChange(String pdpId, PolicyDbDaoTransaction transaction) throws PAPException { // get pdp long pdpIdLong = -1; try { @@ -368,7 +394,7 @@ public class HandleIncomingNotifications { try { pdpRecord = transaction.getPdp(pdpIdLong); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to get pdp record with transaction.getPdp(" + pdpIdLong + ");"); throw new PAPException("Could not get local pdp " + pdpIdLong); } @@ -377,15 +403,15 @@ public class HandleIncomingNotifications { } OnapPDP localPdp = null; try { - localPdp = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getPDP(pdpRecord.getPdpId()); + localPdp = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getPDP(pdpRecord.getPdpId()); } catch (PAPException e) { logger.warn("Caught PAPException trying to get local pdp with papEngine.getPDP(" + pdpId + ");", e); } if (localPdp != null && pdpRecord.isDeleted()) { try { - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().removePDP(localPdp); + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().removePDP(localPdp); } catch (PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught PAPException trying to get remove pdp with papEngine.removePDP(" + localPdp + ");"); throw new PAPException("Could not remove pdp " + pdpId); } @@ -395,17 +421,18 @@ public class HandleIncomingNotifications { OnapPDPGroup localGroup = null; try { localGroup = - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(pdpRecord.getGroup().getGroupId()); + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(pdpRecord.getGroup().getGroupId()); } catch (PAPException e1) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDBDao.POLICYDBDAO_VAR, - "Caught PAPException trying to get local group to add pdp to with papEngine.getGroup(pdpRecord.getGroup().getGroupId());"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDbDao.POLICYDBDAO_VAR, + "Caught PAPException trying to get local group to add pdp to with " + + "papEngine.getGroup(pdpRecord.getGroup().getGroupId());"); throw new PAPException("Could not get local group"); } try { - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().newPDP(pdpRecord.getPdpId(), localGroup, + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().newPDP(pdpRecord.getPdpId(), localGroup, pdpRecord.getPdpName(), pdpRecord.getDescription(), pdpRecord.getJmxPort()); } catch (NullPointerException | PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught PAPException trying to create pdp with papEngine.newPDP(" + pdpRecord.getPdpId() + ", " + localGroup + ", " + pdpRecord.getPdpName() + ", " + pdpRecord.getDescription() + ", " + pdpRecord.getJmxPort() + ");"); @@ -413,41 +440,41 @@ public class HandleIncomingNotifications { } } else { boolean needToUpdate = false; - if (!PolicyDBDao.stringEquals(localPdp.getId(), pdpRecord.getPdpId()) - || !PolicyDBDao.stringEquals(localPdp.getName(), pdpRecord.getPdpName())) { + if (!PolicyDbDao.stringEquals(localPdp.getId(), pdpRecord.getPdpId()) + || !PolicyDbDao.stringEquals(localPdp.getName(), pdpRecord.getPdpName())) { // again, we don't want to change the id, the papEngine will do // this localPdp.setName(pdpRecord.getPdpName()); needToUpdate = true; } - if (!PolicyDBDao.stringEquals(localPdp.getDescription(), pdpRecord.getDescription())) { + if (!PolicyDbDao.stringEquals(localPdp.getDescription(), pdpRecord.getDescription())) { localPdp.setDescription(pdpRecord.getDescription()); needToUpdate = true; } String localPdpGroupId = null; try { - localPdpGroupId = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getPDPGroup(localPdp).getId(); + localPdpGroupId = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getPDPGroup(localPdp).getId(); } catch (PAPException e) { // could be null or something, just warn at this point - logger.warn( - "Caught PAPException trying to get id of local group that pdp is in with localPdpGroupId = papEngine.getPDPGroup(localPdp).getId();", - e); + logger.warn("Caught PAPException trying to get id of local group that pdp is in with " + + "localPdpGroupId = papEngine.getPDPGroup(localPdp).getId();", e); } - if (!PolicyDBDao.stringEquals(localPdpGroupId, pdpRecord.getGroup().getGroupId())) { + if (!PolicyDbDao.stringEquals(localPdpGroupId, pdpRecord.getGroup().getGroupId())) { OnapPDPGroup newPdpGroup = null; try { - newPdpGroup = PolicyDBDao.getPolicyDBDaoInstance().getPapEngine() + newPdpGroup = PolicyDbDao.getPolicyDbDaoInstance().getPapEngine() .getGroup(pdpRecord.getGroup().getGroupId()); } catch (PAPException e) { // ok, now we have an issue. Time to stop things - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, - "Caught PAPException trying to get id of local group to move pdp to with papEngine.getGroup(pdpRecord.getGroup().getGroupId());"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, + "Caught PAPException trying to get id of local group to move pdp to with " + + "papEngine.getGroup(pdpRecord.getGroup().getGroupId());"); throw new PAPException("Could not get local group"); } try { - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().movePDP(localPdp, newPdpGroup); + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().movePDP(localPdp, newPdpGroup); } catch (PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught PAPException trying to move pdp with papEngine.movePDP(localPdp, newPdpGroup);"); throw new PAPException("Could not move pdp " + localPdp); } @@ -458,9 +485,9 @@ public class HandleIncomingNotifications { } if (needToUpdate) { try { - PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().updatePDP(localPdp); + PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().updatePDP(localPdp); } catch (PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught PAPException trying to update pdp with papEngine.updatePdp(" + localPdp + ");"); throw new PAPException("Could not update pdp " + localPdp); } @@ -492,22 +519,22 @@ public class HandleIncomingNotifications { if (policy.getConfigurationData() != null) { subFile = - getPolicySubFile(policy.getConfigurationData().getConfigurationName(), PolicyDBDao.CONFIG); + getPolicySubFile(policy.getConfigurationData().getConfigurationName(), PolicyDbDao.CONFIG); } else if (policy.getActionBodyEntity() != null) { - subFile = getPolicySubFile(policy.getActionBodyEntity().getActionBodyName(), PolicyDBDao.ACTION); + subFile = getPolicySubFile(policy.getActionBodyEntity().getActionBodyName(), PolicyDbDao.ACTION); } if (subFile != null) { Files.deleteIfExists(subFile); } if (policy.getConfigurationData() != null) { - writePolicySubFile(policy, PolicyDBDao.CONFIG); + writePolicySubFile(policy, PolicyDbDao.CONFIG); } else if (policy.getActionBodyEntity() != null) { writePolicySubFile(policy, action); } } } catch (IOException e1) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDbDao.POLICYDBDAO_VAR, "Error occurred while performing [" + action + "] of Policy File: " + policyName); } finally { session.close(); @@ -520,8 +547,8 @@ public class HandleIncomingNotifications { String type = null; String subTypeName = null; String subTypeBody = null; - if (PolicyDBDao.CONFIG.equalsIgnoreCase(policyType)) { - type = PolicyDBDao.CONFIG; + if (PolicyDbDao.CONFIG.equalsIgnoreCase(policyType)) { + type = PolicyDbDao.CONFIG; subTypeName = FilenameUtils.removeExtension(policy.getConfigurationData().getConfigurationName()); subTypeBody = policy.getConfigurationData().getConfigBody(); @@ -541,12 +568,12 @@ public class HandleIncomingNotifications { subTypeName = subTypeName + ".txt"; } } - } else if (PolicyDBDao.ACTION.equalsIgnoreCase(policyType)) { - type = PolicyDBDao.ACTION; + } else if (PolicyDbDao.ACTION.equalsIgnoreCase(policyType)) { + type = PolicyDbDao.ACTION; subTypeName = policy.getActionBodyEntity().getActionBodyName(); subTypeBody = policy.getActionBodyEntity().getActionBody(); } - Path filePath = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_WEBAPPS).toString(), type); + Path filePath = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_WEBAPPS), type); if (subTypeBody == null) { subTypeBody = ""; @@ -560,11 +587,10 @@ public class HandleIncomingNotifications { try (FileWriter fileWriter = new FileWriter(file, false)) { // false to overwrite fileWriter.write(subTypeBody); - fileWriter.close(); success = true; } } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Exception occured while creating Configuration File for Policy : " + policy.getPolicyName()); } return success; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java index b703917c4..c3171de39 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java @@ -3,6 +3,7 @@ * ONAP-PAP-REST * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,7 +61,7 @@ public class NotifyOtherPaps { + entityType + "," + newGroupId + ") called"); failedPaps = new ArrayList<>(); - List otherServers = PolicyDBDao.getPolicyDBDaoInstance().getOtherServers(); + List otherServers = PolicyDbDao.getPolicyDbDaoInstance().getOtherServers(); // Notify other paps startNotifyThreads(otherServers, entityId, entityType, newGroupId); // Retry for failed paps @@ -104,10 +105,9 @@ public class NotifyOtherPaps { @Override public void run() { - PolicyDBDao dao = new PolicyDBDao(); + PolicyDbDao dao = new PolicyDbDao(); PolicyDBDaoEntity dbdEntity = (PolicyDBDaoEntity) obj; String otherPap = dbdEntity.getPolicyDBDaoUrl(); - String username = dbdEntity.getUsername(); String txt; try { txt = PeCryptoUtils.decrypt(dbdEntity.getPassword()); @@ -118,7 +118,6 @@ public class NotifyOtherPaps { } HttpURLConnection connection = null; - UUID requestId = UUID.randomUUID(); URL url; String papUrl; try { @@ -176,6 +175,10 @@ public class NotifyOtherPaps { LOGGER.warn("Caught ProtocolException on connection.setRequestMethod(\"PUT\");", e); return; } + + String username = dbdEntity.getUsername(); + UUID requestId = UUID.randomUUID(); + Base64.Encoder encoder = Base64.getEncoder(); String encoding = encoder.encodeToString((username + ":" + txt).getBytes(StandardCharsets.UTF_8)); connection.setRequestProperty("Authorization", "Basic " + encoding); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java deleted file mode 100644 index 87e684380..000000000 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java +++ /dev/null @@ -1,820 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP-PAP-REST - * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. - * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. - * ================================================================================ - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.pap.xacml.rest.components; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.api.pap.PDPPolicy; -import com.att.research.xacml.util.XACMLProperties; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.net.URI; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -import javax.persistence.PersistenceException; - -import org.apache.commons.io.FilenameUtils; -import org.hibernate.Criteria; -import org.hibernate.LockMode; -import org.hibernate.Query; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.criterion.Restrictions; -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.eelf.PolicyLogger; -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.adapter.PolicyRestAdapter; -import org.onap.policy.rest.dao.PolicyDBException; -import org.onap.policy.rest.jpa.ActionBodyEntity; -import org.onap.policy.rest.jpa.ConfigurationDataEntity; -import org.onap.policy.rest.jpa.DatabaseLockEntity; -import org.onap.policy.rest.jpa.GroupEntity; -import org.onap.policy.rest.jpa.PdpEntity; -import org.onap.policy.rest.jpa.PolicyDBDaoEntity; -import org.onap.policy.rest.jpa.PolicyEntity; -import org.onap.policy.utils.PeCryptoUtils; -import org.onap.policy.xacml.api.XACMLErrorConstants; -import org.onap.policy.xacml.api.pap.OnapPDP; -import org.onap.policy.xacml.api.pap.OnapPDPGroup; -import org.onap.policy.xacml.api.pap.PAPPolicyEngine; -import org.onap.policy.xacml.std.pap.StdPDPGroup; -import org.onap.policy.xacml.std.pap.StdPDPPolicy; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class PolicyDBDao { - private static final Logger logger = FlexLogger.getLogger(PolicyDBDao.class); - public static final String JSON_CONFIG = "JSON"; - public static final String XML_CONFIG = "XML"; - public static final String PROPERTIES_CONFIG = "PROPERTIES"; - public static final String OTHER_CONFIG = "OTHER"; - public static final String AUDIT_USER = "audit"; - - public static final String CONFIG = "Config"; - public static final String ACTION = "Action"; - public static final String GROUP_ID = "groupId"; - public static final String DELETED = "deleted"; - public static final String GROUPENTITY_SELECT = - "SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"; - public static final String PDPENTITY_SELECT = - "SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted"; - public static final String GROUP_NOT_FOUND = "The group could not be found with id "; - public static final String FOUND_IN_DB_NOT_DEL = " were found in the database that are not deleted"; - public static final String MORE_THAN_ONE_PDP = "Somehow, more than one pdp with the same id "; - public static final String DELETED_STATUS_FOUND = " and deleted status were found in the database"; - public static final String DUPLICATE_GROUPID = "Somehow, more than one group with the same id "; - public static final String PDP_ID = "pdpId"; - public static final String QUERY_FAILED_FOR_GROUP = "Query failed trying to check for existing group"; - public static final String QUERY_FAILED_GET_GROUP = "Query failed trying to get group "; - public static final String SCOPE = "scope"; - public static final String POLICYDBDAO_VAR = "PolicyDBDao"; - public static final String DUP_POLICYID = "Somehow, more than one policy with the id "; - public static final String FOUND_IN_DB = " were found in the database"; - private static PolicyDBDao currentInstance = null; - private static boolean isJunit = false; - private static SessionFactory sessionfactory; - private List otherServers; - private PAPPolicyEngine papEngine; - - /** - * Gets the current instance of PolicyDBDao. - * - * @return The instance of PolicyDBDao or throws exception if the given instance is null. - * @throws IllegalStateException if a PolicyDBDao instance is null. Call - * createPolicyDBDaoInstance (EntityManagerFactory emf) to get this. - */ - public static PolicyDBDao getPolicyDBDaoInstance() { - logger.debug("getPolicyDBDaoInstance() as getPolicyDBDaoInstance() called"); - if (currentInstance != null) { - return currentInstance; - } else { - currentInstance = new PolicyDBDao("init"); - } - return currentInstance; - } - - public void setPapEngine(PAPPolicyEngine papEngine2) { - this.papEngine = papEngine2; - } - - @Autowired - public PolicyDBDao(SessionFactory sessionFactory) { - PolicyDBDao.sessionfactory = sessionFactory; - } - - public PolicyDBDao() { - // Default Constructor - } - - public PolicyDBDao(String init) { - // not needed in this release - if (!register()) { - PolicyLogger - .error("This server's PolicyDBDao instance could not be registered and may not reveive updates"); - } - - otherServers = getRemotePolicyDBDaoList(); - if (logger.isDebugEnabled()) { - logger.debug("Number of remote PolicyDBDao instances: " + otherServers.size()); - } - if (otherServers.isEmpty()) { - logger.warn("List of PolicyDBDao servers is empty or could not be retrieved"); - } - } - - // not static because we are going to be using the instance's emf - // waitTime in ms to wait for lock, or -1 to wait forever (no) - @SuppressWarnings("deprecation") - public void startTransactionSynced(Session session, int waitTime) { - logger.debug("\n\nstartTransactionSynced(Hibernate Session,int waitTime) as " + "\n startTransactionSynced(" - + session + "," + waitTime + ") called\n\n"); - DatabaseLockEntity lock = null; - session.beginTransaction(); - try { - if (logger.isDebugEnabled()) { - logger.debug("\n\nstartTransactionSynced():" + "\n ATTEMPT to get the DB lock" + "\n\n"); - } - lock = (DatabaseLockEntity) session.get(DatabaseLockEntity.class, 1, LockMode.PESSIMISTIC_WRITE); - if (logger.isDebugEnabled()) { - logger.debug("\n\nstartTransactionSynced():" + "\n GOT the DB lock" + "\n\n"); - } - } catch (Exception e) { - logger.error("Exception Occured" + e); - } - if (lock == null) { - throw new IllegalStateException( - "The lock row does not exist in the table. Please create a primary key with value = 1."); - } - - } - - /** - * Gets the list of other registered PolicyDBDaos from the database - * - * @return List (type PolicyDBDaoEntity) of other PolicyDBDaos - */ - private List getRemotePolicyDBDaoList() { - logger.debug("getRemotePolicyDBDaoList() as getRemotePolicyDBDaoList() called"); - List policyDBDaoEntityList = new LinkedList<>(); - Session session = sessionfactory.openSession(); - try { - Criteria cr = session.createCriteria(PolicyDBDaoEntity.class); - policyDBDaoEntityList = cr.list(); - } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, - "Exception querying for other registered PolicyDBDaos"); - logger.warn("List of remote PolicyDBDaos will be empty", e); - } finally { - try { - session.close(); - } catch (Exception e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e); - } - } - return policyDBDaoEntityList; - } - - public PolicyDBDaoTransaction getNewTransaction() { - logger.debug("getNewTransaction() as getNewTransaction() called"); - return new PolicyDbDaoTransactionInstance("init"); - } - - /* - * Because the normal transactions are not used in audits, we can use the same transaction - * mechanism to get a transaction and obtain the emlock and the DB lock. We just need to provide - * different transaction timeout values in ms because the audit will run longer than normal - * transactions. - */ - public PolicyDBDaoTransaction getNewAuditTransaction() { - logger.debug("getNewAuditTransaction() as getNewAuditTransaction() called"); - // Use the standard transaction wait time in ms - int auditWaitMs = Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_TRANS_WAIT)); - // Use the (extended) audit timeout time in ms - int auditTimeoutMs = Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_AUDIT_TIMEOUT)); - return new PolicyDbDaoTransactionInstance(auditTimeoutMs, auditWaitMs); - } - - /** - * Checks if two strings are equal. Null strings ARE allowed. - * - * @param one A String or null to compare - * @param two A String or null to compare - */ - public static boolean stringEquals(String one, String two) { - logger.debug("stringEquals(String one, String two) as stringEquals(" + one + ", " + two + ") called"); - if (one == null && two == null) { - return true; - } - if (one == null || two == null) { - return false; - } - return one.equals(two); - } - - /** - * Returns the url of this local pap server, removing the username and password, if they are - * present - * - * @return The url of this local pap server - */ - public String[] getPapUrlUserPass() { - logger.debug("getPapUrl() as getPapUrl() called"); - String url = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URL); - if (url == null) { - return null; - } - return splitPapUrlUserPass(url); - } - - public String[] splitPapUrlUserPass(String url) { - String[] urlUserPass = new String[3]; - String[] commaSplit = url.split(","); - urlUserPass[0] = commaSplit[0]; - if (commaSplit.length > 2) { - urlUserPass[1] = commaSplit[1]; - urlUserPass[2] = commaSplit[2]; - } - if (urlUserPass[1] == null || "".equals(urlUserPass[1])) { - String usernamePropertyValue = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_USERID); - if (usernamePropertyValue != null) { - urlUserPass[1] = usernamePropertyValue; - } - } - if (urlUserPass[2] == null || "".equals(urlUserPass[2])) { - String passwordPropertyValue = - PeCryptoUtils.decrypt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_PASS)); - if (passwordPropertyValue != null) { - urlUserPass[2] = passwordPropertyValue; - } - } - // if there is no comma, for some reason there is no user name and - // password, so don't try to cut them off - return urlUserPass; - } - - /** - * Register the PolicyDBDao instance in the PolicyDBDaoEntity table - * - * @return Boolean, were we able to register? - */ - private boolean register() { - logger.debug("register() as register() called"); - String[] url = getPapUrlUserPass(); - // --- check URL length - if (url == null || url.length < 3) { - return false; - } - Session session = sessionfactory.openSession(); - try { - startTransactionSynced(session, 1000); - } catch (IllegalStateException e) { - logger.debug("\nPolicyDBDao.register() caught an IllegalStateException: \n" + e + "\n"); - DatabaseLockEntity lock; - lock = (DatabaseLockEntity) session.get(DatabaseLockEntity.class, 1); - if (lock == null) { - lock = new DatabaseLockEntity(); - lock.setKey(1); - try { - session.persist(lock); - session.flush(); - session.getTransaction().commit(); - session.close(); - } catch (Exception e2) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, POLICYDBDAO_VAR, - "COULD NOT CREATE DATABASELOCK ROW. WILL TRY ONE MORE TIME"); - } - - session = sessionfactory.openSession(); - try { - startTransactionSynced(session, 1000); - } catch (Exception e3) { - String msg = "DATABASE LOCKING NOT WORKING. CONCURRENCY CONTROL NOT WORKING"; - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e3, POLICYDBDAO_VAR, msg); - throw new IllegalStateException("msg" + "\n" + e3); - } - } - } - logger.debug("\nPolicyDBDao.register. Database locking and concurrency control is initialized\n"); - PolicyDBDaoEntity foundPolicyDBDaoEntity = null; - Criteria cr = session.createCriteria(PolicyDBDaoEntity.class); - cr.add(Restrictions.eq("policyDBDaoUrl", url[0])); - List data = cr.list(); - if (!data.isEmpty()) { - foundPolicyDBDaoEntity = (PolicyDBDaoEntity) data.get(0); - } - - // encrypt the password - String txt = PeCryptoUtils.encrypt(url[2]); - if (foundPolicyDBDaoEntity == null) { - PolicyDBDaoEntity newPolicyDBDaoEntity = new PolicyDBDaoEntity(); - newPolicyDBDaoEntity.setPolicyDBDaoUrl(url[0]); - newPolicyDBDaoEntity.setDescription("PAP server at " + url[0]); - newPolicyDBDaoEntity.setUsername(url[1]); - newPolicyDBDaoEntity.setPassword(txt); - try { - session.persist(newPolicyDBDaoEntity); - session.getTransaction().commit(); - } catch (Exception e) { - logger.debug(e); - try { - session.getTransaction().rollback(); - } catch (Exception e2) { - logger.debug(e2); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, POLICYDBDAO_VAR, - "Could not add new PolicyDBDao to the database"); - } - } - } else { - // just want to update in order to change modified date - if (url[1] != null && !stringEquals(url[1], foundPolicyDBDaoEntity.getUsername())) { - foundPolicyDBDaoEntity.setUsername(url[1]); - } - if (txt != null && !stringEquals(txt, foundPolicyDBDaoEntity.getPassword())) { - foundPolicyDBDaoEntity.setPassword(txt); - } - foundPolicyDBDaoEntity.preUpdate(); - try { - session.getTransaction().commit(); - } catch (Exception e) { - logger.debug(e); - try { - session.getTransaction().rollback(); - } catch (Exception e2) { - logger.debug(e2); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, POLICYDBDAO_VAR, - "Could not update PolicyDBDao in the database"); - } - } - } - session.close(); - logger.debug("\nPolicyDBDao.register(). Success!!\n"); - return true; - } - - /* - * This method is called during all pushPolicy transactions and makes sure the file system group - * is in sync with the database groupentity - */ - public StdPDPGroup synchronizeGroupPoliciesInFileSystem(StdPDPGroup pdpGroup, GroupEntity groupentity) - throws PAPException, PolicyDBException { - - HashMap currentPolicyMap = new HashMap<>(); - HashSet newPolicyIdSet = new HashSet<>(); - HashSet newPolicySet = new HashSet<>(); - - for (PDPPolicy pdpPolicy : pdpGroup.getPolicies()) { - currentPolicyMap.put(pdpPolicy.getId(), pdpPolicy); - } - - for (PolicyEntity policy : groupentity.getPolicies()) { - String pdpPolicyId = getPdpPolicyName(policy.getPolicyName(), policy.getScope()); - newPolicyIdSet.add(pdpPolicyId); - - if (currentPolicyMap.containsKey(pdpPolicyId)) { - newPolicySet.add(currentPolicyMap.get(pdpPolicyId)); - } else { - // convert PolicyEntity object to PDPPolicy - String name = pdpPolicyId.replace(".xml", ""); - name = name.substring(0, name.lastIndexOf('.')); - InputStream policyStream = new ByteArrayInputStream(policy.getPolicyData().getBytes()); - pdpGroup.copyPolicyToFile(pdpPolicyId, name, policyStream); - URI location = Paths.get(pdpGroup.getDirectory().toAbsolutePath().toString(), pdpPolicyId).toUri(); - StdPDPPolicy newPolicy = null; - try { - newPolicy = new StdPDPPolicy(pdpPolicyId, true, - removeExtensionAndVersionFromPolicyName(pdpPolicyId), location); - newPolicySet.add(newPolicy); - logger.info("Adding new policy to PDPGroup - " + newPolicy.getId() + ", Location - " + location); - } catch (Exception e) { - logger.debug(e); - PolicyLogger - .error("PolicyDBDao: Exception occurred while creating the StdPDPPolicy newPolicy object " - + e.getMessage()); - } - } - } - - for (String id : currentPolicyMap.keySet()) { - if (!newPolicyIdSet.contains(id)) { - try { - Files.delete(Paths.get(currentPolicyMap.get(id).getLocation())); - } catch (Exception e) { - logger.debug(e); - PolicyLogger.error( - "PolicyDBDao: Exception occurred while attempting to delete the old version of the policy file from the group. " - + e.getMessage()); - } - } - } - - logger.info("PolicyDBDao: Adding new policy set to group to keep filesystem and DB in sync"); - pdpGroup.setPolicies(newPolicySet); - - return pdpGroup; - } - - public String removeExtensionAndVersionFromPolicyName(String originalPolicyName) throws PolicyDBException { - return getPolicyNameAndVersionFromPolicyFileName(originalPolicyName)[0]; - } - - /** - * Splits apart the policy name and version from a policy file path - * - * @param originalPolicyName: a policy file name ex: Config_policy.2.xml - * @return An array [0]: The policy name, [1]: the policy version, as a string - */ - public String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) throws PolicyDBException { - String policyName = originalPolicyName; - String[] nameAndVersion = new String[2]; - try { - policyName = removeFileExtension(policyName); - nameAndVersion[0] = policyName.substring(0, policyName.lastIndexOf('.')); - if (isNullOrEmpty(nameAndVersion[0])) { - throw new PolicyDBException(); - } - } catch (Exception e) { - nameAndVersion[0] = originalPolicyName; - logger.debug(e); - } - try { - nameAndVersion[1] = policyName.substring(policyName.lastIndexOf('.') + 1); - if (isNullOrEmpty(nameAndVersion[1])) { - throw new PolicyDBException(); - } - } catch (Exception e) { - nameAndVersion[1] = "1"; - logger.debug(e); - } - return nameAndVersion; - } - - public String getPdpPolicyName(String name, String scope) { - String finalName = ""; - finalName += scope; - finalName += "."; - finalName += removeFileExtension(name); - finalName += ".xml"; - return finalName; - } - - private String removeFileExtension(String fileName) { - return fileName.substring(0, fileName.lastIndexOf('.')); - } - - public void auditLocalDatabase(PAPPolicyEngine papEngine2) { - logger.debug("PolicyDBDao.auditLocalDatabase() is called"); - try { - deleteAllGroupTables(); - auditGroups(papEngine2); - } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "auditLocalDatabase() error"); - logger.error("Exception Occured" + e); - } - } - - public StdPDPGroup auditLocalFileSystem(StdPDPGroup group) { - - logger.info("Starting Local File System group audit"); - Session session = sessionfactory.openSession(); - session.getTransaction().begin(); - - StdPDPGroup updatedGroup = null; - try { - Query groupQuery = session.createQuery(GROUPENTITY_SELECT); - groupQuery.setParameter(GROUP_ID, group.getId()); - groupQuery.setParameter(DELETED, false); - List groupQueryList = groupQuery.list(); - if (groupQueryList != null && !groupQueryList.isEmpty()) { - GroupEntity dbgroup = (GroupEntity) groupQueryList.get(0); - updatedGroup = synchronizeGroupPoliciesInFileSystem(group, dbgroup); - logger.info("Group was updated during file system audit: " + updatedGroup.toString()); - } - } catch (PAPException | PolicyDBException e) { - logger.error(e); - } catch (Exception e) { - logger.error(e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, - "Caught Exception trying to check if group exists groupQuery.getResultList()"); - throw new PersistenceException("Query failed trying to check if group " + group.getId() + " exists"); - } - - session.getTransaction().commit(); - session.close(); - - return updatedGroup; - } - - /* - * This method is called at startup to recreate config data from DB to the file system. - * - */ - public void synchronizeConfigDataInFileSystem() { - - logger.info("Starting Local File System Config data Sync"); - // sync both web apps Config and Action - syncConfigData(ConfigurationDataEntity.class, CONFIG); - syncConfigData(ActionBodyEntity.class, ACTION); - } - - private void syncConfigData(Class cl, String type) { - Session session = sessionfactory.openSession(); - try { - final Criteria configDataQuery = session.createCriteria(cl.getName()); - @SuppressWarnings("unchecked") - final List configDataResult = configDataQuery.list(); - Path webappsPath = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_WEBAPPS), type); - - for (final T configData : configDataResult) { - String configName = null; - byte[] configBody; - try { - if (CONFIG.equalsIgnoreCase(type)) { - configName = ((ConfigurationDataEntity) configData).getConfigurationName(); - configBody = - (((ConfigurationDataEntity) configData).getConfigBody() != null) - ? ((ConfigurationDataEntity) configData).getConfigBody() - .getBytes(StandardCharsets.UTF_8) - : "".getBytes(); - } else { - configName = ((ActionBodyEntity) configData).getActionBodyName(); - configBody = (((ActionBodyEntity) configData).getActionBody() != null) - ? ((ActionBodyEntity) configData).getActionBody().getBytes(StandardCharsets.UTF_8) - : "".getBytes(); - } - Path filePath = Paths.get(webappsPath.toString(), configName); - if (!filePath.toFile().exists()) { - Files.write(filePath, configBody); - logger.info("Created Config File from DB - " + filePath.toString()); - } - } catch (Exception e) { - // log and keep going - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, - "Exception occured while creating Configuration File - " + configName); - } - } - } catch (final Exception exception) { - logger.error("Unable to synchronizeConfigDataInFileSystem", exception); - } - session.close(); - } - - public void deleteAllGroupTables() { - logger.debug("PolicyDBDao.deleteAllGroupTables() called"); - Session session = sessionfactory.openSession(); - session.getTransaction().begin(); - - Query deletePdpEntityEntityTableUpdate = session.getNamedQuery("PdpEntity.deleteAll"); - deletePdpEntityEntityTableUpdate.executeUpdate(); - - Query deleteGroupEntityTableUpdate = session.getNamedQuery("GroupEntity.deleteAll"); - deleteGroupEntityTableUpdate.executeUpdate(); - - session.getTransaction().commit(); - session.close(); - } - - @SuppressWarnings("unchecked") - public void auditGroups(PAPPolicyEngine papEngine2) { - logger.debug("PolicyDBDao.auditGroups() called"); - - Session session = sessionfactory.openSession(); - session.getTransaction().begin(); - final String AUDIT_STR = "Audit"; - try { - - Set groups = papEngine2.getOnapPDPGroups(); - - for (OnapPDPGroup grp : groups) { - try { - GroupEntity groupEntity = new GroupEntity(); - groupEntity.setGroupName(grp.getName()); - groupEntity.setDescription(grp.getDescription()); - groupEntity.setDefaultGroup(grp.isDefaultGroup()); - groupEntity.setCreatedBy(AUDIT_STR); - groupEntity.setGroupId(createNewPDPGroupId(grp.getId())); - groupEntity.setModifiedBy(AUDIT_STR); - session.persist(groupEntity); - Set pdps = grp.getOnapPdps(); - - for (OnapPDP pdp : pdps) { - PdpEntity pdpEntity = new PdpEntity(); - pdpEntity.setGroup(groupEntity); - pdpEntity.setJmxPort(pdp.getJmxPort()); - pdpEntity.setPdpId(pdp.getId()); - pdpEntity.setPdpName(pdp.getName()); - pdpEntity.setModifiedBy(AUDIT_STR); - pdpEntity.setCreatedBy(AUDIT_STR); - session.persist(pdpEntity); - } - - Set policies = grp.getPolicies(); - - for (PDPPolicy policy : policies) { - try { - String[] stringArray = getNameScopeAndVersionFromPdpPolicy(policy.getId()); - if (stringArray == null) { - throw new IllegalArgumentException( - "Invalid input - policyID must contain name, scope and version"); - } - List policyEntityList; - Query getPolicyEntitiesQuery = session.getNamedQuery("PolicyEntity.findByNameAndScope"); - getPolicyEntitiesQuery.setParameter("name", stringArray[0]); - getPolicyEntitiesQuery.setParameter(SCOPE, stringArray[1]); - - policyEntityList = getPolicyEntitiesQuery.list(); - PolicyEntity policyEntity = null; - if (!policyEntityList.isEmpty()) { - policyEntity = policyEntityList.get(0); - } - if (policyEntity != null) { - groupEntity.addPolicyToGroup(policyEntity); - } - } catch (Exception e2) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, POLICYDBDAO_VAR, - "Exception auditGroups inner catch"); - } - } - } catch (Exception e1) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, POLICYDBDAO_VAR, - "Exception auditGroups middle catch"); - } - } - } catch (Exception e) { - session.getTransaction().rollback(); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "Exception auditGroups outer catch"); - session.close(); - return; - } - - session.getTransaction().commit(); - session.close(); - - } - - public String getConfigFile(String filename, PolicyRestAdapter policy) { - if (policy == null) { - return getConfigFile(filename, (String) null); - } - return getConfigFile(filename, policy.getConfigType()); - } - - // copied from ConfigPolicy.java and modified - // Here we are adding the extension for the configurations file based on the - // config type selection for saving. - public String getConfigFile(String inputFilename, String configType) { - String filename = inputFilename; - logger.debug("getConfigFile(String filename, String scope, String configType) as getConfigFile(" + filename - + ", " + configType + ") called"); - filename = FilenameUtils.removeExtension(filename); - String id = configType; - - if (id != null) { - if (id.equals(ConfigPolicy.JSON_CONFIG) || id.contains("Firewall")) { - filename = filename + ".json"; - } - if (id.equals(ConfigPolicy.XML_CONFIG)) { - filename = filename + ".xml"; - } - if (id.equals(ConfigPolicy.PROPERTIES_CONFIG)) { - filename = filename + ".properties"; - } - if (id.equals(ConfigPolicy.OTHER_CONFIG)) { - filename = filename + ".txt"; - } - } - return filename; - } - - public String[] getNameScopeAndVersionFromPdpPolicy(String fileName) { - String[] splitByDots = fileName.split("\\."); - if (splitByDots.length < 3) { - return null; - } - String policyName = splitByDots[splitByDots.length - 3]; - String version = splitByDots[splitByDots.length - 2]; - // policy names now include version - String scope = ""; - for (int i = 0; i < splitByDots.length - 3; i++) { - scope += ".".concat(splitByDots[i]); - } - // remove the first dot - if (scope.length() > 0) { - scope = scope.substring(1); - } - String[] returnArray = new String[3]; - returnArray[0] = policyName + "." + version + ".xml"; - returnArray[2] = version; - returnArray[1] = scope; - return returnArray; - } - - public static String createNewPDPGroupId(String name) { - String id = name; - // replace "bad" characters with sequences that will be ok for file - // names and properties keys. - id = id.replace(" ", "_sp_"); - id = id.replace("\t", "_tab_"); - id = id.replace("\\", "_bksl_"); - id = id.replace("/", "_sl_"); - id = id.replace(":", "_col_"); - id = id.replace("*", "_ast_"); - id = id.replace("?", "_q_"); - id = id.replace("\"", "_quo_"); - id = id.replace("<", "_lt_"); - id = id.replace(">", "_gt_"); - id = id.replace("|", "_bar_"); - id = id.replace("=", "_eq_"); - id = id.replace(",", "_com_"); - id = id.replace(";", "_scom_"); - - return id; - } - - /** - * Checks if any of the given strings are empty or null - * - * @param strings One or more Strings (or nulls) to check if they are null or empty - * @return true if one or more of the given strings are empty or null - */ - public static boolean isNullOrEmpty(String... strings) { - for (String s : strings) { - if (s == null || "".equals(s)) { - return true; - } - } - return false; - } - - public List getOtherServers() { - return otherServers; - } - - public void setOtherServers(List otherServers) { - this.otherServers = otherServers; - } - - public PAPPolicyEngine getPapEngine() { - return papEngine; - } - - public static boolean isJunit() { - return isJunit; - } - - public static void setJunit(boolean isJunit) { - PolicyDBDao.isJunit = isJunit; - } - - public static PolicyDBDaoTestClass getPolicyDBDaoTestClass() { - return new PolicyDBDao().new PolicyDBDaoTestClass(); - } - - final class PolicyDBDaoTestClass { - String getConfigFile(String filename, String scope, PolicyRestAdapter policy) { - return scope + "." + PolicyDBDao.this.getConfigFile(filename, policy); - } - - String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) throws PolicyDBException { - return PolicyDBDao.this.getPolicyNameAndVersionFromPolicyFileName(originalPolicyName); - } - - String[] getNameScopeAndVersionFromPdpPolicy(String fileName) { - return PolicyDBDao.this.getNameScopeAndVersionFromPdpPolicy(fileName); - } - - String getPdpPolicyName(String name, String scope) { - return PolicyDBDao.this.getPdpPolicyName(name, scope); - } - } - -} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTransaction.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTransaction.java deleted file mode 100644 index 250029a89..000000000 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTransaction.java +++ /dev/null @@ -1,197 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP-PAP-REST - * ================================================================================ - * 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. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.pap.xacml.rest.components; - -import com.att.research.xacml.api.pap.PAPException; - -import java.util.List; - -import javax.persistence.PersistenceException; - -import org.onap.policy.rest.dao.PolicyDBException; -import org.onap.policy.rest.jpa.GroupEntity; -import org.onap.policy.rest.jpa.PdpEntity; -import org.onap.policy.xacml.api.pap.OnapPDP; -import org.onap.policy.xacml.api.pap.OnapPDPGroup; -import org.onap.policy.xacml.std.pap.StdPDPGroup; - -public interface PolicyDBDaoTransaction { - - /** - * Commits (makes permanent) the current transaction. Also, notifies other PolicyDBDao instances on other PAP - * servers of the update. - * - * @throws IllegalStateException if the PolicyDBDao transaction has not been used or has been committed already. - * @throws PersistenceException if the commit fails for some reason - */ - public void commitTransaction(); - - /** - * Create or update a policy - * - * @param policy A Policy object representing the policy to store or update - * @param username A string of the username you want to be stored for doing this operation - * @throws IllegalStateException If a transaction is open that has not yet been committed - * @throws PersistenceException If a database error occurs - * @throws IllegalArgumentException If the Policy's PolicyRestAdapter contains incorrect data. - */ - public void createPolicy(Policy policy, String username) throws PolicyDBException; - - /** - * Check if the PolicyDBDaoTransaction is currently open - * - * @return False if the PolicyDBDao transaction has not been used or has been committed already, true if it is open. - */ - public boolean isTransactionOpen(); - - /** - * Rollback (undo) the current transaction. - */ - public void rollbackTransaction(); - - /** - * Close the PolicyDBDaoTransaction without rolling back or doing anything. Just used to close the Hibernate - * session. - */ - public void close(); - - /** - * Create a new PDP group in the database - * - * @param groupID The ID to name the new group (use PolicyDBDao.createNewPDPGroupId) - * @param groupName The name to use for the new group - * @param groupDescription Description of the new group (optional) - * @param username Username of the user performing the operation - * @throws IllegalArgumentException If non-optional parameters are null or empty strings - * @throws IllegalStateException If a transaction is already open - * @throws PersistenceException If a database error occurs - */ - public void createGroup(String groupID, String groupName, String groupDescription, String username) - throws PolicyDBException; - - /** - * Updates a group in the database with a new name of description - * - * @param group The group with updated information. The id must match an existing group, but the name and - * description can be changed. - * @param username Username of the user performing the operation - * @param userId needed to store user information in policyAuditlog table during transaction. - * @throws IllegalArgumentException If non-optional parameters are null or empty strings - * @throws IllegalStateException If a transaction is already open - * @throws PersistenceException If a database error occurs or if the group can not be found - */ - public void updateGroup(OnapPDPGroup group, String requestType, String userId) throws PolicyDBException; - - /** - * Updates a PDP in the database with new information - * - * @param pdp The PDP to update - * @param username Username of the user performing the operation - * @throws IllegalArgumentException If non-optional parameters are null or empty strings - * @throws IllegalStateException If a transaction is already open - * @throws PersistenceException If a database error occurs or if the pdp can not be found - */ - public void updatePdp(OnapPDP pdp, String username) throws PolicyDBException; - - /** - * Change the default group in the database to the group provided. - * - * @param group The new group which should be set as default in the database - * @param username Username of the user performing the operation - * @throws IllegalArgumentException If non-optional parameters are null or empty strings - * @throws IllegalStateException If a transaction is already open - * @throws PersistenceException If a database error occurs - */ - public void changeDefaultGroup(OnapPDPGroup group, String username) throws PolicyDBException; - - /** - * Moves a PDP to a new group. - * - * @param pdp The PDP which is to be moved to a new group - * @param group The new group which the PDP should be added to - * @param username Username of the user performing the operation - * @throws IllegalArgumentException If non-optional parameters are null or empty strings - * @throws IllegalStateException If a transaction is already open - * @throws PersistenceException If a database error occurs - */ - public void movePdp(OnapPDP pdp, OnapPDPGroup group, String username) throws PolicyDBException; - - /** - * Add a new PDP to an existing group - * - * @param pdpID The ID to name the new PDP - * @param groupID The ID of the existing group to add the PDP to - * @param pdpName The name to use for the new PDP - * @param pdpDescription Description of the new PDP (optional) - * @param pdpJmxPort - * @param username Username of the user performing the operation - * @throws IllegalArgumentException If non-optional parameters are null or empty strings - * @throws IllegalStateException If a transaction is already open - * @throws PersistenceException If a database error occurs - */ - public void addPdpToGroup(String pdpID, String groupID, String pdpName, String pdpDescription, int pdpJmxPort, - String username) throws PolicyDBException; - - /** - * Add an existing policy to an existing group - * - * @param group The ID of the existing group to add the policy to - * @param policyID The ID of an existing policy - * @return - * @throws IllegalArgumentException If non-optional parameters are null or empty strings - * @throws IllegalStateException If a transaction is already open - * @throws PersistenceException If a database error occurs - * @throws PolicyDBException - */ - public StdPDPGroup addPolicyToGroup(String group, String policyID, String requestType, String username) - throws PolicyDBException; - - /** - * Delete an existing PDP groupPolicyDBException - * - * @param group A PDPGroup object representing the group to delete - * @param moveToGroup A PDPGroup object representing another existing group which PDPs in the group being deleted - * should be moved to - * @throws IllegalArgumentException If non-optional parameters are null or empty strings - * @throws IllegalStateException If a transaction is already open - * @throws PersistenceException If a database error occurs - * @throws PAPException If an error relating to how groups are handled occurs - */ - public void deleteGroup(OnapPDPGroup group, OnapPDPGroup moveToGroup, String username) throws PolicyDBException; - - /** - * Removes an existing PDP from its group and deletes it. - * - * @param pdpID The ID of the existing PDP which should be deleted - * @throws IllegalArgumentException If non-optional parameters are null or empty strings - * @throws IllegalStateException If a transaction is already open - * @throws PersistenceException If a database error occurs - */ - public void removePdpFromGroup(String pdpID, String username) throws PolicyDBException; - - public GroupEntity getGroup(long groupKey); - - public GroupEntity getGroup(String groupId); - - public List getPdpsInGroup(long groupKey); - - public PdpEntity getPdp(long pdpKey); -} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDao.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDao.java new file mode 100644 index 000000000..e0db53e8b --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDao.java @@ -0,0 +1,993 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. + * ================================================================================ + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.xacml.rest.components; + +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.att.research.xacml.util.XACMLProperties; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import javax.persistence.PersistenceException; + +import org.apache.commons.io.FilenameUtils; +import org.hibernate.Criteria; +import org.hibernate.LockMode; +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.criterion.Restrictions; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +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.adapter.PolicyRestAdapter; +import org.onap.policy.rest.dao.PolicyDbException; +import org.onap.policy.rest.jpa.ActionBodyEntity; +import org.onap.policy.rest.jpa.ConfigurationDataEntity; +import org.onap.policy.rest.jpa.DatabaseLockEntity; +import org.onap.policy.rest.jpa.GroupEntity; +import org.onap.policy.rest.jpa.PdpEntity; +import org.onap.policy.rest.jpa.PolicyDBDaoEntity; +import org.onap.policy.rest.jpa.PolicyEntity; +import org.onap.policy.utils.PeCryptoUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.api.pap.OnapPDP; +import org.onap.policy.xacml.api.pap.OnapPDPGroup; +import org.onap.policy.xacml.api.pap.PAPPolicyEngine; +import org.onap.policy.xacml.std.pap.StdPDPGroup; +import org.onap.policy.xacml.std.pap.StdPDPPolicy; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** + * The Class PolicyDbDao. + */ +@Component +public class PolicyDbDao { + private static final Logger logger = FlexLogger.getLogger(PolicyDbDao.class); + public static final String JSON_CONFIG = "JSON"; + public static final String XML_CONFIG = "XML"; + public static final String PROPERTIES_CONFIG = "PROPERTIES"; + public static final String OTHER_CONFIG = "OTHER"; + public static final String AUDIT_USER = "audit"; + + public static final String CONFIG = "Config"; + public static final String ACTION = "Action"; + public static final String GROUP_ID = "groupId"; + public static final String DELETED = "deleted"; + public static final String GROUPENTITY_SELECT = + "SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"; + public static final String PDPENTITY_SELECT = + "SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted"; + public static final String GROUP_NOT_FOUND = "The group could not be found with id "; + public static final String FOUND_IN_DB_NOT_DEL = " were found in the database that are not deleted"; + public static final String MORE_THAN_ONE_PDP = "Somehow, more than one pdp with the same id "; + public static final String DELETED_STATUS_FOUND = " and deleted status were found in the database"; + public static final String DUPLICATE_GROUPID = "Somehow, more than one group with the same id "; + public static final String PDP_ID = "pdpId"; + public static final String QUERY_FAILED_FOR_GROUP = "Query failed trying to check for existing group"; + public static final String QUERY_FAILED_GET_GROUP = "Query failed trying to get group "; + public static final String SCOPE = "scope"; + public static final String POLICYDBDAO_VAR = "PolicyDBDao"; + public static final String DUP_POLICYID = "Somehow, more than one policy with the id "; + public static final String FOUND_IN_DB = " were found in the database"; + + private static final String AUDIT_STR = "Audit"; + + private static PolicyDbDao currentInstance = null; + private static boolean isJunit = false; + private static SessionFactory sessionfactory; + private List otherServers; + private PAPPolicyEngine papEngine; + + /** + * Gets the current instance of PolicyDBDao. + * + * @return The instance of PolicyDBDao or throws exception if the given instance is null. + * @throws IllegalStateException if a PolicyDBDao instance is null. Call createPolicyDBDaoInstance + * (EntityManagerFactory emf) to get this. + */ + public static PolicyDbDao getPolicyDbDaoInstance() { + logger.debug("getPolicyDBDaoInstance() as getPolicyDBDaoInstance() called"); + if (currentInstance != null) { + return currentInstance; + } else { + currentInstance = new PolicyDbDao("init"); + } + return currentInstance; + } + + /** + * Sets the pap engine. + * + * @param papEngine2 the new pap engine + */ + public void setPapEngine(PAPPolicyEngine papEngine2) { + this.papEngine = papEngine2; + } + + /** + * Instantiates a new policy db dao. + * + * @param sessionFactory the session factory + */ + @Autowired + public PolicyDbDao(SessionFactory sessionFactory) { + PolicyDbDao.sessionfactory = sessionFactory; + } + + /** + * Instantiates a new policy db dao. + */ + public PolicyDbDao() { + // Default Constructor + } + + /** + * Initialize the DAO. + * + * @param init initiation parameters + */ + public PolicyDbDao(String init) { + // not needed in this release + if (!register()) { + PolicyLogger + .error("This server's PolicyDBDao instance could not be registered and may not reveive updates"); + } + + otherServers = getRemotePolicyDbDaoList(); + if (logger.isDebugEnabled()) { + logger.debug("Number of remote PolicyDBDao instances: " + otherServers.size()); + } + if (otherServers.isEmpty()) { + logger.warn("List of PolicyDBDao servers is empty or could not be retrieved"); + } + } + + /** + * Start a synchronized transaction. + * + *

Not static because we are going to be using the instance's emf waitTime in ms to wait for lock, or -1 to wait + * forever (no) + * + * @param session the session + * @param waitTime the wait time + */ + @SuppressWarnings("deprecation") + public void startTransactionSynced(Session session, int waitTime) { + logger.debug("\n\nstartTransactionSynced(Hibernate Session,int waitTime) as " + "\n startTransactionSynced(" + + session + "," + waitTime + ") called\n\n"); + DatabaseLockEntity lock = null; + session.beginTransaction(); + try { + if (logger.isDebugEnabled()) { + logger.debug("\n\nstartTransactionSynced():" + "\n ATTEMPT to get the DB lock" + "\n\n"); + } + lock = (DatabaseLockEntity) session.get(DatabaseLockEntity.class, 1, LockMode.PESSIMISTIC_WRITE); + if (logger.isDebugEnabled()) { + logger.debug("\n\nstartTransactionSynced():" + "\n GOT the DB lock" + "\n\n"); + } + } catch (Exception e) { + logger.error("Exception Occured" + e); + } + if (lock == null) { + throw new IllegalStateException( + "The lock row does not exist in the table. Please create a primary key with value = 1."); + } + + } + + /** + * Gets the list of other registered PolicyDBDaos from the database. + * + * @return List (type PolicyDBDaoEntity) of other PolicyDBDaos + */ + private List getRemotePolicyDbDaoList() { + logger.debug("getRemotePolicyDBDaoList() as getRemotePolicyDBDaoList() called"); + List policyDbDaoEntityList = new LinkedList<>(); + Session session = sessionfactory.openSession(); + try { + Criteria cr = session.createCriteria(PolicyDBDaoEntity.class); + policyDbDaoEntityList = cr.list(); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, + "Exception querying for other registered PolicyDBDaos"); + logger.warn("List of remote PolicyDBDaos will be empty", e); + } finally { + try { + session.close(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e); + } + } + return policyDbDaoEntityList; + } + + /** + * Gets the new transaction. + * + * @return the new transaction + */ + public PolicyDbDaoTransaction getNewTransaction() { + logger.debug("getNewTransaction() as getNewTransaction() called"); + return new PolicyDbDaoTransactionInstance("init"); + } + + /** + * Get a new audit transaction. + * + *

Because the normal transactions are not used in audits, we can use the same transaction mechanism to get a + * transaction and obtain the emlock and the DB lock. We just need to provide different transaction timeout values + * in ms because the audit will run longer than normal transactions. + * + * @return the new audit transaction + */ + public PolicyDbDaoTransaction getNewAuditTransaction() { + logger.debug("getNewAuditTransaction() as getNewAuditTransaction() called"); + // Use the standard transaction wait time in ms + int auditWaitMs = Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_TRANS_WAIT)); + // Use the (extended) audit timeout time in ms + int auditTimeoutMs = Integer.parseInt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_AUDIT_TIMEOUT)); + return new PolicyDbDaoTransactionInstance(auditTimeoutMs, auditWaitMs); + } + + /** + * Checks if two strings are equal. Null strings ARE allowed. + * + * @param one A String or null to compare + * @param two A String or null to compare + * @return true, if successful + */ + public static boolean stringEquals(String one, String two) { + logger.debug("stringEquals(String one, String two) as stringEquals(" + one + ", " + two + ") called"); + if (one == null && two == null) { + return true; + } + if (one == null || two == null) { + return false; + } + return one.equals(two); + } + + /** + * Returns the url of this local pap server, removing the username and password, if they are present. + * + * @return The url of this local pap server + */ + public String[] getPapUrlUserPass() { + logger.debug("getPapUrl() as getPapUrl() called"); + String url = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URL); + if (url == null) { + return null; + } + return splitPapUrlUserPass(url); + } + + /** + * Split the user and password of a PAP URL. + * + * @param url the URL + * @return the user and password + */ + public String[] splitPapUrlUserPass(String url) { + String[] urlUserPass = new String[3]; + String[] commaSplit = url.split(","); + urlUserPass[0] = commaSplit[0]; + if (commaSplit.length > 2) { + urlUserPass[1] = commaSplit[1]; + urlUserPass[2] = commaSplit[2]; + } + if (urlUserPass[1] == null || "".equals(urlUserPass[1])) { + String usernamePropertyValue = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_USERID); + if (usernamePropertyValue != null) { + urlUserPass[1] = usernamePropertyValue; + } + } + if (urlUserPass[2] == null || "".equals(urlUserPass[2])) { + String passwordPropertyValue = + PeCryptoUtils.decrypt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_PASS)); + if (passwordPropertyValue != null) { + urlUserPass[2] = passwordPropertyValue; + } + } + // if there is no comma, for some reason there is no user name and + // password, so don't try to cut them off + return urlUserPass; + } + + /** + * Register the PolicyDBDao instance in the PolicyDBDaoEntity table. + * + * @return Boolean, were we able to register? + */ + private boolean register() { + logger.debug("register() as register() called"); + String[] url = getPapUrlUserPass(); + // --- check URL length + if (url == null || url.length < 3) { + return false; + } + Session session = sessionfactory.openSession(); + try { + startTransactionSynced(session, 1000); + } catch (IllegalStateException e) { + logger.debug("\nPolicyDBDao.register() caught an IllegalStateException: \n" + e + "\n"); + DatabaseLockEntity lock; + lock = (DatabaseLockEntity) session.get(DatabaseLockEntity.class, 1); + if (lock == null) { + lock = new DatabaseLockEntity(); + lock.setKey(1); + try { + session.persist(lock); + session.flush(); + session.getTransaction().commit(); + session.close(); + } catch (Exception e2) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, POLICYDBDAO_VAR, + "COULD NOT CREATE DATABASELOCK ROW. WILL TRY ONE MORE TIME"); + } + + session = sessionfactory.openSession(); + try { + startTransactionSynced(session, 1000); + } catch (Exception e3) { + String msg = "DATABASE LOCKING NOT WORKING. CONCURRENCY CONTROL NOT WORKING"; + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e3, POLICYDBDAO_VAR, msg); + throw new IllegalStateException("msg" + "\n" + e3); + } + } + } + logger.debug("\nPolicyDBDao.register. Database locking and concurrency control is initialized\n"); + PolicyDBDaoEntity foundPolicyDbDaoEntity = null; + Criteria cr = session.createCriteria(PolicyDBDaoEntity.class); + cr.add(Restrictions.eq("policyDBDaoUrl", url[0])); + List data = cr.list(); + if (!data.isEmpty()) { + foundPolicyDbDaoEntity = (PolicyDBDaoEntity) data.get(0); + } + + // encrypt the password + String txt = PeCryptoUtils.encrypt(url[2]); + if (foundPolicyDbDaoEntity == null) { + PolicyDBDaoEntity newPolicyDbDaoEntity = new PolicyDBDaoEntity(); + newPolicyDbDaoEntity.setPolicyDBDaoUrl(url[0]); + newPolicyDbDaoEntity.setDescription("PAP server at " + url[0]); + newPolicyDbDaoEntity.setUsername(url[1]); + newPolicyDbDaoEntity.setPassword(txt); + try { + session.persist(newPolicyDbDaoEntity); + session.getTransaction().commit(); + } catch (Exception e) { + logger.debug(e); + try { + session.getTransaction().rollback(); + } catch (Exception e2) { + logger.debug(e2); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, POLICYDBDAO_VAR, + "Could not add new PolicyDBDao to the database"); + } + } + } else { + // just want to update in order to change modified date + if (url[1] != null && !stringEquals(url[1], foundPolicyDbDaoEntity.getUsername())) { + foundPolicyDbDaoEntity.setUsername(url[1]); + } + if (txt != null && !stringEquals(txt, foundPolicyDbDaoEntity.getPassword())) { + foundPolicyDbDaoEntity.setPassword(txt); + } + foundPolicyDbDaoEntity.preUpdate(); + try { + session.getTransaction().commit(); + } catch (Exception e) { + logger.debug(e); + try { + session.getTransaction().rollback(); + } catch (Exception e2) { + logger.debug(e2); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, POLICYDBDAO_VAR, + "Could not update PolicyDBDao in the database"); + } + } + } + session.close(); + logger.debug("\nPolicyDBDao.register(). Success!!\n"); + return true; + } + + /** + * Synchronize group policies in the fuile system. + * + *

This method is called during all pushPolicy transactions and makes sure the file system group is in sync with + * the database group entity + * + * @param pdpGroup the pdp group + * @param groupentity the groupentity + * @return the std PDP group + * @throws PAPException the PAP exception + * @throws PolicyDbException the policy db exception + */ + public StdPDPGroup synchronizeGroupPoliciesInFileSystem(StdPDPGroup pdpGroup, GroupEntity groupentity) + throws PAPException, PolicyDbException { + + HashMap currentPolicyMap = new HashMap<>(); + HashSet newPolicyIdSet = new HashSet<>(); + HashSet newPolicySet = new HashSet<>(); + + for (PDPPolicy pdpPolicy : pdpGroup.getPolicies()) { + currentPolicyMap.put(pdpPolicy.getId(), pdpPolicy); + } + + for (PolicyEntity policy : groupentity.getPolicies()) { + String pdpPolicyId = getPdpPolicyName(policy.getPolicyName(), policy.getScope()); + newPolicyIdSet.add(pdpPolicyId); + + if (currentPolicyMap.containsKey(pdpPolicyId)) { + newPolicySet.add(currentPolicyMap.get(pdpPolicyId)); + } else { + // convert PolicyEntity object to PDPPolicy + String name = pdpPolicyId.replace(".xml", ""); + name = name.substring(0, name.lastIndexOf('.')); + InputStream policyStream = new ByteArrayInputStream(policy.getPolicyData().getBytes()); + pdpGroup.copyPolicyToFile(pdpPolicyId, name, policyStream); + URI location = Paths.get(pdpGroup.getDirectory().toAbsolutePath().toString(), pdpPolicyId).toUri(); + StdPDPPolicy newPolicy = null; + try { + newPolicy = new StdPDPPolicy(pdpPolicyId, true, + removeExtensionAndVersionFromPolicyName(pdpPolicyId), location); + newPolicySet.add(newPolicy); + logger.info("Adding new policy to PDPGroup - " + newPolicy.getId() + ", Location - " + location); + } catch (Exception e) { + logger.debug(e); + PolicyLogger + .error("PolicyDBDao: Exception occurred while creating the StdPDPPolicy newPolicy object " + + e.getMessage()); + } + } + } + + for (String id : currentPolicyMap.keySet()) { + if (!newPolicyIdSet.contains(id)) { + try { + Files.delete(Paths.get(currentPolicyMap.get(id).getLocation())); + } catch (Exception e) { + logger.debug(e); + PolicyLogger.error( + "PolicyDBDao: Exception occurred while attempting to delete the old version of the policy" + + " file from the group. " + e.getMessage()); + } + } + } + + logger.info("PolicyDBDao: Adding new policy set to group to keep filesystem and DB in sync"); + pdpGroup.setPolicies(newPolicySet); + + return pdpGroup; + } + + /** + * Removes the extension and version from policy name. + * + * @param originalPolicyName the original policy name + * @return the string + * @throws PolicyDbException the policy db exception + */ + public String removeExtensionAndVersionFromPolicyName(String originalPolicyName) throws PolicyDbException { + return getPolicyNameAndVersionFromPolicyFileName(originalPolicyName)[0]; + } + + /** + * Splits apart the policy name and version from a policy file path. + * + * @param originalPolicyName the original policy name + * @return An array [0]: The policy name, [1]: the policy version, as a string + * @throws PolicyDbException the policy db exception + */ + public String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) throws PolicyDbException { + String policyName = originalPolicyName; + String[] nameAndVersion = new String[2]; + try { + policyName = removeFileExtension(policyName); + nameAndVersion[0] = policyName.substring(0, policyName.lastIndexOf('.')); + if (isNullOrEmpty(nameAndVersion[0])) { + throw new PolicyDbException(); + } + } catch (Exception e) { + nameAndVersion[0] = originalPolicyName; + logger.debug(e); + } + try { + nameAndVersion[1] = policyName.substring(policyName.lastIndexOf('.') + 1); + if (isNullOrEmpty(nameAndVersion[1])) { + throw new PolicyDbException(); + } + } catch (Exception e) { + nameAndVersion[1] = "1"; + logger.debug(e); + } + return nameAndVersion; + } + + /** + * Get the PDP policy by name. + * + * @param name The name to get + * @param scope The scope to use + * @return the policy. + */ + public String getPdpPolicyName(String name, String scope) { + String finalName = ""; + finalName += scope; + finalName += "."; + finalName += removeFileExtension(name); + finalName += ".xml"; + return finalName; + } + + private String removeFileExtension(String fileName) { + return fileName.substring(0, fileName.lastIndexOf('.')); + } + + /** + * Audit local database. + * + * @param papEngine2 the pap engine 2 + */ + public void auditLocalDatabase(PAPPolicyEngine papEngine2) { + logger.debug("PolicyDBDao.auditLocalDatabase() is called"); + try { + deleteAllGroupTables(); + auditGroups(papEngine2); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "auditLocalDatabase() error"); + logger.error("Exception Occured" + e); + } + } + + /** + * Audit local file system. + * + * @param group the group + * @return the std PDP group + */ + public StdPDPGroup auditLocalFileSystem(StdPDPGroup group) { + + logger.info("Starting Local File System group audit"); + Session session = sessionfactory.openSession(); + session.getTransaction().begin(); + + StdPDPGroup updatedGroup = null; + try { + Query groupQuery = session.createQuery(GROUPENTITY_SELECT); + groupQuery.setParameter(GROUP_ID, group.getId()); + groupQuery.setParameter(DELETED, false); + List groupQueryList = groupQuery.list(); + if (groupQueryList != null && !groupQueryList.isEmpty()) { + GroupEntity dbgroup = (GroupEntity) groupQueryList.get(0); + updatedGroup = synchronizeGroupPoliciesInFileSystem(group, dbgroup); + logger.info("Group was updated during file system audit: " + updatedGroup.toString()); + } + } catch (PAPException | PolicyDbException e) { + logger.error(e); + } catch (Exception e) { + logger.error(e); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, + "Caught Exception trying to check if group exists groupQuery.getResultList()"); + throw new PersistenceException("Query failed trying to check if group " + group.getId() + " exists"); + } + + session.getTransaction().commit(); + session.close(); + + return updatedGroup; + } + + /** + * Synchronize config data in file system. + */ + public void synchronizeConfigDataInFileSystem() { + + logger.info("Starting Local File System Config data Sync"); + // sync both web apps Config and Action + syncConfigData(ConfigurationDataEntity.class, CONFIG); + syncConfigData(ActionBodyEntity.class, ACTION); + } + + private void syncConfigData(Class cl, String type) { + Session session = sessionfactory.openSession(); + try { + final Criteria configDataQuery = session.createCriteria(cl.getName()); + @SuppressWarnings("unchecked") + final List configDataResult = configDataQuery.list(); + Path webappsPath = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_WEBAPPS), type); + + for (final T configData : configDataResult) { + String configName = null; + byte[] configBody; + try { + if (CONFIG.equalsIgnoreCase(type)) { + configName = ((ConfigurationDataEntity) configData).getConfigurationName(); + configBody = + (((ConfigurationDataEntity) configData).getConfigBody() != null) + ? ((ConfigurationDataEntity) configData).getConfigBody() + .getBytes(StandardCharsets.UTF_8) + : "".getBytes(); + } else { + configName = ((ActionBodyEntity) configData).getActionBodyName(); + configBody = (((ActionBodyEntity) configData).getActionBody() != null) + ? ((ActionBodyEntity) configData).getActionBody().getBytes(StandardCharsets.UTF_8) + : "".getBytes(); + } + Path filePath = Paths.get(webappsPath.toString(), configName); + if (!filePath.toFile().exists()) { + Files.write(filePath, configBody); + logger.info("Created Config File from DB - " + filePath.toString()); + } + } catch (Exception e) { + // log and keep going + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, + "Exception occured while creating Configuration File - " + configName); + } + } + } catch (final Exception exception) { + logger.error("Unable to synchronizeConfigDataInFileSystem", exception); + } + session.close(); + } + + /** + * Delete all group tables. + */ + public void deleteAllGroupTables() { + logger.debug("PolicyDBDao.deleteAllGroupTables() called"); + Session session = sessionfactory.openSession(); + session.getTransaction().begin(); + + Query deletePdpEntityEntityTableUpdate = session.getNamedQuery("PdpEntity.deleteAll"); + deletePdpEntityEntityTableUpdate.executeUpdate(); + + Query deleteGroupEntityTableUpdate = session.getNamedQuery("GroupEntity.deleteAll"); + deleteGroupEntityTableUpdate.executeUpdate(); + + session.getTransaction().commit(); + session.close(); + } + + /** + * Audit groups. + * + * @param papEngine2 the pap engine 2 + */ + @SuppressWarnings("unchecked") + public void auditGroups(PAPPolicyEngine papEngine2) { + logger.debug("PolicyDBDao.auditGroups() called"); + + Session session = sessionfactory.openSession(); + session.getTransaction().begin(); + try { + + Set groups = papEngine2.getOnapPDPGroups(); + + for (OnapPDPGroup grp : groups) { + try { + GroupEntity groupEntity = new GroupEntity(); + groupEntity.setGroupName(grp.getName()); + groupEntity.setDescription(grp.getDescription()); + groupEntity.setDefaultGroup(grp.isDefaultGroup()); + groupEntity.setCreatedBy(AUDIT_STR); + groupEntity.setGroupId(createNewPdpGroupId(grp.getId())); + groupEntity.setModifiedBy(AUDIT_STR); + session.persist(groupEntity); + Set pdps = grp.getOnapPdps(); + + for (OnapPDP pdp : pdps) { + PdpEntity pdpEntity = new PdpEntity(); + pdpEntity.setGroup(groupEntity); + pdpEntity.setJmxPort(pdp.getJmxPort()); + pdpEntity.setPdpId(pdp.getId()); + pdpEntity.setPdpName(pdp.getName()); + pdpEntity.setModifiedBy(AUDIT_STR); + pdpEntity.setCreatedBy(AUDIT_STR); + session.persist(pdpEntity); + } + + Set policies = grp.getPolicies(); + + for (PDPPolicy policy : policies) { + try { + String[] stringArray = getNameScopeAndVersionFromPdpPolicy(policy.getId()); + if (stringArray == null) { + throw new IllegalArgumentException( + "Invalid input - policyID must contain name, scope and version"); + } + List policyEntityList; + Query getPolicyEntitiesQuery = session.getNamedQuery("PolicyEntity.findByNameAndScope"); + getPolicyEntitiesQuery.setParameter("name", stringArray[0]); + getPolicyEntitiesQuery.setParameter(SCOPE, stringArray[1]); + + policyEntityList = getPolicyEntitiesQuery.list(); + PolicyEntity policyEntity = null; + if (!policyEntityList.isEmpty()) { + policyEntity = policyEntityList.get(0); + } + if (policyEntity != null) { + groupEntity.addPolicyToGroup(policyEntity); + } + } catch (Exception e2) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, POLICYDBDAO_VAR, + "Exception auditGroups inner catch"); + } + } + } catch (Exception e1) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, POLICYDBDAO_VAR, + "Exception auditGroups middle catch"); + } + } + } catch (Exception e) { + session.getTransaction().rollback(); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "Exception auditGroups outer catch"); + session.close(); + return; + } + + session.getTransaction().commit(); + session.close(); + + } + + /** + * Gets the config file. + * + * @param filename the filename + * @param policy the policy + * @return the config file + */ + public String getConfigFile(String filename, PolicyRestAdapter policy) { + if (policy == null) { + return getConfigFile(filename, (String) null); + } + return getConfigFile(filename, policy.getConfigType()); + } + + // copied from ConfigPolicy.java and modified + // Here we are adding the extension for the configurations file based on the + /** + * Gets the config file. + * + * @param inputFilename the input filename + * @param configType the config type + * @return the config file + */ + // config type selection for saving. + public String getConfigFile(String inputFilename, String configType) { + String filename = inputFilename; + logger.debug("getConfigFile(String filename, String scope, String configType) as getConfigFile(" + filename + + ", " + configType + ") called"); + filename = FilenameUtils.removeExtension(filename); + String id = configType; + + if (id != null) { + if (id.equals(ConfigPolicy.JSON_CONFIG) || id.contains("Firewall")) { + filename = filename + ".json"; + } + if (id.equals(ConfigPolicy.XML_CONFIG)) { + filename = filename + ".xml"; + } + if (id.equals(ConfigPolicy.PROPERTIES_CONFIG)) { + filename = filename + ".properties"; + } + if (id.equals(ConfigPolicy.OTHER_CONFIG)) { + filename = filename + ".txt"; + } + } + return filename; + } + + /** + * Gets the name scope and version from pdp policy. + * + * @param fileName the file name + * @return the name scope and version from pdp policy + */ + public String[] getNameScopeAndVersionFromPdpPolicy(String fileName) { + String[] splitByDots = fileName.split("\\."); + if (splitByDots.length < 3) { + return null; + } + String policyName = splitByDots[splitByDots.length - 3]; + String version = splitByDots[splitByDots.length - 2]; + // policy names now include version + String scope = ""; + for (int i = 0; i < splitByDots.length - 3; i++) { + scope += ".".concat(splitByDots[i]); + } + // remove the first dot + if (scope.length() > 0) { + scope = scope.substring(1); + } + String[] returnArray = new String[3]; + returnArray[0] = policyName + "." + version + ".xml"; + returnArray[2] = version; + returnArray[1] = scope; + return returnArray; + } + + /** + * Creates the new PDP group id. + * + * @param name the name + * @return the string + */ + public static String createNewPdpGroupId(String name) { + String id = name; + // replace "bad" characters with sequences that will be ok for file + // names and properties keys. + id = id.replace(" ", "_sp_"); + id = id.replace("\t", "_tab_"); + id = id.replace("\\", "_bksl_"); + id = id.replace("/", "_sl_"); + id = id.replace(":", "_col_"); + id = id.replace("*", "_ast_"); + id = id.replace("?", "_q_"); + id = id.replace("\"", "_quo_"); + id = id.replace("<", "_lt_"); + id = id.replace(">", "_gt_"); + id = id.replace("|", "_bar_"); + id = id.replace("=", "_eq_"); + id = id.replace(",", "_com_"); + id = id.replace(";", "_scom_"); + + return id; + } + + /** + * Checks if any of the given strings are empty or null. + * + * @param strings One or more Strings (or nulls) to check if they are null or empty + * @return true if one or more of the given strings are empty or null + */ + public static boolean isNullOrEmpty(String... strings) { + for (String s : strings) { + if (s == null || "".equals(s)) { + return true; + } + } + return false; + } + + /** + * Gets the other servers. + * + * @return the other servers + */ + public List getOtherServers() { + return otherServers; + } + + /** + * Sets the other servers. + * + * @param otherServers the new other servers + */ + public void setOtherServers(List otherServers) { + this.otherServers = otherServers; + } + + /** + * Gets the pap engine. + * + * @return the pap engine + */ + public PAPPolicyEngine getPapEngine() { + return papEngine; + } + + /** + * Checks if is junit. + * + * @return true, if is junit + */ + public static boolean isJunit() { + return isJunit; + } + + /** + * Sets the junit. + * + * @param isJunit the new junit + */ + public static void setJunit(boolean isJunit) { + PolicyDbDao.isJunit = isJunit; + } + + /** + * Gets the policy DB dao test class. + * + * @return the policy DB dao test class + */ + public static PolicyDbDaoTestClass getPolicyDbDaoTestClass() { + return new PolicyDbDao().new PolicyDbDaoTestClass(); + } + + /** + * The Class PolicyDBDaoTestClass. + */ + final class PolicyDbDaoTestClass { + + /** + * Gets the config file. + * + * @param filename the filename + * @param scope the scope + * @param policy the policy + * @return the config file + */ + String getConfigFile(String filename, String scope, PolicyRestAdapter policy) { + return scope + "." + PolicyDbDao.this.getConfigFile(filename, policy); + } + + /** + * Gets the policy name and version from policy file name. + * + * @param originalPolicyName the original policy name + * @return the policy name and version from policy file name + * @throws PolicyDbException the policy db exception + */ + String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) throws PolicyDbException { + return PolicyDbDao.this.getPolicyNameAndVersionFromPolicyFileName(originalPolicyName); + } + + /** + * Gets the name scope and version from pdp policy. + * + * @param fileName the file name + * @return the name scope and version from pdp policy + */ + String[] getNameScopeAndVersionFromPdpPolicy(String fileName) { + return PolicyDbDao.this.getNameScopeAndVersionFromPdpPolicy(fileName); + } + + /** + * Gets the pdp policy name. + * + * @param name the name + * @param scope the scope + * @return the pdp policy name + */ + String getPdpPolicyName(String name, String scope) { + return PolicyDbDao.this.getPdpPolicyName(name, scope); + } + } + +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransaction.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransaction.java new file mode 100644 index 000000000..70ca36ac7 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransaction.java @@ -0,0 +1,194 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * ================================================================================ + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pap.xacml.rest.components; + +import com.att.research.xacml.api.pap.PAPException; + +import java.util.List; + +import javax.persistence.PersistenceException; + +import org.onap.policy.rest.dao.PolicyDbException; +import org.onap.policy.rest.jpa.GroupEntity; +import org.onap.policy.rest.jpa.PdpEntity; +import org.onap.policy.xacml.api.pap.OnapPDP; +import org.onap.policy.xacml.api.pap.OnapPDPGroup; +import org.onap.policy.xacml.std.pap.StdPDPGroup; + +public interface PolicyDbDaoTransaction { + + /** + * Commits (makes permanent) the current transaction. Also, notifies other PolicyDBDao instances on other PAP + * servers of the update. + * + * @throws IllegalStateException if the PolicyDBDao transaction has not been used or has been committed already. + * @throws PersistenceException if the commit fails for some reason + */ + public void commitTransaction(); + + /** + * Create or update a policy. + * + * @param policy A Policy object representing the policy to store or update + * @param username A string of the username you want to be stored for doing this operation + * @throws IllegalStateException If a transaction is open that has not yet been committed + * @throws PersistenceException If a database error occurs + * @throws IllegalArgumentException If the Policy's PolicyRestAdapter contains incorrect data. + */ + public void createPolicy(Policy policy, String username) throws PolicyDbException; + + /** + * Check if the PolicyDBDaoTransaction is currently open. + * + * @return False if the PolicyDBDao transaction has not been used or has been committed already, true if it is open. + */ + public boolean isTransactionOpen(); + + /** + * Rollback (undo) the current transaction. + */ + public void rollbackTransaction(); + + /** + * Close the PolicyDBDaoTransaction without rolling back or doing anything. Just used to close the Hibernate + * session. + */ + public void close(); + + /** + * Create a new PDP group in the database. + * + * @param groupID The ID to name the new group (use PolicyDBDao.createNewPDPGroupId) + * @param groupName The name to use for the new group + * @param groupDescription Description of the new group (optional) + * @param username Username of the user performing the operation + * @throws IllegalArgumentException If non-optional parameters are null or empty strings + * @throws IllegalStateException If a transaction is already open + * @throws PersistenceException If a database error occurs + */ + public void createGroup(String groupID, String groupName, String groupDescription, String username) + throws PolicyDbException; + + /** + * Updates a group in the database with a new name of description. + * + * @param group The group with updated information. The id must match an existing group, but the name and + * description can be changed. + * @param userId needed to store user information in policyAuditlog table during transaction. + * @throws IllegalArgumentException If non-optional parameters are null or empty strings + * @throws IllegalStateException If a transaction is already open + * @throws PersistenceException If a database error occurs or if the group can not be found + */ + public void updateGroup(OnapPDPGroup group, String requestType, String userId) throws PolicyDbException; + + /** + * Updates a PDP in the database with new information. + * + * @param pdp The PDP to update + * @param username Username of the user performing the operation + * @throws IllegalArgumentException If non-optional parameters are null or empty strings + * @throws IllegalStateException If a transaction is already open + * @throws PersistenceException If a database error occurs or if the pdp can not be found + */ + public void updatePdp(OnapPDP pdp, String username) throws PolicyDbException; + + /** + * Change the default group in the database to the group provided. + * + * @param group The new group which should be set as default in the database + * @param username Username of the user performing the operation + * @throws IllegalArgumentException If non-optional parameters are null or empty strings + * @throws IllegalStateException If a transaction is already open + * @throws PersistenceException If a database error occurs + */ + public void changeDefaultGroup(OnapPDPGroup group, String username) throws PolicyDbException; + + /** + * Moves a PDP to a new group. + * + * @param pdp The PDP which is to be moved to a new group + * @param group The new group which the PDP should be added to + * @param username Username of the user performing the operation + * @throws IllegalArgumentException If non-optional parameters are null or empty strings + * @throws IllegalStateException If a transaction is already open + * @throws PersistenceException If a database error occurs + */ + public void movePdp(OnapPDP pdp, OnapPDPGroup group, String username) throws PolicyDbException; + + /** + * Add a new PDP to an existing group. + * + * @param pdpID The ID to name the new PDP + * @param groupID The ID of the existing group to add the PDP to + * @param pdpName The name to use for the new PDP + * @param pdpDescription Description of the new PDP (optional) + * @param pdpJmxPort PDP JMX port + * @param username Username of the user performing the operation + * @throws IllegalArgumentException If non-optional parameters are null or empty strings + * @throws IllegalStateException If a transaction is already open + * @throws PersistenceException If a database error occurs + */ + public void addPdpToGroup(String pdpID, String groupID, String pdpName, String pdpDescription, int pdpJmxPort, + String username) throws PolicyDbException; + + /** + * Add an existing policy to an existing group. + * + * @param group The ID of the existing group to add the policy to + * @param policyID The ID of an existing policy + * @return the PDP groups + * @throws PolicyDbException on DB exceptions + */ + public StdPDPGroup addPolicyToGroup(String group, String policyID, String requestType, String username) + throws PolicyDbException; + + /** + * Delete an existing PDP groupPolicyDBException. + * + * @param group A PDPGroup object representing the group to delete + * @param moveToGroup A PDPGroup object representing another existing group which PDPs in the group being deleted + * should be moved to + * @throws IllegalArgumentException If non-optional parameters are null or empty strings + * @throws IllegalStateException If a transaction is already open + * @throws PersistenceException If a database error occurs + * @throws PAPException If an error relating to how groups are handled occurs + */ + public void deleteGroup(OnapPDPGroup group, OnapPDPGroup moveToGroup, String username) throws PolicyDbException; + + /** + * Removes an existing PDP from its group and deletes it. + * + * @param pdpID The ID of the existing PDP which should be deleted + * @throws IllegalArgumentException If non-optional parameters are null or empty strings + * @throws IllegalStateException If a transaction is already open + * @throws PersistenceException If a database error occurs + */ + public void removePdpFromGroup(String pdpID, String username) throws PolicyDbException; + + public GroupEntity getGroup(long groupKey); + + public GroupEntity getGroup(String groupId); + + public List getPdpsInGroup(long groupKey); + + public PdpEntity getPdp(long pdpKey); +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransactionInstance.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransactionInstance.java index daa2d6b5d..882169a34 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransactionInstance.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransactionInstance.java @@ -3,6 +3,7 @@ * ONAP-PAP-REST * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,7 +60,7 @@ 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.adapter.PolicyRestAdapter; -import org.onap.policy.rest.dao.PolicyDBException; +import org.onap.policy.rest.dao.PolicyDbException; import org.onap.policy.rest.jpa.ActionBodyEntity; import org.onap.policy.rest.jpa.ConfigurationDataEntity; import org.onap.policy.rest.jpa.GroupEntity; @@ -76,10 +77,15 @@ import org.w3c.dom.Document; import org.xml.sax.InputSource; @Component -public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { - +public class PolicyDbDaoTransactionInstance implements PolicyDbDaoTransaction { private static final Logger logger = FlexLogger.getLogger(PolicyDbDaoTransactionInstance.class); + // Recurring constants + private static final String BRACKET_CALLED = ") called"; + private static final String EXISTS = " exists"; + private static final String GROUP = "group"; + private static final String CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS = "Caught Exception on notifyOthers("; + private final Object emLock = new Object(); long policyId; long groupId; @@ -89,7 +95,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { private Thread transactionTimer; private static final String POLICY_NOTIFICATION = "policy"; private static final String PDP_NOTIFICATION = "pdp"; - private static final String GROUP_NOTIFICATION = "group"; + private static final String GROUP_NOTIFICATION = GROUP; private static final String DECISIONMS_MODEL = "MicroService_Model"; private static boolean isJunit = false; @@ -135,7 +141,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { synchronized (emLock) { session = sessionfactory.openSession(); try { - PolicyDBDao.getPolicyDBDaoInstance().startTransactionSynced(session, transactionWaitTime); + PolicyDbDao.getPolicyDbDaoInstance().startTransactionSynced(session, transactionWaitTime); } catch (Exception e) { logger.error("Could not lock transaction within " + transactionWaitTime + " milliseconds" + e); throw new PersistenceException( @@ -222,7 +228,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { try { session.getTransaction().commit(); } catch (RollbackException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught RollbackException on em.getTransaction().commit()"); throw new PersistenceException("The commit failed. Message:\n" + e.getMessage()); } @@ -233,16 +239,16 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { try { otherPaps.notifyOthers(policyId, POLICY_NOTIFICATION, newGroupId); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, - "Caught Exception on notifyOthers(" + policyId + "," + POLICY_NOTIFICATION + "," + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, + CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS + policyId + "," + POLICY_NOTIFICATION + "," + newGroupId + ")"); } } else { try { otherPaps.notifyOthers(policyId, POLICY_NOTIFICATION); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, - "Caught Exception on notifyOthers(" + policyId + "," + POLICY_NOTIFICATION + ")"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, + CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS + policyId + "," + POLICY_NOTIFICATION + ")"); } } } @@ -252,16 +258,16 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { try { otherPaps.notifyOthers(groupId, GROUP_NOTIFICATION, newGroupId); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, - "Caught Exception on notifyOthers(" + groupId + "," + GROUP_NOTIFICATION + "," + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, + CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS + groupId + "," + GROUP_NOTIFICATION + "," + newGroupId + ")"); } } else { try { otherPaps.notifyOthers(groupId, GROUP_NOTIFICATION); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, - "Caught Exception on notifyOthers(" + groupId + "," + GROUP_NOTIFICATION + ")"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, + CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS + groupId + "," + GROUP_NOTIFICATION + ")"); } } } @@ -270,8 +276,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { try { otherPaps.notifyOthers(pdpId, PDP_NOTIFICATION); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, - "Caught Exception on notifyOthers(" + pdpId + "," + PDP_NOTIFICATION + ")"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, + CAUGHT_EXCEPTION_ON_NOTIFY_OTHERS + pdpId + "," + PDP_NOTIFICATION + ")"); } } } @@ -288,13 +294,13 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { try { session.getTransaction().rollback(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Could not rollback transaction"); } try { session.close(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Could not close Hibernate Session."); } @@ -318,7 +324,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { + " String policyName, String policyDataString) as createPolicy(" + policy + ", " + username + ", " + policyScope + ", " + policyName + ", " + policyDataString + ") called"); synchronized (emLock) { - PolicyDBDao policyDbDao = new PolicyDBDao(); + PolicyDbDao policyDbDao = new PolicyDbDao(); checkBeforeOperationRun(); String configName = policyName; if (policyName.contains("Config_")) { @@ -333,7 +339,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { policyName = policyName.split(":")[1]; Query createPolicyQuery = session .createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName"); - createPolicyQuery.setParameter(PolicyDBDao.SCOPE, policyScope); + createPolicyQuery.setParameter(PolicyDbDao.SCOPE, policyScope); createPolicyQuery.setParameter("policyName", policyName); List createPolicyQueryList = createPolicyQuery.list(); PolicyEntity newPolicyEntity; @@ -352,7 +358,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } ActionBodyEntity newActionBodyEntity = null; - if (policy.getPolicyType().equals(PolicyDBDao.ACTION)) { + if (policy.getPolicyType().equals(PolicyDbDao.ACTION)) { boolean abupdate = false; if (newPolicyEntity.getActionBodyEntity() == null) { newActionBodyEntity = new ActionBodyEntity(); @@ -411,7 +417,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } ConfigurationDataEntity newConfigurationDataEntity; - if (PolicyDBDao.CONFIG.equals(policy.getPolicyType()) + if (PolicyDbDao.CONFIG.equals(policy.getPolicyType()) || DECISIONMS_MODEL.equals(policy.getRuleProvider())) { boolean configUpdate; if (newPolicyEntity.getConfigurationData() == null) { @@ -424,7 +430,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } if (newConfigurationDataEntity != null) { - if (!PolicyDBDao.stringEquals(newConfigurationDataEntity.getConfigurationName(), + if (!PolicyDbDao.stringEquals(newConfigurationDataEntity.getConfigurationName(), policyDbDao.getConfigFile(configName, policy))) { newConfigurationDataEntity.setConfigurationName(policyDbDao.getConfigFile(configName, policy)); } @@ -479,22 +485,22 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } policyId = newPolicyEntity.getPolicyId(); - if (!PolicyDBDao.stringEquals(newPolicyEntity.getPolicyName(), policyName)) { + if (!PolicyDbDao.stringEquals(newPolicyEntity.getPolicyName(), policyName)) { newPolicyEntity.setPolicyName(policyName); } - if (!PolicyDBDao.stringEquals(newPolicyEntity.getCreatedBy(), username)) { + if (!PolicyDbDao.stringEquals(newPolicyEntity.getCreatedBy(), username)) { newPolicyEntity.setCreatedBy(username); } - if (!PolicyDBDao.stringEquals(newPolicyEntity.getDescription(), policy.getPolicyDescription())) { + if (!PolicyDbDao.stringEquals(newPolicyEntity.getDescription(), policy.getPolicyDescription())) { newPolicyEntity.setDescription(policy.getPolicyDescription()); } - if (!PolicyDBDao.stringEquals(newPolicyEntity.getModifiedBy(), username)) { + if (!PolicyDbDao.stringEquals(newPolicyEntity.getModifiedBy(), username)) { newPolicyEntity.setModifiedBy(username); } - if (!PolicyDBDao.stringEquals(newPolicyEntity.getPolicyData(), policyDataString)) { + if (!PolicyDbDao.stringEquals(newPolicyEntity.getPolicyData(), policyDataString)) { newPolicyEntity.setPolicyData(policyDataString); } - if (!PolicyDBDao.stringEquals(newPolicyEntity.getScope(), policyScope)) { + if (!PolicyDbDao.stringEquals(newPolicyEntity.getScope(), policyScope)) { newPolicyEntity.setScope(policyScope); } if (newPolicyEntity.isDeleted()) { @@ -519,7 +525,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { InputStream policyXmlStream = null; try { logger.debug("createPolicy(PolicyRestAdapter policy, String username) as createPolicy(" + policy + "," - + username + ") called"); + + username + BRACKET_CALLED); String policyScope = policy.policyAdapter.getDomainDir().replace(File.separator, "."); // Does not need to be XACMLPolicyWriterWithPapNotify since it is // already in the PAP @@ -536,22 +542,23 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { policyDataString = IOUtils.toString(policyXmlStream); } catch (IOException e) { policyDataString = "could not read"; - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught IOException on IOUtils.toString(" + policyXmlStream + ")"); throw new IllegalArgumentException("Cannot parse the policy xml from the PolicyRestAdapter."); } IOUtils.closeQuietly(policyXmlStream); - if (PolicyDBDao.isJunit()) { + if (PolicyDbDao.isJunit()) { // Using parentPath object to set policy data. policyDataString = policy.policyAdapter.getParentPath(); } String configPath = ""; - if (PolicyDBDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) { + if (PolicyDbDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) { configPath = evaluateXPath( - "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'ID')]/AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()", + "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'ID')]/" + + "AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()", policyDataString); - } else if (PolicyDBDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) { + } else if (PolicyDbDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) { configPath = evaluateXPath( "/Policy/Rule/ObligationExpressions/ObligationExpression[contains(@ObligationId, " + policy.policyAdapter.getActionAttribute() @@ -559,16 +566,17 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { policyDataString); } else if (DECISIONMS_MODEL.equalsIgnoreCase(policy.policyAdapter.getRuleProvider())) { configPath = evaluateXPath( - "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'MicroService')]/AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()", + "/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'MicroService')]/" + + "AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()", policyDataString); } String prefix = null; - if (PolicyDBDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType()) + if (PolicyDbDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType()) || DECISIONMS_MODEL.equalsIgnoreCase(policy.policyAdapter.getRuleProvider())) { prefix = configPath.substring(configPath.indexOf(policyScope + ".") + policyScope.concat(".").length(), configPath.lastIndexOf(policy.policyAdapter.getPolicyName())); - if (PolicyDBDao.isNullOrEmpty(policy.policyAdapter.getConfigBodyData())) { + if (PolicyDbDao.isNullOrEmpty(policy.policyAdapter.getConfigBodyData())) { String configData = ""; try { String newConfigPath = configPath; @@ -583,7 +591,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } policy.policyAdapter.setConfigBodyData(configData); } - } else if (PolicyDBDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) { + } else if (PolicyDbDao.ACTION.equalsIgnoreCase(policy.policyAdapter.getPolicyType())) { prefix = "Action_"; } else if ("Decision".equalsIgnoreCase(policy.policyAdapter.getPolicyType())) { prefix = "Decision_"; @@ -600,20 +608,20 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { // get the config file extension String ext = ""; if (configPath != null && !"".equalsIgnoreCase(configPath)) { - ext = configPath.substring(configPath.lastIndexOf('.'), configPath.length());; + ext = configPath.substring(configPath.lastIndexOf('.'), configPath.length()); } if (ext.contains("txt")) { - policy.policyAdapter.setConfigType(PolicyDBDao.OTHER_CONFIG); + policy.policyAdapter.setConfigType(PolicyDbDao.OTHER_CONFIG); } else if (ext.contains("json")) { - policy.policyAdapter.setConfigType(PolicyDBDao.JSON_CONFIG); + policy.policyAdapter.setConfigType(PolicyDbDao.JSON_CONFIG); } else if (ext.contains("xml")) { - policy.policyAdapter.setConfigType(PolicyDBDao.XML_CONFIG); + policy.policyAdapter.setConfigType(PolicyDbDao.XML_CONFIG); } else if (ext.contains("properties")) { - policy.policyAdapter.setConfigType(PolicyDBDao.PROPERTIES_CONFIG); + policy.policyAdapter.setConfigType(PolicyDbDao.PROPERTIES_CONFIG); } else { - if (policy.policyAdapter.getPolicyType().equalsIgnoreCase(PolicyDBDao.ACTION)) { - policy.policyAdapter.setConfigType(PolicyDBDao.JSON_CONFIG); + if (policy.policyAdapter.getPolicyType().equalsIgnoreCase(PolicyDbDao.ACTION)) { + policy.policyAdapter.setConfigType(PolicyDbDao.JSON_CONFIG); } } } @@ -640,42 +648,42 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { private PolicyEntity getPolicy(int policyIdVar, String policyName, String scope) { logger.debug("getPolicy(int policyId, String policyName) as " + " getPolicy(" + policyIdVar + "," + policyName - + ") called"); - if (policyIdVar < 0 && PolicyDBDao.isNullOrEmpty(policyName, scope)) { + + BRACKET_CALLED); + if (policyIdVar < 0 && PolicyDbDao.isNullOrEmpty(policyName, scope)) { throw new IllegalArgumentException("policyID must be at least 0 or policyName must be not null or blank"); } synchronized (emLock) { checkBeforeOperationRun(true); // check if group exists - String policyId; + String locPolicyId; Query policyQuery; - if (!PolicyDBDao.isNullOrEmpty(policyName, scope)) { - policyId = policyName; + if (!PolicyDbDao.isNullOrEmpty(policyName, scope)) { + locPolicyId = policyName; policyQuery = session.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:name AND p.scope=:scope"); - policyQuery.setParameter("name", policyId); + policyQuery.setParameter("name", locPolicyId); policyQuery.setParameter("scope", scope); } else { - policyId = String.valueOf(policyIdVar); + locPolicyId = String.valueOf(policyIdVar); policyQuery = session.getNamedQuery("PolicyEntity.FindById"); - policyQuery.setParameter("id", policyId); + policyQuery.setParameter("id", locPolicyId); } List policyQueryList; try { policyQueryList = policyQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to get policy with policyQuery.getResultList()"); - throw new PersistenceException("Query failed trying to get policy " + policyId); + throw new PersistenceException("Query failed trying to get policy " + locPolicyId); } if (policyQueryList.isEmpty()) { - PolicyLogger.error("Policy does not exist with id " + policyId); - throw new PersistenceException("Group policy is being added to does not exist with id " + policyId); + PolicyLogger.error("Policy does not exist with id " + locPolicyId); + throw new PersistenceException("Group policy is being added to does not exist with id " + locPolicyId); } else if (policyQueryList.size() > 1) { - PolicyLogger.error(PolicyDBDao.DUP_POLICYID + policyId + PolicyDBDao.FOUND_IN_DB); - throw new PersistenceException(PolicyDBDao.DUP_POLICYID + policyId + PolicyDBDao.FOUND_IN_DB); + PolicyLogger.error(PolicyDbDao.DUP_POLICYID + locPolicyId + PolicyDbDao.FOUND_IN_DB); + throw new PersistenceException(PolicyDbDao.DUP_POLICYID + locPolicyId + PolicyDbDao.FOUND_IN_DB); } return (PolicyEntity) policyQueryList.get(0); } @@ -683,7 +691,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @Override public GroupEntity getGroup(long groupKey) { - logger.debug("getGroup(int groupKey) as getGroup(" + groupKey + ") called"); + logger.debug("getGroup(int groupKey) as getGroup(" + groupKey + BRACKET_CALLED); if (groupKey < 0) { throw new IllegalArgumentException("groupKey must be at least 0"); } @@ -696,18 +704,18 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { try { groupQueryList = groupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to get group with groupQuery.getResultList()"); - throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + groupKey); + throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + groupKey); } if (groupQueryList.isEmpty()) { PolicyLogger.error("Group does not exist with groupKey " + groupKey); throw new PersistenceException("Group does not exist with groupKey " + groupKey); } else if (groupQueryList.size() > 1) { PolicyLogger - .error("Somehow, more than one group with the groupKey " + groupKey + PolicyDBDao.FOUND_IN_DB); + .error("Somehow, more than one group with the groupKey " + groupKey + PolicyDbDao.FOUND_IN_DB); throw new PersistenceException( - "Somehow, more than one group with the groupKey " + groupKey + PolicyDBDao.FOUND_IN_DB); + "Somehow, more than one group with the groupKey " + groupKey + PolicyDbDao.FOUND_IN_DB); } return (GroupEntity) groupQueryList.get(0); } @@ -715,29 +723,29 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @Override public GroupEntity getGroup(String groupId) { - logger.debug("getGroup(String groupId) as getGroup(" + groupId + ") called"); - if (PolicyDBDao.isNullOrEmpty(groupId)) { + logger.debug("getGroup(String groupId) as getGroup(" + groupId + BRACKET_CALLED); + if (PolicyDbDao.isNullOrEmpty(groupId)) { throw new IllegalArgumentException("groupId must not be null or empty"); } synchronized (emLock) { checkBeforeOperationRun(true); // check if group exists Query groupQuery = session.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId"); - groupQuery.setParameter(PolicyDBDao.GROUP_ID, groupId); + groupQuery.setParameter(PolicyDbDao.GROUP_ID, groupId); List groupQueryList; try { groupQueryList = groupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to get group with groupQuery.getResultList()"); - throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + groupId); + throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + groupId); } if (groupQueryList.isEmpty()) { PolicyLogger.error("Group does not exist with id " + groupId); throw new PersistenceException("Group does not exist with id " + groupId); } else if (groupQueryList.size() > 1) { - PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + groupId + PolicyDBDao.FOUND_IN_DB); - throw new PersistenceException(PolicyDBDao.DUPLICATE_GROUPID + groupId + PolicyDBDao.FOUND_IN_DB); + PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + groupId + PolicyDbDao.FOUND_IN_DB); + throw new PersistenceException(PolicyDbDao.DUPLICATE_GROUPID + groupId + PolicyDbDao.FOUND_IN_DB); } return (GroupEntity) groupQueryList.get(0); } @@ -745,21 +753,21 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @Override public List getPdpsInGroup(long groupKey) { - logger.debug("getPdpsInGroup(int groupKey) as getPdpsInGroup(" + groupKey + ") called"); + logger.debug("getPdpsInGroup(int groupKey) as getPdpsInGroup(" + groupKey + BRACKET_CALLED); if (groupKey < 0) { throw new IllegalArgumentException("groupId must not be < 0"); } synchronized (emLock) { checkBeforeOperationRun(true); Query pdpsQuery = session.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group"); - pdpsQuery.setParameter("group", getGroup(groupKey)); + pdpsQuery.setParameter(GROUP, getGroup(groupKey)); return pdpsQuery.list(); } } @Override public PdpEntity getPdp(long pdpKey) { - logger.debug("getPdp(int pdpKey) as getPdp(" + pdpKey + ") called"); + logger.debug("getPdp(int pdpKey) as getPdp(" + pdpKey + BRACKET_CALLED); if (pdpKey < 0) { throw new IllegalArgumentException("pdpKey must be at least 0"); } @@ -772,7 +780,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { try { pdpQueryList = pdpQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to get pdp with pdpQuery.getResultList()"); throw new PersistenceException("Query failed trying to get pdp " + pdpKey); } @@ -780,9 +788,9 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { PolicyLogger.error("Pdp does not exist with pdpKey " + pdpKey); throw new PersistenceException("Pdp does not exist with pdpKey " + pdpKey); } else if (pdpQueryList.size() > 1) { - PolicyLogger.error("Somehow, more than one pdp with the pdpKey " + pdpKey + PolicyDBDao.FOUND_IN_DB); + PolicyLogger.error("Somehow, more than one pdp with the pdpKey " + pdpKey + PolicyDbDao.FOUND_IN_DB); throw new PersistenceException( - "Somehow, more than one pdp with the pdpKey " + pdpKey + PolicyDBDao.FOUND_IN_DB); + "Somehow, more than one pdp with the pdpKey " + pdpKey + PolicyDbDao.FOUND_IN_DB); } return (PdpEntity) pdpQueryList.get(0); } @@ -854,8 +862,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { public void createGroup(String groupId, String groupName, String inputGroupDescription, String username) { String groupDescription = inputGroupDescription; logger.debug("deletePolicy(String policyToDeletes) as createGroup(" + groupId + ", " + groupName + ", " - + groupDescription + ") called"); - if (PolicyDBDao.isNullOrEmpty(groupId, groupName, username)) { + + groupDescription + BRACKET_CALLED); + if (PolicyDbDao.isNullOrEmpty(groupId, groupName, username)) { throw new IllegalArgumentException("groupId, groupName, and username must not be null or empty"); } if (groupDescription == null) { @@ -864,16 +872,16 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { synchronized (emLock) { checkBeforeOperationRun(); - Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT); - checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, groupId); - checkGroupQuery.setParameter(PolicyDBDao.DELETED, false); + Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT); + checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, groupId); + checkGroupQuery.setParameter(PolicyDbDao.DELETED, false); List checkGroupQueryList; try { checkGroupQueryList = checkGroupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception on checkGroupQuery.getResultList()"); - throw new PersistenceException(PolicyDBDao.QUERY_FAILED_FOR_GROUP); + throw new PersistenceException(PolicyDbDao.QUERY_FAILED_FOR_GROUP); } if (!checkGroupQueryList.isEmpty()) { PolicyLogger.error("The group being added already exists with id " + groupId); @@ -897,50 +905,50 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @Override public void updateGroup(OnapPDPGroup group, String requestType, String username) { logger.info("PolicyDBDao: updateGroup(PDPGroup group) as updateGroup(" + group + "," + requestType + "," - + username + ") called"); + + username + BRACKET_CALLED); if (group == null) { throw new IllegalArgumentException("PDPGroup group must not be null"); } - if (PolicyDBDao.isNullOrEmpty(group.getId(), requestType)) { + if (PolicyDbDao.isNullOrEmpty(group.getId(), requestType)) { throw new IllegalArgumentException("group.getId() and username must not be null or empty"); } synchronized (emLock) { - PolicyDBDao policyDbDaoVar = new PolicyDBDao(); + PolicyDbDao policyDbDaoVar = new PolicyDbDao(); checkBeforeOperationRun(); - Query getGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT); - getGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId()); - getGroupQuery.setParameter(PolicyDBDao.DELETED, false); + Query getGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT); + getGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId()); + getGroupQuery.setParameter(PolicyDbDao.DELETED, false); List getGroupQueryList; try { getGroupQueryList = getGroupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception on getGroupQuery.getResultList()"); - throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + group.getId() + " for editing"); + throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + group.getId() + " for editing"); } if (getGroupQueryList.isEmpty()) { PolicyLogger.error("The group cannot be found to update with id " + group.getId()); throw new PersistenceException("The group cannot be found to update with id " + group.getId()); } else if (getGroupQueryList.size() > 1) { - PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND); throw new PersistenceException( - PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND); } GroupEntity groupToUpdateInDb = (GroupEntity) getGroupQueryList.get(0); - if (!PolicyDBDao.stringEquals(groupToUpdateInDb.getModifiedBy(), requestType)) { + if (!PolicyDbDao.stringEquals(groupToUpdateInDb.getModifiedBy(), requestType)) { groupToUpdateInDb.setModifiedBy(requestType); } if (group.getDescription() != null - && !PolicyDBDao.stringEquals(group.getDescription(), groupToUpdateInDb.getDescription())) { + && !PolicyDbDao.stringEquals(group.getDescription(), groupToUpdateInDb.getDescription())) { groupToUpdateInDb.setDescription(group.getDescription()); } // let's find out what policies have been deleted StdPDPGroup oldGroup = null; try { - oldGroup = (StdPDPGroup) PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(group.getId()); + oldGroup = (StdPDPGroup) PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(group.getId()); } catch (PAPException e1) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, PolicyDbDao.POLICYDBDAO_VAR, "We cannot get the group from the papEngine to delete policies"); } if (oldGroup == null) { @@ -991,7 +999,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } } } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Could not get policy to remove: " + pol.getId()); throw new PersistenceException("Could not get policy to remove: " + pol.getId()); } @@ -1000,19 +1008,19 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } if (group.getName() != null - && !PolicyDBDao.stringEquals(group.getName(), groupToUpdateInDb.getgroupName())) { + && !PolicyDbDao.stringEquals(group.getName(), groupToUpdateInDb.getgroupName())) { // we need to check if the new id exists in the database - String newGrpId = PolicyDBDao.createNewPDPGroupId(group.getName()); - Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT); - checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, newGrpId); - checkGroupQuery.setParameter(PolicyDBDao.DELETED, false); + String newGrpId = PolicyDbDao.createNewPdpGroupId(group.getName()); + Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT); + checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, newGrpId); + checkGroupQuery.setParameter(PolicyDbDao.DELETED, false); List checkGroupQueryList; try { checkGroupQueryList = checkGroupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception on checkGroupQuery.getResultList()"); - throw new PersistenceException(PolicyDBDao.QUERY_FAILED_FOR_GROUP); + throw new PersistenceException(PolicyDbDao.QUERY_FAILED_FOR_GROUP); } if (!checkGroupQueryList.isEmpty()) { PolicyLogger.error("The new group name already exists, group id " + newGrpId); @@ -1033,35 +1041,35 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { logger.debug("addPdpToGroup(String pdpID, String groupID, String pdpName, " + "String pdpDescription, int pdpJmxPort, String username) as addPdpToGroup(" + pdpId + ", " + groupIdVar + ", " + pdpName + ", " + pdpDescription + ", " + pdpJmxPort + ", " + username - + ") called"); - if (PolicyDBDao.isNullOrEmpty(pdpId, groupIdVar, pdpName, username)) { + + BRACKET_CALLED); + if (PolicyDbDao.isNullOrEmpty(pdpId, groupIdVar, pdpName, username)) { throw new IllegalArgumentException("pdpID, groupID, pdpName, and username must not be null or empty"); } synchronized (emLock) { checkBeforeOperationRun(); - Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT); - checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, groupIdVar); - checkGroupQuery.setParameter(PolicyDBDao.DELETED, false); + Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT); + checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, groupIdVar); + checkGroupQuery.setParameter(PolicyDbDao.DELETED, false); List checkGroupQueryList; try { checkGroupQueryList = checkGroupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to check for existing group on checkGroupQuery.getResultList()"); - throw new PersistenceException(PolicyDBDao.QUERY_FAILED_FOR_GROUP); + throw new PersistenceException(PolicyDbDao.QUERY_FAILED_FOR_GROUP); } if (checkGroupQueryList.size() != 1) { PolicyLogger.error("The group does not exist"); throw new PersistenceException("The group does not exist"); } - Query checkDuplicateQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT); - checkDuplicateQuery.setParameter(PolicyDBDao.PDP_ID, pdpId); - checkDuplicateQuery.setParameter(PolicyDBDao.DELETED, false); + Query checkDuplicateQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT); + checkDuplicateQuery.setParameter(PolicyDbDao.PDP_ID, pdpId); + checkDuplicateQuery.setParameter(PolicyDbDao.DELETED, false); List checkDuplicateList; try { checkDuplicateList = checkDuplicateQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to check for duplicate PDP " + pdpId + " on checkDuplicateQuery.getResultList()"); throw new PersistenceException("Query failed trying to check for duplicate PDP " + pdpId); @@ -1093,24 +1101,24 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @Override public void updatePdp(OnapPDP pdp, String username) { - logger.debug("updatePdp(PDP pdp, String username) as updatePdp(" + pdp + "," + username + ") called"); + logger.debug("updatePdp(PDP pdp, String username) as updatePdp(" + pdp + "," + username + BRACKET_CALLED); if (pdp == null) { throw new IllegalArgumentException("PDP pdp must not be null"); } - if (PolicyDBDao.isNullOrEmpty(pdp.getId(), username)) { + if (PolicyDbDao.isNullOrEmpty(pdp.getId(), username)) { throw new IllegalArgumentException("pdp.getId() and username must not be null or empty"); } synchronized (emLock) { checkBeforeOperationRun(); - Query getPdpQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT); - getPdpQuery.setParameter(PolicyDBDao.PDP_ID, pdp.getId()); - getPdpQuery.setParameter(PolicyDBDao.DELETED, false); + Query getPdpQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT); + getPdpQuery.setParameter(PolicyDbDao.PDP_ID, pdp.getId()); + getPdpQuery.setParameter(PolicyDbDao.DELETED, false); List getPdpQueryList; try { getPdpQueryList = getPdpQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception on getPdpQuery.getResultList()"); throw new PersistenceException("Query failed trying to get PDP " + pdp.getId()); } @@ -1118,19 +1126,19 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { PolicyLogger.error("The pdp cannot be found to update with id " + pdp.getId()); throw new PersistenceException("The pdp cannot be found to update with id " + pdp.getId()); } else if (getPdpQueryList.size() > 1) { - PolicyLogger.error(PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + PolicyLogger.error(PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND); throw new PersistenceException( - PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND); } PdpEntity pdpToUpdate = (PdpEntity) getPdpQueryList.get(0); - if (!PolicyDBDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) { + if (!PolicyDbDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) { pdpToUpdate.setModifiedBy(username); } if (pdp.getDescription() != null - && !PolicyDBDao.stringEquals(pdp.getDescription(), pdpToUpdate.getDescription())) { + && !PolicyDbDao.stringEquals(pdp.getDescription(), pdpToUpdate.getDescription())) { pdpToUpdate.setDescription(pdp.getDescription()); } - if (pdp.getName() != null && !PolicyDBDao.stringEquals(pdp.getName(), pdpToUpdate.getPdpName())) { + if (pdp.getName() != null && !PolicyDbDao.stringEquals(pdp.getName(), pdpToUpdate.getPdpName())) { pdpToUpdate.setPdpName(pdp.getName()); } if (pdp.getJmxPort() != null && !pdp.getJmxPort().equals(pdpToUpdate.getJmxPort())) { @@ -1145,25 +1153,25 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @Override public void movePdp(OnapPDP pdp, OnapPDPGroup group, String username) { logger.debug("movePdp(PDP pdp, PDPGroup group, String username) as movePdp(" + pdp + "," + group + "," - + username + ") called"); + + username + BRACKET_CALLED); if (pdp == null || group == null) { throw new IllegalArgumentException("PDP pdp and PDPGroup group must not be null"); } - if (PolicyDBDao.isNullOrEmpty(username, pdp.getId(), group.getId())) { + if (PolicyDbDao.isNullOrEmpty(username, pdp.getId(), group.getId())) { throw new IllegalArgumentException("pdp.getId(), group.getId(), and username must not be null or empty"); } synchronized (emLock) { checkBeforeOperationRun(); // check if pdp exists - Query getPdpQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT); - getPdpQuery.setParameter(PolicyDBDao.PDP_ID, pdp.getId()); - getPdpQuery.setParameter(PolicyDBDao.DELETED, false); + Query getPdpQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT); + getPdpQuery.setParameter(PolicyDbDao.PDP_ID, pdp.getId()); + getPdpQuery.setParameter(PolicyDbDao.DELETED, false); List getPdpQueryList; try { getPdpQueryList = getPdpQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception on getPdpQuery.getResultList()"); throw new PersistenceException("Query failed trying to get pdp to move with id " + pdp.getId()); } @@ -1171,20 +1179,20 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { PolicyLogger.error("The pdp cannot be found to move with id " + pdp.getId()); throw new PersistenceException("The pdp cannot be found to move with id " + pdp.getId()); } else if (getPdpQueryList.size() > 1) { - PolicyLogger.error(PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + PolicyLogger.error(PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND); throw new PersistenceException( - PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + PolicyDbDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDbDao.DELETED_STATUS_FOUND); } // check if new group exists - Query checkGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT); - checkGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId()); - checkGroupQuery.setParameter(PolicyDBDao.DELETED, false); + Query checkGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT); + checkGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId()); + checkGroupQuery.setParameter(PolicyDbDao.DELETED, false); List checkGroupQueryList; try { checkGroupQueryList = checkGroupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to get group on checkGroupQuery.getResultList()"); throw new PersistenceException("Query failed trying to get new group " + group.getId()); } @@ -1195,7 +1203,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { GroupEntity groupToMoveInto = (GroupEntity) checkGroupQueryList.get(0); PdpEntity pdpToUpdate = (PdpEntity) getPdpQueryList.get(0); pdpToUpdate.setGroup(groupToMoveInto); - if (!PolicyDBDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) { + if (!PolicyDbDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) { pdpToUpdate.setModifiedBy(username); } @@ -1207,38 +1215,38 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @Override public void changeDefaultGroup(OnapPDPGroup group, String username) { logger.debug("changeDefaultGroup(PDPGroup group, String username) as changeDefaultGroup(" + group + "," - + username + ") called"); + + username + BRACKET_CALLED); if (group == null) { throw new IllegalArgumentException("PDPGroup group must not be null"); } - if (PolicyDBDao.isNullOrEmpty(group.getId(), username)) { + if (PolicyDbDao.isNullOrEmpty(group.getId(), username)) { throw new IllegalArgumentException("group.getId() and username must not be null or empty"); } synchronized (emLock) { checkBeforeOperationRun(); - Query getGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT); - getGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId()); - getGroupQuery.setParameter(PolicyDBDao.DELETED, false); + Query getGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT); + getGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId()); + getGroupQuery.setParameter(PolicyDbDao.DELETED, false); List getGroupQueryList; try { getGroupQueryList = getGroupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception on getGroupQuery.getResultList()"); - throw new PersistenceException(PolicyDBDao.QUERY_FAILED_GET_GROUP + group.getId()); + throw new PersistenceException(PolicyDbDao.QUERY_FAILED_GET_GROUP + group.getId()); } if (getGroupQueryList.isEmpty()) { PolicyLogger.error("The group cannot be found to set default with id " + group.getId()); throw new PersistenceException("The group cannot be found to set default with id " + group.getId()); } else if (getGroupQueryList.size() > 1) { - PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND); throw new PersistenceException( - PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.DELETED_STATUS_FOUND); } GroupEntity newDefaultGroup = (GroupEntity) getGroupQueryList.get(0); newDefaultGroup.setDefaultGroup(true); - if (!PolicyDBDao.stringEquals(newDefaultGroup.getModifiedBy(), username)) { + if (!PolicyDbDao.stringEquals(newDefaultGroup.getModifiedBy(), username)) { newDefaultGroup.setModifiedBy(username); } @@ -1248,12 +1256,12 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { + "WHERE g.deleted=:deleted AND g.groupKey<>:groupKey"); // not going to set modified by for all groups setAllGroupsNotDefault.setParameter("defaultGroup", false); - setAllGroupsNotDefault.setParameter(PolicyDBDao.DELETED, false); + setAllGroupsNotDefault.setParameter(PolicyDbDao.DELETED, false); setAllGroupsNotDefault.setParameter("groupKey", newDefaultGroup.getGroupKey()); try { logger.info("set " + setAllGroupsNotDefault.executeUpdate() + " groups as not default"); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception on setAllGroupsNotDefault.executeUpdate()"); throw new PersistenceException("Could not set all other groups default to false"); } @@ -1262,51 +1270,51 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } @Override - public void deleteGroup(OnapPDPGroup group, OnapPDPGroup moveToGroup, String username) throws PolicyDBException { + public void deleteGroup(OnapPDPGroup group, OnapPDPGroup moveToGroup, String username) throws PolicyDbException { logger.debug("deleteGroup(PDPGroup group, PDPGroup moveToGroup, String username) as deleteGroup(" + group + ", " - + moveToGroup + "," + username + ") called"); + + moveToGroup + "," + username + BRACKET_CALLED); if (group == null) { throw new IllegalArgumentException("PDPGroup group cannot be null"); } - if (PolicyDBDao.isNullOrEmpty(username, group.getId())) { + if (PolicyDbDao.isNullOrEmpty(username, group.getId())) { throw new IllegalArgumentException("group.getId() and and username must not be null or empty"); } if (group.isDefaultGroup()) { PolicyLogger.error("The default group " + group.getId() + " was attempted to be deleted. It cannot be."); - throw new PolicyDBException("You cannot delete the default group."); + throw new PolicyDbException("You cannot delete the default group."); } synchronized (emLock) { checkBeforeOperationRun(); - Query deleteGroupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT); - deleteGroupQuery.setParameter(PolicyDBDao.GROUP_ID, group.getId()); - deleteGroupQuery.setParameter(PolicyDBDao.DELETED, false); + Query deleteGroupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT); + deleteGroupQuery.setParameter(PolicyDbDao.GROUP_ID, group.getId()); + deleteGroupQuery.setParameter(PolicyDbDao.DELETED, false); List deleteGroupQueryList; try { deleteGroupQueryList = deleteGroupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to check if group exists deleteGroupQuery.getResultList()"); throw new PersistenceException("Query failed trying to check if group exists"); } if (deleteGroupQueryList.isEmpty()) { - logger.warn(PolicyDBDao.GROUP_NOT_FOUND + group.getId()); + logger.warn(PolicyDbDao.GROUP_NOT_FOUND + group.getId()); return; } else if (deleteGroupQueryList.size() > 1) { - PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL); throw new PersistenceException( - PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + PolicyDbDao.DUPLICATE_GROUPID + group.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL); } Query pdpsInGroupQuery = session.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group and p.deleted=:deleted"); - pdpsInGroupQuery.setParameter("group", (deleteGroupQueryList.get(0))); - pdpsInGroupQuery.setParameter(PolicyDBDao.DELETED, false); + pdpsInGroupQuery.setParameter(GROUP, (deleteGroupQueryList.get(0))); + pdpsInGroupQuery.setParameter(PolicyDbDao.DELETED, false); List pdpsInGroupList; try { pdpsInGroupList = pdpsInGroupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to get PDPs in group on pdpsInGroupQuery.getResultList()"); throw new PersistenceException("Query failed trying to get PDPs in group"); } @@ -1314,37 +1322,37 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { if (moveToGroup != null) { Query checkMoveToGroupQuery = session .createQuery("SELECT o FROM GroupEntity o WHERE o.groupId=:groupId AND o.deleted=:deleted"); - checkMoveToGroupQuery.setParameter(PolicyDBDao.GROUP_ID, moveToGroup.getId()); - checkMoveToGroupQuery.setParameter(PolicyDBDao.DELETED, false); + checkMoveToGroupQuery.setParameter(PolicyDbDao.GROUP_ID, moveToGroup.getId()); + checkMoveToGroupQuery.setParameter(PolicyDbDao.DELETED, false); List checkMoveToGroupList; try { checkMoveToGroupList = checkMoveToGroupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to check if group exists checkMoveToGroupQuery.getResultList"); throw new PersistenceException("Query failed trying to check if group exists"); } if (checkMoveToGroupList.isEmpty()) { - PolicyLogger.error(PolicyDBDao.GROUP_NOT_FOUND + moveToGroup.getId()); - throw new PersistenceException(PolicyDBDao.GROUP_NOT_FOUND + moveToGroup.getId()); + PolicyLogger.error(PolicyDbDao.GROUP_NOT_FOUND + moveToGroup.getId()); + throw new PersistenceException(PolicyDbDao.GROUP_NOT_FOUND + moveToGroup.getId()); } else if (checkMoveToGroupList.size() > 1) { PolicyLogger.error( - PolicyDBDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + PolicyDbDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL); throw new PersistenceException( - PolicyDBDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + PolicyDbDao.DUPLICATE_GROUPID + moveToGroup.getId() + PolicyDbDao.FOUND_IN_DB_NOT_DEL); } else { GroupEntity newGroup = (GroupEntity) checkMoveToGroupList.get(0); for (Object pdpObject : pdpsInGroupList) { PdpEntity pdp = (PdpEntity) pdpObject; pdp.setGroup(newGroup); - if (!PolicyDBDao.stringEquals(pdp.getModifiedBy(), username)) { + if (!PolicyDbDao.stringEquals(pdp.getModifiedBy(), username)) { pdp.setModifiedBy(username); } try { session.flush(); this.newGroupId = newGroup.getGroupId(); } catch (PersistenceException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught PersistenceException trying to set pdp group to null on em.flush()"); throw new PersistenceException("Query failed trying to set pdp group to "); } @@ -1353,14 +1361,14 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } else { PolicyLogger.error("Group " + group.getId() + " is trying to be delted with PDPs. No group was provided to move them to"); - throw new PolicyDBException("Group has PDPs. Must provide a group for them to move to"); + throw new PolicyDbException("Group has PDPs. Must provide a group for them to move to"); } } // delete group here GroupEntity groupToDelete = (GroupEntity) deleteGroupQueryList.get(0); groupToDelete.setDeleted(true); - if (!PolicyDBDao.stringEquals(groupToDelete.getModifiedBy(), username)) { + if (!PolicyDbDao.stringEquals(groupToDelete.getModifiedBy(), username)) { groupToDelete.setModifiedBy(username); } session.flush(); @@ -1370,40 +1378,40 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @Override public StdPDPGroup addPolicyToGroup(String groupIdVar, String policyIdVar, String requestType, String username) - throws PolicyDBException { + throws PolicyDbException { logger.info( "PolicyDBDao: addPolicyToGroup(String groupID, String policyID, String username) as addPolicyToGroup(" - + groupIdVar + ", " + policyIdVar + "," + requestType + "," + username + ") called"); - if (PolicyDBDao.isNullOrEmpty(groupIdVar, policyIdVar, requestType)) { + + groupIdVar + ", " + policyIdVar + "," + requestType + "," + username + BRACKET_CALLED); + if (PolicyDbDao.isNullOrEmpty(groupIdVar, policyIdVar, requestType)) { throw new IllegalArgumentException("groupID, policyID, and username must not be null or empty"); } synchronized (emLock) { checkBeforeOperationRun(); // check if group exists - Query groupQuery = session.createQuery(PolicyDBDao.GROUPENTITY_SELECT); - groupQuery.setParameter(PolicyDBDao.GROUP_ID, groupIdVar); - groupQuery.setParameter(PolicyDBDao.DELETED, false); + Query groupQuery = session.createQuery(PolicyDbDao.GROUPENTITY_SELECT); + groupQuery.setParameter(PolicyDbDao.GROUP_ID, groupIdVar); + groupQuery.setParameter(PolicyDbDao.DELETED, false); List groupQueryList; try { groupQueryList = groupQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to check if group exists groupQuery.getResultList()"); - throw new PersistenceException("Query failed trying to check if group " + groupIdVar + " exists"); + throw new PersistenceException("Query failed trying to check if group " + groupIdVar + EXISTS); } if (groupQueryList.isEmpty()) { PolicyLogger.error("Group policy is being added to does not exist with id " + groupIdVar); throw new PersistenceException("Group policy is being added to does not exist with id " + groupIdVar); } else if (groupQueryList.size() > 1) { - PolicyLogger.error(PolicyDBDao.DUPLICATE_GROUPID + groupIdVar + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + PolicyLogger.error(PolicyDbDao.DUPLICATE_GROUPID + groupIdVar + PolicyDbDao.FOUND_IN_DB_NOT_DEL); throw new PersistenceException( - PolicyDBDao.DUPLICATE_GROUPID + groupIdVar + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + PolicyDbDao.DUPLICATE_GROUPID + groupIdVar + PolicyDbDao.FOUND_IN_DB_NOT_DEL); } // we need to convert the form of the policy id that is used groups // into the form that is used // for the database. (com.Config_mypol.1.xml) to (Config_mypol.xml) - PolicyDBDao policyDbDao = new PolicyDBDao(); + PolicyDbDao policyDbDao = new PolicyDbDao(); String[] policyNameScopeAndVersion = policyDbDao.getNameScopeAndVersionFromPdpPolicy(policyIdVar); if (policyNameScopeAndVersion == null) { throw new IllegalArgumentException("Invalid input - policyID must contain name, scope and version"); @@ -1411,17 +1419,17 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { Query policyQuery = session.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:policyName " + "AND p.scope=:scope AND p.deleted=:deleted"); policyQuery.setParameter("policyName", policyNameScopeAndVersion[0]); - policyQuery.setParameter(PolicyDBDao.SCOPE, policyNameScopeAndVersion[1]); - policyQuery.setParameter(PolicyDBDao.DELETED, false); + policyQuery.setParameter(PolicyDbDao.SCOPE, policyNameScopeAndVersion[1]); + policyQuery.setParameter(PolicyDbDao.DELETED, false); List policyQueryList; try { policyQueryList = policyQuery.list(); } catch (Exception e) { logger.debug(e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to check if policy exists policyQuery.getResultList()"); throw new PersistenceException( - "Query failed trying to check if policy " + policyNameScopeAndVersion[0] + " exists"); + "Query failed trying to check if policy " + policyNameScopeAndVersion[0] + EXISTS); } if (policyQueryList.isEmpty()) { PolicyLogger.error("Policy being added to the group does not exist with policy id " @@ -1430,9 +1438,9 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { + policyNameScopeAndVersion[0]); } else if (policyQueryList.size() > 1) { PolicyLogger.error( - PolicyDBDao.DUP_POLICYID + policyNameScopeAndVersion[0] + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + PolicyDbDao.DUP_POLICYID + policyNameScopeAndVersion[0] + PolicyDbDao.FOUND_IN_DB_NOT_DEL); throw new PersistenceException( - PolicyDBDao.DUPLICATE_GROUPID + policyNameScopeAndVersion[0] + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + PolicyDbDao.DUPLICATE_GROUPID + policyNameScopeAndVersion[0] + PolicyDbDao.FOUND_IN_DB_NOT_DEL); } logger.info("PolicyDBDao: Getting group and policy from database"); GroupEntity group = (GroupEntity) groupQueryList.get(0); @@ -1463,7 +1471,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { // filesytem group is in sync with the db group try { StdPDPGroup pdpGroup = - (StdPDPGroup) PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(group.getGroupId()); + (StdPDPGroup) PolicyDbDao.getPolicyDbDaoInstance().getPapEngine().getGroup(group.getGroupId()); return policyDbDao.synchronizeGroupPoliciesInFileSystem(pdpGroup, group); } catch (PAPException e) { logger.debug(e); @@ -1478,27 +1486,27 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @Override public void removePdpFromGroup(String pdpId, String username) { logger.debug("removePdpFromGroup(String pdpID, String username) as removePdpFromGroup(" + pdpId + "," + username - + ") called"); - if (PolicyDBDao.isNullOrEmpty(pdpId, username)) { + + BRACKET_CALLED); + if (PolicyDbDao.isNullOrEmpty(pdpId, username)) { throw new IllegalArgumentException("pdpID and username must not be null or empty"); } synchronized (emLock) { checkBeforeOperationRun(); - Query pdpQuery = session.createQuery(PolicyDBDao.PDPENTITY_SELECT); - pdpQuery.setParameter(PolicyDBDao.PDP_ID, pdpId); - pdpQuery.setParameter(PolicyDBDao.DELETED, false); + Query pdpQuery = session.createQuery(PolicyDbDao.PDPENTITY_SELECT); + pdpQuery.setParameter(PolicyDbDao.PDP_ID, pdpId); + pdpQuery.setParameter(PolicyDbDao.DELETED, false); List pdpList; try { pdpList = pdpQuery.list(); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDbDao.POLICYDBDAO_VAR, "Caught Exception trying to check if pdp exists pdpQuery.getResultList()"); - throw new PersistenceException("Query failed trying to check if pdp " + pdpId + " exists"); + throw new PersistenceException("Query failed trying to check if pdp " + pdpId + EXISTS); } if (pdpList.size() > 1) { - PolicyLogger.error("Somehow, more than one pdp with the id " + pdpId + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + PolicyLogger.error("Somehow, more than one pdp with the id " + pdpId + PolicyDbDao.FOUND_IN_DB_NOT_DEL); throw new PersistenceException( - "Somehow, more than one pdp with the id " + pdpId + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + "Somehow, more than one pdp with the id " + pdpId + PolicyDbDao.FOUND_IN_DB_NOT_DEL); } else if (pdpList.isEmpty()) { PolicyLogger.error("Pdp being removed does not exist with id " + pdpId); return; @@ -1508,7 +1516,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { pdp.setGroup(null); } - if (!PolicyDBDao.stringEquals(pdp.getModifiedBy(), username)) { + if (!PolicyDbDao.stringEquals(pdp.getModifiedBy(), username)) { pdp.setModifiedBy(username); } pdp.setDeleted(true); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandler.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandler.java index a5e61b9a0..b300f6dd1 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandler.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandler.java @@ -3,6 +3,7 @@ * ONAP-PAP-REST * ================================================================================ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,7 +41,7 @@ import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.pap.xacml.rest.XACMLPapServlet; -import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTransaction; +import org.onap.policy.pap.xacml.rest.components.PolicyDbDaoTransaction; import org.onap.policy.pap.xacml.rest.elk.client.PolicyElasticSearchController; import org.onap.policy.pap.xacml.rest.model.RemoveGroupPolicy; import org.onap.policy.pap.xacml.rest.util.JPAUtils; @@ -453,7 +454,7 @@ public class DeleteHandler { } private String deletePolicyFromPdpGroup(OnapPDPGroup group, OnapLoggingContext loggingContext, String userId) { - PolicyDBDaoTransaction acPutTransaction = XACMLPapServlet.getDbDaoTransaction(); + PolicyDbDaoTransaction acPutTransaction = XACMLPapServlet.getDbDaoTransaction(); String response = null; loggingContext.setServiceName("API:PAP.DeleteHandler"); OnapPDPGroup existingGroup = null; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreation.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreation.java index fd1764e69..34ea2c099 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreation.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreation.java @@ -3,6 +3,7 @@ * ONAP-PAP-REST * ================================================================================ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,8 +49,8 @@ import org.onap.policy.pap.xacml.rest.components.FirewallConfigPolicy; import org.onap.policy.pap.xacml.rest.components.MicroServiceConfigPolicy; import org.onap.policy.pap.xacml.rest.components.OptimizationConfigPolicy; import org.onap.policy.pap.xacml.rest.components.Policy; -import org.onap.policy.pap.xacml.rest.components.PolicyDBDao; -import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTransaction; +import org.onap.policy.pap.xacml.rest.components.PolicyDbDao; +import org.onap.policy.pap.xacml.rest.components.PolicyDbDaoTransaction; import org.onap.policy.pap.xacml.rest.elk.client.PolicyElasticSearchController; import org.onap.policy.pap.xacml.rest.util.AbstractPolicyCreation; import org.onap.policy.rest.adapter.PolicyRestAdapter; @@ -71,34 +72,65 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; +/** + * The Class PolicyCreation. + */ @RestController @RequestMapping("/") public class PolicyCreation extends AbstractPolicyCreation { - private static final Logger LOGGER = FlexLogger.getLogger(PolicyCreation.class); + // Recurring constants + private static final String INVALID_ATTRIBUTE = "invalidAttribute"; + private static final String SUCCESS = "success"; + private static final String ERROR = "error"; + private static final String POLICY_NAME = "policyName"; + private String ruleID = ""; - private PolicyDBDao policyDBDao; - String CLName = null; + private String clName = null; private static CommonClassDao commonClassDao; + /** + * Gets the common class dao. + * + * @return the common class dao + */ public static CommonClassDao getCommonClassDao() { return commonClassDao; } + /** + * Sets the common class dao. + * + * @param commonClassDao the new common class dao + */ public static void setCommonClassDao(CommonClassDao commonClassDao) { PolicyCreation.commonClassDao = commonClassDao; } + /** + * Instantiates a new policy creation. + * + * @param commonClassDao the common class dao + */ @Autowired public PolicyCreation(CommonClassDao commonClassDao) { PolicyCreation.commonClassDao = commonClassDao; } - public PolicyCreation() { - } - + /** + * Instantiates a new policy creation. + */ + public PolicyCreation() {} + + /** + * Save policy. + * + * @param policyData the policy data + * @param response the response + * @return the response entity + */ @RequestMapping(value = "/policycreation/save_policy", method = RequestMethod.POST) @ResponseBody public ResponseEntity savePolicy(@RequestBody PolicyRestAdapter policyData, HttpServletResponse response) { @@ -116,8 +148,8 @@ public class PolicyCreation extends AbstractPolicyCreation { if (policyData.getTtlDate() == null) { policyData.setTtlDate("NA"); } else { - String dateTTL = policyData.getTtlDate(); - String newDate = convertDate(dateTTL); + String dateTtl = policyData.getTtlDate(); + String newDate = convertDate(dateTtl); policyData.setTtlDate(newDate); } @@ -195,8 +227,8 @@ public class PolicyCreation extends AbstractPolicyCreation { body = "policyExists"; status = HttpStatus.CONFLICT; response.setStatus(HttpServletResponse.SC_CONFLICT); - response.addHeader("error", "policyExists"); - response.addHeader("policyName", policyData.getPolicyName()); + response.addHeader(ERROR, "policyExists"); + response.addHeader(POLICY_NAME, policyData.getPolicyName()); return new ResponseEntity<>(body, status); } } else { @@ -205,7 +237,7 @@ public class PolicyCreation extends AbstractPolicyCreation { body = "policyNotAvailableForEdit"; status = HttpStatus.NOT_FOUND; response.setStatus(HttpServletResponse.SC_NOT_FOUND); - response.addHeader("error", body); + response.addHeader(ERROR, body); response.addHeader("message", policyData.getPolicyName() + " does not exist on the PAP and cannot be updated."); return new ResponseEntity<>(body, status); @@ -264,22 +296,22 @@ public class PolicyCreation extends AbstractPolicyCreation { } else if ("BRMS_Param".equalsIgnoreCase(policyConfigType)) { policyData.setOnapName("DROOLS"); policyData.setConfigName("BRMS_PARAM_RULE"); - Map drlRuleAndUIParams = new HashMap<>(); + Map drlRuleAndUiParams = new HashMap<>(); if (policyData.getApiflag() == null) { // If there is any dynamic field create the matches here String key = "templateName"; String value = policyData.getRuleName(); - drlRuleAndUIParams.put(key, value); + drlRuleAndUiParams.put(key, value); if (policyData.getRuleData().size() > 0) { for (Object keyValue : policyData.getRuleData().keySet()) { - drlRuleAndUIParams.put(keyValue.toString(), + drlRuleAndUiParams.put(keyValue.toString(), policyData.getRuleData().get(keyValue).toString()); } } - policyData.setBrmsParamBody(drlRuleAndUIParams); + policyData.setBrmsParamBody(drlRuleAndUiParams); } else { - drlRuleAndUIParams = policyData.getBrmsParamBody(); - String modelName = drlRuleAndUIParams.get("templateName"); + drlRuleAndUiParams = policyData.getBrmsParamBody(); + String modelName = drlRuleAndUiParams.get("templateName"); PolicyLogger.info("Template name from API is: " + modelName); BRMSParamTemplate template = (BRMSParamTemplate) commonClassDao @@ -291,9 +323,9 @@ public class PolicyCreation extends AbstractPolicyCreation { body = message; status = HttpStatus.BAD_REQUEST; response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", message); + response.addHeader(ERROR, message); response.addHeader("modelName", modelName); - return new ResponseEntity(body, status); + return new ResponseEntity<>(body, status); } } newPolicy = new CreateBrmsParamPolicy(policyData); @@ -329,15 +361,15 @@ public class PolicyCreation extends AbstractPolicyCreation { for (Object attribute : policyData.getRuleAlgorithmschoices()) { if (attribute instanceof LinkedHashMap) { String label = ((LinkedHashMap) attribute).get("id").toString(); + dynamicRuleAlgorithmLabels.add(label); String key = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmField1").toString(); + dynamicRuleAlgorithmField1.add(key); String rule = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmCombo").toString(); + dynamicRuleAlgorithmCombo.add(rule); String value = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmField2").toString(); - dynamicRuleAlgorithmLabels.add(label); - dynamicRuleAlgorithmField1.add(key); - dynamicRuleAlgorithmCombo.add(rule); dynamicRuleAlgorithmField2.add(value); } } @@ -347,15 +379,15 @@ public class PolicyCreation extends AbstractPolicyCreation { ActionPolicyDict jsonData = ((ActionPolicyDict) commonClassDao.getEntityItem(ActionPolicyDict.class, "attributeName", actionDictValue)); if (jsonData != null) { - String actionBodyString = jsonData.getBody(); String actionDictHeader = jsonData.getHeader(); - String actionDictType = jsonData.getType(); - String actionDictUrl = jsonData.getUrl(); - String actionDictMethod = jsonData.getMethod(); policyData.setActionDictHeader(actionDictHeader); + String actionDictType = jsonData.getType(); policyData.setActionDictType(actionDictType); + String actionDictUrl = jsonData.getUrl(); policyData.setActionDictUrl(actionDictUrl); + String actionDictMethod = jsonData.getMethod(); policyData.setActionDictMethod(actionDictMethod); + String actionBodyString = jsonData.getBody(); if (actionBodyString != null) { policyData.setActionBody(actionBodyString); } @@ -381,17 +413,8 @@ public class PolicyCreation extends AbstractPolicyCreation { newPolicy = new ActionPolicy(policyData, commonClassDao); } else if ("Decision".equalsIgnoreCase(policyType)) { if (policyData.getApiflag() == null) { - Map settingsMap = new HashMap<>(); Map treatmentMap = new HashMap<>(); - List dynamicRuleAlgorithmLabels = new LinkedList<>(); - List dynamicRuleAlgorithmCombo = new LinkedList<>(); - List dynamicRuleAlgorithmField1 = new LinkedList<>(); - List dynamicRuleAlgorithmField2 = new LinkedList<>(); - List dynamicVariableList = new LinkedList<>(); - List dataTypeList = new LinkedList<>(); - List errorCodeList = new LinkedList<>(); - List treatmentList = new LinkedList<>(); - + Map settingsMap = new HashMap<>(); if (!policyData.getSettings().isEmpty()) { for (Object settingsData : policyData.getSettings()) { if (settingsData instanceof LinkedHashMap) { @@ -401,20 +424,25 @@ public class PolicyCreation extends AbstractPolicyCreation { } } } + + List dynamicRuleAlgorithmLabels = new LinkedList<>(); + List dynamicRuleAlgorithmField1 = new LinkedList<>(); + List dynamicRuleAlgorithmCombo = new LinkedList<>(); + List dynamicRuleAlgorithmField2 = new LinkedList<>(); if (policyData.getRuleAlgorithmschoices() != null - && policyData.getRuleAlgorithmschoices().size() > 0) { + && !policyData.getRuleAlgorithmschoices().isEmpty()) { for (Object attribute : policyData.getRuleAlgorithmschoices()) { if (attribute instanceof LinkedHashMap) { String label = ((LinkedHashMap) attribute).get("id").toString(); + dynamicRuleAlgorithmLabels.add(label); String key = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmField1").toString(); + dynamicRuleAlgorithmField1.add(key); String rule = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmCombo").toString(); + dynamicRuleAlgorithmCombo.add(rule); String value = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmField2").toString(); - dynamicRuleAlgorithmLabels.add(label); - dynamicRuleAlgorithmField1.add(key); - dynamicRuleAlgorithmCombo.add(rule); dynamicRuleAlgorithmField2.add(value); } } @@ -475,6 +503,11 @@ public class PolicyCreation extends AbstractPolicyCreation { } } + List dynamicVariableList = new LinkedList<>(); + List dataTypeList = new LinkedList<>(); + List errorCodeList = new LinkedList<>(); + List treatmentList = new LinkedList<>(); + policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels); policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo); policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1); @@ -493,21 +526,21 @@ public class PolicyCreation extends AbstractPolicyCreation { if (newPolicy != null) { newPolicy.prepareToSave(); } else { - body = "error"; + body = ERROR; status = HttpStatus.INTERNAL_SERVER_ERROR; response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader("error", "error"); + response.addHeader(ERROR, ERROR); return new ResponseEntity<>(body, status); } - PolicyDBDaoTransaction policyDBDaoTransaction = null; + PolicyDbDaoTransaction policyDbDaoTransaction = null; try { - policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(); - policyDBDaoTransaction = policyDBDao.getNewTransaction(); - policyDBDaoTransaction.createPolicy(newPolicy, policyData.getUserId()); + PolicyDbDao policyDbDao = PolicyDbDao.getPolicyDbDaoInstance(); + policyDbDaoTransaction = policyDbDao.getNewTransaction(); + policyDbDaoTransaction.createPolicy(newPolicy, policyData.getUserId()); successMap = newPolicy.savePolicies(); - if (successMap.containsKey("success")) { - policyDBDaoTransaction.commitTransaction(); + if (successMap.containsKey(SUCCESS)) { + policyDbDaoTransaction.commitTransaction(); if (policyData.isEditPolicy()) { commonClassDao.update(policyVersionDao); } else { @@ -519,78 +552,86 @@ public class PolicyCreation extends AbstractPolicyCreation { } catch (Exception e) { LOGGER.error("Error Occured while saving policy to Elastic Database" + e); } - body = "success"; + body = SUCCESS; status = HttpStatus.OK; response.setStatus(HttpServletResponse.SC_OK); - response.addHeader("successMapKey", "success"); - response.addHeader("policyName", policyData.getNewFileName()); + response.addHeader("successMapKey", SUCCESS); + response.addHeader(POLICY_NAME, policyData.getNewFileName()); // get message from the SafetyCheckerResults if present String safetyCheckerResponse = policyData.getClWarning(); - String existingCLName = policyData.getExistingCLName(); + String existingClName = policyData.getExistingCLName(); // if safetyCheckerResponse is not null add a header to send back with response if (safetyCheckerResponse != null) { PolicyLogger.info("SafetyCheckerResponse message: " + safetyCheckerResponse); response.addHeader("safetyChecker", safetyCheckerResponse); - response.addHeader("newCLName", CLName); - response.addHeader("conflictCLName", existingCLName); + response.addHeader("newCLName", clName); + response.addHeader("conflictCLName", existingClName); } else { PolicyLogger.info("SafetyCheckerResponse was empty or null."); } - } else if (successMap.containsKey("invalidAttribute")) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Action Attribute"; + } else if (successMap.containsKey(INVALID_ATTRIBUTE)) { LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not fine " + policyData.getActionAttribute() + " in the ActionPolicyDict table."); - body = "invalidAttribute"; + body = INVALID_ATTRIBUTE; status = HttpStatus.BAD_REQUEST; response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("invalidAttribute", policyData.getActionAttribute()); - response.addHeader("error", message); - response.addHeader("policyName", policyData.getPolicyName()); + response.addHeader(INVALID_ATTRIBUTE, policyData.getActionAttribute()); + + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Action Attribute"; + response.addHeader(ERROR, message); + response.addHeader(POLICY_NAME, policyData.getPolicyName()); } else if (successMap.containsKey("fwdberror")) { - policyDBDaoTransaction.rollbackTransaction(); + policyDbDaoTransaction.rollbackTransaction(); body = "fwdberror"; status = HttpStatus.BAD_REQUEST; String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Error when inserting Firewall ConfigBody data into the database."; PolicyLogger.error(message); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", message); - response.addHeader("policyName", policyData.getPolicyName()); - } else if (successMap.get("error").equals("Validation Failed")) { - policyDBDaoTransaction.rollbackTransaction(); + response.addHeader(ERROR, message); + response.addHeader(POLICY_NAME, policyData.getPolicyName()); + } else if (successMap.get(ERROR).equals("Validation Failed")) { + policyDbDaoTransaction.rollbackTransaction(); String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Validating the Policy on the PAP."; PolicyLogger.error(message); body = "Validation"; status = HttpStatus.BAD_REQUEST; response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", message); - response.addHeader("policyName", policyData.getPolicyName()); + response.addHeader(ERROR, message); + response.addHeader(POLICY_NAME, policyData.getPolicyName()); } else { - policyDBDaoTransaction.rollbackTransaction(); - body = "error"; + policyDbDaoTransaction.rollbackTransaction(); + body = ERROR; status = HttpStatus.INTERNAL_SERVER_ERROR; response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader("error", "error"); + response.addHeader(ERROR, ERROR); } } catch (Exception e) { LOGGER.error("Exception Occured : ", e); - if (policyDBDaoTransaction != null) { - policyDBDaoTransaction.rollbackTransaction(); + if (policyDbDaoTransaction != null) { + policyDbDaoTransaction.rollbackTransaction(); } } } catch (Exception e) { LOGGER.error("Exception Occured : " + e.getMessage(), e); - body = "error"; - response.addHeader("error", e.getMessage()); + body = ERROR; + response.addHeader(ERROR, e.getMessage()); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } return new ResponseEntity<>(body, status); } - @ExceptionHandler({HttpMessageNotReadableException.class}) + /** + * Message not readable exception handler. + * + * @param req the req + * @param exception the exception + * @return the response entity + */ + @ExceptionHandler({ HttpMessageNotReadableException.class }) public ResponseEntity messageNotReadableExceptionHandler(HttpServletRequest req, HttpMessageNotReadableException exception) { LOGGER.error("Request not readable: {}", exception); @@ -602,13 +643,17 @@ public class PolicyCreation extends AbstractPolicyCreation { return new ResponseEntity<>(message.toString(), HttpStatus.BAD_REQUEST); } + /** + * Gets the policy version data. + * + * @param dbCheckPolicyName the db check policy name + * @return the policy version data + */ public PolicyVersion getPolicyVersionData(String dbCheckPolicyName) { PolicyVersion entityItem = - (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", dbCheckPolicyName); - if (entityItem != null) { - if (entityItem.getPolicyName().equals(dbCheckPolicyName)) { - return entityItem; - } + (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, POLICY_NAME, dbCheckPolicyName); + if (entityItem != null && entityItem.getPolicyName().equals(dbCheckPolicyName)) { + return entityItem; } return entityItem; } -- cgit 1.2.3-korg