From: Jorge Hernandez Date: Tue, 2 Apr 2019 22:38:05 +0000 (+0000) Subject: Merge "Push and unpush to support multiple policies" X-Git-Tag: 1.4.0~28 X-Git-Url: https://gerrit.onap.org/r/gitweb?p=policy%2Fengine.git;a=commitdiff_plain;h=338796c4d56d2e95aa2903d80589b3b35b5a3dd2;hp=c72526cde70d6b2899d9e4bbc40e096e0ecf1b7d Merge "Push and unpush to support multiple policies" --- 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 a9ef7eee6..41c91ec27 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 @@ -98,7 +98,7 @@ public class ConsoleAndApiService { } catch (UnsupportedEncodingException e) { LOGGER.error(e); } - PolicyDBDaoTransaction newGroupTransaction = XACMLPapServlet.policyDBDao.getNewTransaction(); + PolicyDBDaoTransaction newGroupTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); try { newGroupTransaction.createGroup(PolicyDBDao.createNewPDPGroupId(unescapedName), unescapedName, unescapedDescription, PAPSERVLETDOACPOST); @@ -169,7 +169,7 @@ public class ConsoleAndApiService { StdPDPPolicy policyForSafetyCheck = new StdPDPPolicy(); for (String policyId : policyIdList) { PolicyDBDaoTransaction addPolicyToGroupTransaction = - XACMLPapServlet.policyDBDao.getNewTransaction(); + XACMLPapServlet.getPolicyDbDao().getNewTransaction(); try { // Copying the policy to the file system and updating groups // in database @@ -223,7 +223,7 @@ public class ConsoleAndApiService { */ // Get new transaction to perform updateGroup() - PolicyDBDaoTransaction acPutTransaction = XACMLPapServlet.policyDBDao.getNewTransaction(); + PolicyDBDaoTransaction acPutTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); try { // Assume that this is an update of an existing PDP // Group @@ -288,7 +288,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 = XACMLPapServlet.policyDBDao.getNewTransaction(); + PolicyDBDaoTransaction setDefaultGroupTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); try { setDefaultGroupTransaction.changeDefaultGroup(group, PAPSERVLETDOACPOST); papEngine.setDefaultGroup(group); @@ -313,7 +313,7 @@ public class ConsoleAndApiService { LOGGER.info(TRANSENDED); return; } else if (request.getParameter("pdpId") != null) { - doAcPostTransaction = XACMLPapServlet.policyDBDao.getNewTransaction(); + doAcPostTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); // Args: group= pdpId= <= move PDP to group loggingContext.setServiceName("AC:PAP.movePDP"); String pdpId = request.getParameter("pdpId"); @@ -571,7 +571,7 @@ public class ConsoleAndApiService { */ public void doAcPut(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext, PAPPolicyEngine papEngine) throws IOException { - PolicyDBDaoTransaction acPutTransaction = XACMLPapServlet.policyDBDao.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 @@ -812,7 +812,7 @@ public class ConsoleAndApiService { */ public void doAcDelete(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext, PAPPolicyEngine papEngine) throws IOException { - PolicyDBDaoTransaction removePdpOrGroupTransaction = XACMLPapServlet.policyDBDao.getNewTransaction(); + PolicyDBDaoTransaction removePdpOrGroupTransaction = XACMLPapServlet.getPolicyDbDao().getNewTransaction(); try { // for all DELETE operations the group must exist before the // operation can be done diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DataToNotifyPdp.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DataToNotifyPdp.java index 825aeb774..5615b13cf 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DataToNotifyPdp.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DataToNotifyPdp.java @@ -156,7 +156,7 @@ public class DataToNotifyPdp { if (policyName != null) { policyProperties.setProperty(policyName + ".name", policy.getScope() + "." + policyNameWithNoScope.substring(0, policyNameWithNoScope.indexOf('.'))); - policyLocations.put(policyName + ".url", XACMLPapServlet.papURL + "?id=" + policyName); + policyLocations.put(policyName + ".url", XACMLPapServlet.getPapUrl() + "?id=" + policyName); } roots.add(policyName); } 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 30d09edb5..889905eb6 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 @@ -42,8 +42,6 @@ import java.util.Properties; import java.util.Set; import java.util.UUID; import java.util.concurrent.CopyOnWriteArrayList; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; import javax.persistence.PersistenceException; import javax.servlet.Servlet; import javax.servlet.ServletConfig; @@ -93,7 +91,8 @@ import org.onap.policy.xacml.std.pap.StdPDPStatus; /** * Servlet implementation class XacmlPapServlet */ -@WebServlet(description = "Implements the XACML PAP RESTful API.", urlPatterns = {"/"}, loadOnStartup = 1, +@WebServlet(description = "Implements the XACML PAP RESTful API.", urlPatterns = {"/"}, + loadOnStartup = 1, initParams = {@WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.pap.properties", description = "The location of the properties file holding configuration information.")}) public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeListener, Runnable { @@ -114,23 +113,23 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList /* * List of Admin Console URLs. Used to send notifications when configuration changes. * - * The CopyOnWriteArrayList *should* protect from concurrency errors. This list is seldom changed - * but often read, so the costs of this approach make sense. + * The CopyOnWriteArrayList *should* protect from concurrency errors. This list is seldom + * changed but often read, so the costs of this approach make sense. */ - private static final CopyOnWriteArrayList adminConsoleURLStringList = new CopyOnWriteArrayList<>(); + private static final CopyOnWriteArrayList adminConsoleURLStringList = + new CopyOnWriteArrayList<>(); private static String configHome; private static String actionHome; /* - * This PAP instance's own URL. Need this when creating URLs to send to the PDPs so they can GET the - * Policy files from this process. + * This PAP instance's own URL. Need this when creating URLs to send to the PDPs so they can GET + * the Policy files from this process. */ - public static String papURL = null; + private static String papUrl = null; // The heartbeat thread. private static Heartbeat heartbeat = null; private static Thread heartbeatThread = null; - private static EntityManagerFactory emf; - public static PolicyDBDao policyDBDao; + private static PolicyDBDao policyDbDao; /* * papEngine - This is our engine workhorse that manages the PDP Groups and Nodes. */ @@ -182,7 +181,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList String hostname = InetAddress.getLocalHost().getCanonicalHostName(); baseLoggingContext.setServer(hostname); } catch (UnknownHostException e) { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging", e); + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "Unable to get hostname for logging", e); } // Initialize @@ -207,49 +207,56 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } // Integer will throw an exception of anything is missing or // unrecognized - int papTransWait = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT)); - int papTransTimeout = - Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)); - int papAuditTimeout = - Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT)); + int papTransWait = Integer + .parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT)); + int papTransTimeout = Integer.parseInt( + XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)); + int papAuditTimeout = Integer.parseInt( + XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT)); // Boolean will default to false if anything is missing or // unrecognized - boolean papAuditFlag = - Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG)); - boolean papFileSystemAudit = - Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG)); - String papDependencyGroups = XACMLProperties.getProperty(XACMLRestProperties.PAP_DEPENDENCY_GROUPS); + boolean papAuditFlag = Boolean.parseBoolean( + XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG)); + boolean papFileSystemAudit = Boolean.parseBoolean( + XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG)); + String papDependencyGroups = + XACMLProperties.getProperty(XACMLRestProperties.PAP_DEPENDENCY_GROUPS); if (papDependencyGroups == null) { throw new PAPException("papDependencyGroups is null"); } setPAPDependencyGroups(papDependencyGroups); // Integer will throw an exception of anything is missing or // unrecognized - int fpMonitorInterval = - Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL)); - int failedCounterThreshold = - Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD)); - int testTransInterval = - Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL)); - int writeFpcInterval = - Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL)); - LOGGER.debug("\n\n\n**************************************" + "\n*************************************" - + "\n" + "\n papDbDriver = " + papDbDriver + "\n papDbUrl = " + papDbUrl + "\n papDbUser = " - + papDbUser + "\n papTransWait = " + papTransWait + "\n papTransTimeout = " + papTransTimeout - + "\n papAuditTimeout = " + papAuditTimeout + "\n papAuditFlag = " + papAuditFlag - + "\n papFileSystemAudit = " + papFileSystemAudit + "\n papResourceName = " + papResourceName - + "\n fpMonitorInterval = " + fpMonitorInterval + "\n failedCounterThreshold = " - + failedCounterThreshold + "\n testTransInterval = " + testTransInterval + "\n writeFpcInterval = " - + writeFpcInterval + "\n papSiteName = " + papSiteName + "\n papNodeType = " + papNodeType - + "\n papDependencyGroupsList = " + papDependencyGroups + "\n papIntegrityAuditPeriodSeconds = " - + papIntegrityAuditPeriodSeconds + "\n\n*************************************" + int fpMonitorInterval = Integer.parseInt( + XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL)); + int failedCounterThreshold = Integer.parseInt(XACMLProperties + .getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD)); + int testTransInterval = Integer.parseInt( + XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL)); + int writeFpcInterval = Integer.parseInt( + XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL)); + LOGGER.debug("\n\n\n**************************************" + + "\n*************************************" + "\n" + "\n papDbDriver = " + + papDbDriver + "\n papDbUrl = " + papDbUrl + "\n papDbUser = " + papDbUser + + "\n papTransWait = " + papTransWait + "\n papTransTimeout = " + + papTransTimeout + "\n papAuditTimeout = " + papAuditTimeout + + "\n papAuditFlag = " + papAuditFlag + "\n papFileSystemAudit = " + + papFileSystemAudit + "\n papResourceName = " + papResourceName + + "\n fpMonitorInterval = " + fpMonitorInterval + + "\n failedCounterThreshold = " + failedCounterThreshold + + "\n testTransInterval = " + testTransInterval + "\n writeFpcInterval = " + + writeFpcInterval + "\n papSiteName = " + papSiteName + "\n papNodeType = " + + papNodeType + "\n papDependencyGroupsList = " + papDependencyGroups + + "\n papIntegrityAuditPeriodSeconds = " + papIntegrityAuditPeriodSeconds + + "\n\n*************************************" + "\n**************************************"); // Pull custom persistence settings Properties properties; try { properties = XACMLProperties.getProperties(); - LOGGER.debug("\n\n\n**************************************" + "\n**************************************" - + "\n\n" + "properties = " + properties + "\n\n**************************************"); + LOGGER.debug("\n\n\n**************************************" + + "\n**************************************" + "\n\n" + "properties = " + + properties + "\n\n**************************************"); } catch (IOException e) { PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error loading properties with: " + "XACMLProperties.getProperties()"); @@ -257,8 +264,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } // Create an IntegrityMonitor if (properties.getProperty(PERSISTENCE_JDBC_PWD) != null) { - properties.setProperty(PERSISTENCE_JDBC_PWD, - CryptoUtils.decryptTxtNoExStr(properties.getProperty(PERSISTENCE_JDBC_PWD, ""))); + properties.setProperty(PERSISTENCE_JDBC_PWD, CryptoUtils + .decryptTxtNoExStr(properties.getProperty(PERSISTENCE_JDBC_PWD, ""))); } im = IntegrityMonitor.getInstance(papResourceName, properties); // Create an IntegrityAudit @@ -268,39 +275,41 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // we are about to call the PDPs and give them their configuration. // To do that we need to have the URL of this PAP so we can // construct the Policy file URLs - setPAPURL(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL)); + setPapUrl(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL)); // Create the policyDBDao - setPolicyDBDao(); + setPolicyDbDao(); // Load our PAP engine, first create a factory - ONAPPapEngineFactory factory = ONAPPapEngineFactory - .newInstance(XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY)); + ONAPPapEngineFactory factory = ONAPPapEngineFactory.newInstance( + XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY)); // The factory knows how to go about creating a PAP Engine setPAPEngine(factory.newEngine()); if (((org.onap.policy.xacml.std.pap.StdEngine) papEngine).wasDefaultGroupJustAdded) { createDefaultGroupOnInit(); } - policyDBDao.setPapEngine(XACMLPapServlet.papEngine); - if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG))) { + policyDbDao.setPapEngine(XACMLPapServlet.papEngine); + if (Boolean.parseBoolean( + XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG))) { /* * Auditing the local File System groups to be in sync with the Database */ // 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()); // get the current filesystem group and update from the database if needed StdPDPGroup group = (StdPDPGroup) papEngine.getDefaultGroup(); - StdPDPGroup updatedGroup = policyDBDao.auditLocalFileSystem(group); + StdPDPGroup updatedGroup = policyDbDao.auditLocalFileSystem(group); if (updatedGroup != null) { papEngine.updateGroup(updatedGroup); } - LOGGER.info("PapServlet: updated group is " + papEngine.getDefaultGroup().toString()); + LOGGER.info( + "PapServlet: updated group is " + papEngine.getDefaultGroup().toString()); // sync up the config data from DB to file system LOGGER.info("PapServlet: Sync config data from DB to file system"); - policyDBDao.synchronizeConfigDataInFileSystem(); + policyDbDao.synchronizeConfigDataInFileSystem(); // release the transaction lock auditTrans.close(); @@ -309,20 +318,23 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // Configurable - have the PAP servlet initiate sending the latest // PDP policy/pip configuration // to all its known PDP nodes. - if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) { + if (Boolean.parseBoolean(XACMLProperties + .getProperty(XACMLRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) { startInitiateThreadService(new Thread(this)); } // After startup, the PAP does Heartbeat's to each of the PDPs // periodically startHeartBeatService(new Heartbeat(XACMLPapServlet.papEngine)); } catch (FactoryException | PAPException e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine"); - throw new ServletException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; error: " + e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", + " Failed to create engine"); + throw new ServletException( + XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; error: " + e); } catch (Exception e) { PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine - unexpected error"); - throw new ServletException( - XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; unexpected error: " + e); + throw new ServletException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "PAP not initialized; unexpected error: " + e); } } @@ -330,11 +342,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList private void createDefaultGroupOnInit() { PolicyDBDaoTransaction addNewGroup = null; try { - addNewGroup = policyDBDao.getNewTransaction(); + addNewGroup = policyDbDao.getNewTransaction(); OnapPDPGroup group = papEngine.getDefaultGroup(); - addNewGroup.createGroup(group.getId(), group.getName(), group.getDescription(), "automaticallyAdded"); + addNewGroup.createGroup(group.getId(), group.getName(), group.getDescription(), + "automaticallyAdded"); addNewGroup.commitTransaction(); - addNewGroup = policyDBDao.getNewTransaction(); + addNewGroup = policyDbDao.getNewTransaction(); addNewGroup.changeDefaultGroup(group, "automaticallyAdded"); addNewGroup.commitTransaction(); } catch (Exception e) { @@ -351,7 +364,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList initiateThread.start(); } - private static void mapperWriteValue(ObjectMapper mapper, HttpServletResponse response, Object value) { + private static void mapperWriteValue(ObjectMapper mapper, HttpServletResponse response, + Object value) { try { mapper.writeValue(response.getOutputStream(), value); } catch (Exception e) { @@ -365,25 +379,24 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList XACMLPapServlet.heartbeatThread.start(); } - private static void setPolicyDBDao() throws ServletException { + 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); } } - private static void setEMF(Properties properties) throws ServletException { - emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, properties); - if (emf == null) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE - + " Error creating entity manager factory with persistence unit: " + PERSISTENCE_UNIT); - throw new ServletException("Unable to create Entity Manager Factory"); - } + public static PolicyDBDao getPolicyDbDao() { + return policyDbDao; } - private static void setPAPURL(String papURL) { - XACMLPapServlet.papURL = papURL; + private static void setPapUrl(String papUrl) { + XACMLPapServlet.papUrl = papUrl; + } + + public static String getPapUrl() { + return papUrl; } private static void setPAPEngine(PAPPolicyEngine newEngine) { @@ -399,9 +412,11 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList papDependencyGroupsFlatArray[i] = papDependencyGroupsFlatArray[i].trim(); } try { - if (XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null) { - papIntegrityAuditPeriodSeconds = Integer.parseInt( - XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS).trim()); + if (XACMLProperties.getProperty( + XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null) { + papIntegrityAuditPeriodSeconds = Integer.parseInt(XACMLProperties + .getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) + .trim()); } } catch (Exception e) { String msg = "integrity_audit_period_seconds "; @@ -411,7 +426,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList throw e; } } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", + " ERROR: Bad property entry"); throw new PAPException(e); } } @@ -428,7 +444,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList setPapDbDriver(papDbDriver); papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL); if (papDbUrl == null) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet", " ERROR: Bad papDbUrl property entry"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet", + " ERROR: Bad papDbUrl property entry"); throw new PAPException("papDbUrl is null"); } setPapDbUrl(papDbUrl); @@ -439,8 +456,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList throw new PAPException("papDbUser is null"); } setPapDbUser(papDbUser); - papDbPd = CryptoUtils - .decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD, "")); + papDbPd = CryptoUtils.decryptTxtNoExStr( + XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD, "")); if (papDbPd == null) { PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet", " ERROR: Bad papDbPassword property entry"); @@ -462,16 +479,18 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // PDPId File location XACMLPapServlet.pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE); if (XACMLPapServlet.pdpFile == null) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " The PDP Id Authentication File Property is not valid: " + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + + " The PDP Id Authentication File Property is not valid: " + XACMLRestProperties.PROP_PDP_IDFILE); - throw new PAPException("The PDP Id Authentication File Property :" + XACMLRestProperties.PROP_PDP_IDFILE - + " is not Valid. "); + throw new PAPException("The PDP Id Authentication File Property :" + + XACMLRestProperties.PROP_PDP_IDFILE + " is not Valid. "); } } /** - * Thread used only during PAP startup to initiate change messages to all known PDPs. This must be - * on a separate thread so that any GET requests from the PDPs during this update can be serviced. + * Thread used only during PAP startup to initiate change messages to all known PDPs. This must + * be on a separate thread so that any GET requests from the PDPs during this update can be + * serviced. */ @Override public void run() { @@ -498,7 +517,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList XACMLPapServlet.heartbeatThread.join(); } catch (InterruptedException e) { XACMLPapServlet.heartbeatThread.interrupt(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping heartbeat"); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", + " Error stopping heartbeat"); } } if (initiateThread != null) { @@ -507,7 +527,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList initiateThread.join(); } catch (InterruptedException e) { initiateThread.interrupt(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping thread"); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", + " Error stopping thread"); } } } @@ -517,15 +538,16 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } /** - * Called by: - PDP nodes to register themselves with the PAP, and - Admin Console to make changes - * in the PDP Groups. + * Called by: - PDP nodes to register themselves with the PAP, and - Admin Console to make + * changes in the PDP Groups. * * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); + ONAPLoggingContext loggingContext = + ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); setLoggingContext(loggingContext, "doPost", "PAP.post"); PolicyDBDaoTransaction pdpTransaction = null; try { @@ -534,8 +556,9 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction"); } catch (AdministrativeStateException ae) { - String message = "POST interface called for PAP " + papResourceName + " but it has an Administrative" - + " state of " + im.getStateManager().getAdminState() + "\n Exception Message: " + String message = "POST interface called for PAP " + papResourceName + + " but it has an Administrative" + " state of " + + im.getStateManager().getAdminState() + "\n Exception Message: " + PolicyUtils.CATCH_EXCEPTION; LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, ae); loggingContext.metricEnded(); @@ -545,8 +568,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return; } catch (StandbyStatusException se) { - String message = "POST interface called for PAP " + papResourceName + " but it has a Standby Status" - + " of " + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + se.getMessage(); + String message = "POST interface called for PAP " + papResourceName + + " but it has a Standby Status" + " of " + + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + + se.getMessage(); LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, se); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction"); @@ -583,7 +608,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } } loggingContext.metricStarted(); - getAcServiceInstance().doAcPost(request, response, groupId, loggingContext, papEngine); + getAcServiceInstance().doAcPost(request, response, groupId, loggingContext, + papEngine); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doPost doACPost"); loggingContext.transactionEnded(); @@ -604,20 +630,25 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList LOGGER.info("Unknown PDP: " + id); // Check PDP ID if (CheckPDP.validateID(id)) { - pdpTransaction = policyDBDao.getNewTransaction(); + pdpTransaction = policyDbDao.getNewTransaction(); try { - pdpTransaction.addPdpToGroup(id, XACMLPapServlet.papEngine.getDefaultGroup().getId(), id, - "Registered on first startup", Integer.parseInt(jmxport), "PDP autoregister"); - XACMLPapServlet.papEngine.newPDP(id, XACMLPapServlet.papEngine.getDefaultGroup(), id, + pdpTransaction.addPdpToGroup(id, + XACMLPapServlet.papEngine.getDefaultGroup().getId(), id, + "Registered on first startup", Integer.parseInt(jmxport), + "PDP autoregister"); + XACMLPapServlet.papEngine.newPDP(id, + XACMLPapServlet.papEngine.getDefaultGroup(), id, "Registered on first startup", Integer.parseInt(jmxport)); - } catch (NullPointerException | PAPException | IllegalArgumentException | IllegalStateException - | PersistenceException | PolicyDBException e) { + } catch (NullPointerException | PAPException | IllegalArgumentException + | IllegalStateException | PersistenceException | PolicyDBException e) { pdpTransaction.rollbackTransaction(); String message = "Failed to create new PDP for id: " + id; - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " " + message); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, + e.getMessage()); im.endTransaction(); return; } @@ -635,7 +666,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, + message); im.endTransaction(); return; } @@ -674,8 +706,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList LOGGER.error(e); } if (group == null) { - PolicyLogger.error( - MessageCodes.ERROR_PROCESS_FLOW + " PDP not associated with any group, even the default"); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + + " PDP not associated with any group, even the default"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, @@ -748,7 +780,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList LOGGER.debug(XACMLErrorConstants.ERROR_PROCESS_FLOW + "POST exception: " + e, e); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, + e.getMessage()); im.endTransaction(); return; } @@ -774,7 +807,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); + ONAPLoggingContext loggingContext = + ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); setLoggingContext(loggingContext, "doGet", "PAP.get"); loggingContext.metricStarted(); XACMLRest.dumpRequest(request); @@ -798,8 +832,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doGet im startTransaction"); } catch (AdministrativeStateException ae) { - String message = "GET interface called for PAP " + papResourceName + " but it has an Administrative" - + " state of " + im.getStateManager().getAdminState() + "\n Exception Message: " + ae.getMessage(); + String message = "GET interface called for PAP " + papResourceName + + " but it has an Administrative" + " state of " + + im.getStateManager().getAdminState() + "\n Exception Message: " + + ae.getMessage(); LOGGER.info(message, ae); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); loggingContext.transactionEnded(); @@ -807,8 +843,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return; } catch (StandbyStatusException se) { - String message = "GET interface called for PAP " + papResourceName + " but it has a Standby Status" + " of " - + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + se.getMessage(); + String message = "GET interface called for PAP " + papResourceName + + " but it has a Standby Status" + " of " + + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + + se.getMessage(); LOGGER.info(message, se); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); loggingContext.transactionEnded(); @@ -850,7 +888,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // this is from the Admin Console, so handle separately try { loggingContext.metricStarted(); - getAcServiceInstance().doAcGet(request, response, groupId, loggingContext, papEngine); + getAcServiceInstance().doAcGet(request, response, groupId, loggingContext, + papEngine); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doGet doACGet"); } catch (IOException e) { @@ -874,7 +913,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // Is it known? if (pdp == null) { // Check if request came from localhost - if ("localhost".equals(request.getRemoteHost()) || request.getRemoteHost().equals(request.getLocalAddr())) { + if ("localhost".equals(request.getRemoteHost()) + || request.getRemoteHost().equals(request.getLocalAddr())) { // Return status information - basically all the groups loggingContext.setServiceName("PAP.getGroups"); Set groups = null; @@ -882,10 +922,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList groups = papEngine.getOnapPDPGroups(); } catch (PAPException e) { LOGGER.debug(e); - PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " GET exception"); + PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", + " GET exception"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, + e.getMessage()); im.endTransaction(); return; } @@ -898,8 +940,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList im.endTransaction(); return; } - String message = - "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: " + request.getLocalAddr(); + String message = "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: " + + request.getLocalAddr(); PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); @@ -946,13 +988,14 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList return; } try { - LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n " + "Policy Name : " - + policy.getName() + "\n Policy URI: " + policy.getLocation().toString()); + LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n " + + "Policy Name : " + policy.getName() + "\n Policy URI: " + + policy.getLocation().toString()); } catch (PAPException | IOException e) { LOGGER.error(e); } - try (InputStream is = - new FileInputStream(((StdPDPGroup) group).getDirectory().toString() + File.separator + policyId); + try (InputStream is = new FileInputStream( + ((StdPDPGroup) group).getDirectory().toString() + File.separator + policyId); OutputStream os = response.getOutputStream()) { // Send the policy back IOUtils.copy(is, os); @@ -979,7 +1022,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList @Override protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); + ONAPLoggingContext loggingContext = + ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); setLoggingContext(loggingContext, "doPut", "PAP.put"); try { loggingContext.metricStarted(); @@ -989,9 +1033,11 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } catch (IntegrityMonitorException e) { String message = "PUT interface called for PAP " + papResourceName; if (e instanceof AdministrativeStateException) { - message += " but it has an Administrative state of " + im.getStateManager().getAdminState(); + message += " but it has an Administrative state of " + + im.getStateManager().getAdminState(); } else if (e instanceof StandbyStatusException) { - message += " but it has a Standby Status of " + im.getStateManager().getStandbyStatus(); + message += " but it has a Standby Status of " + + im.getStateManager().getStandbyStatus(); } else { message += " but an exception occurred"; @@ -1032,9 +1078,11 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } loggingContext.metricStarted(); LOGGER.info("XACMLPapServlet: Calling PolicyDBDao to handlIncomingHttpNotification"); - HandleIncomingNotifications handleIncomingNotifications = new HandleIncomingNotifications(); + HandleIncomingNotifications handleIncomingNotifications = + new HandleIncomingNotifications(); handleIncomingNotifications.handleIncomingHttpNotification(policyDBDaoRequestUrl, - policyDBDaoRequestEntityId, policyDBDaoRequestEntityType, policyDBDaoRequestExtraData, this); + policyDBDaoRequestEntityId, policyDBDaoRequestEntityType, + policyDBDaoRequestExtraData, this); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doPut handle incoming http notification"); response.setStatus(200); @@ -1091,9 +1139,9 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList return; } /* - * This is to update the PDP Group with the policy/policies being pushed Part of a 2 step process to - * push policies to the PDP that can now be done From both the Admin Console and the PolicyEngine - * API + * This is to update the PDP Group with the policy/policies being pushed Part of a 2 step + * process to push policies to the PDP that can now be done From both the Admin Console and + * the PolicyEngine API */ String groupId = request.getParameter(GROUPID); if (groupId != null) { @@ -1122,7 +1170,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // this is from the Admin Console, so handle separately try { loggingContext.metricEnded(); - getAcServiceInstance().doAcPut(request, response, groupId, loggingContext, papEngine); + getAcServiceInstance().doAcPut(request, response, groupId, loggingContext, + papEngine); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet goPut doACPut"); } catch (IOException e) { @@ -1179,10 +1228,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } // We do not expect anything from anywhere else. // This method is here in case we ever need to support other operations. - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Request does not have groupId or apiflag"); + LOGGER.error( + XACMLErrorConstants.ERROR_DATA_ISSUE + "Request does not have groupId or apiflag"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId or apiflag"); + setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, + "Request does not have groupId or apiflag"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See error.log"); im.endTransaction(); @@ -1194,7 +1245,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList @Override protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); + ONAPLoggingContext loggingContext = + ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); setLoggingContext(loggingContext, "doDelete", "PAP.delete"); try { loggingContext.metricStarted(); @@ -1202,8 +1254,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doDelete im startTransaction"); } catch (AdministrativeStateException ae) { - String message = "DELETE interface called for PAP " + papResourceName + " but it has an Administrative" - + " state of " + im.getStateManager().getAdminState() + "\n Exception Message: " + ae.getMessage(); + String message = "DELETE interface called for PAP " + papResourceName + + " but it has an Administrative" + " state of " + + im.getStateManager().getAdminState() + "\n Exception Message: " + + ae.getMessage(); LOGGER.info(message, ae); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); loggingContext.transactionEnded(); @@ -1211,8 +1265,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return; } catch (StandbyStatusException se) { - String message = "PUT interface called for PAP " + papResourceName + " but it has a Standby Status" + " of " - + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + se.getMessage(); + String message = "PUT interface called for PAP " + papResourceName + + " but it has a Standby Status" + " of " + + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + + se.getMessage(); LOGGER.info(message, se); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); loggingContext.transactionEnded(); @@ -1255,7 +1311,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // this is from the Admin Console, so handle separately try { loggingContext.metricStarted(); - getAcServiceInstance().doAcDelete(request, response, groupId, loggingContext, papEngine); + getAcServiceInstance().doAcDelete(request, response, groupId, loggingContext, + papEngine); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doDelete doACDelete"); } catch (IOException e) { @@ -1270,16 +1327,20 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Request does not have groupId"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId"); + setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, + "Request does not have groupId"); im.endTransaction(); } - private boolean isPDPCurrent(Properties policies, Properties pipconfig, Properties pdpProperties) { + private boolean isPDPCurrent(Properties policies, Properties pipconfig, + Properties pdpProperties) { String localRootPolicies = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES); - String localReferencedPolicies = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES); + String localReferencedPolicies = + policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES); if (localRootPolicies == null || localReferencedPolicies == null) { - LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing property on PAP server: RootPolicies=" - + localRootPolicies + " ReferencedPolicies=" + localReferencedPolicies); + LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + + "Missing property on PAP server: RootPolicies=" + localRootPolicies + + " ReferencedPolicies=" + localReferencedPolicies); return false; } // Compare the policies and pipconfig properties to the pdpProperties @@ -1289,7 +1350,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList Properties pdpPolicies = XACMLProperties.getPolicyProperties(pdpProperties, false); Properties pdpPipConfig = XACMLProperties.getPipProperties(pdpProperties); if (localRootPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_ROOTPOLICIES)) - && localReferencedPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES)) + && localReferencedPolicies.equals( + pdpPolicies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES)) && pdpPipConfig.equals(pipconfig)) { // The PDP is current return true; @@ -1301,7 +1363,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // property. // Either of these cases means that the PDP is not up-to-date, so // just drop-through to return false. - PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPapServlet", " PDP Error"); + PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPapServlet", + " PDP Error"); } return false; } @@ -1352,9 +1415,9 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList * @throws ServletException * @throws IOException */ - public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId, - ONAPLoggingContext loggingContext) throws IOException { - PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction(); + public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, + String groupId, ONAPLoggingContext loggingContext) throws IOException { + PolicyDBDaoTransaction acPutTransaction = policyDbDao.getNewTransaction(); PolicyLogger.audit("PolicyDBDaoTransaction started for updateGroupsFromAPI"); try { String userId = request.getParameter("userId"); @@ -1426,8 +1489,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList loggingContext.transactionEnded(); LOGGER.info("Success"); - if (policy != null - && ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) { + if (policy != null && ((policy.getId().contains("Config_MS_")) + || (policy.getId().contains("BRMS_Param")))) { PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance(); if (pushPolicyHandler.preSafetyCheck(policy, configHome)) { LOGGER.debug("Precheck Successful."); @@ -1438,12 +1501,14 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList return; } catch (PAPException e) { acPutTransaction.rollbackTransaction(); - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception"); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", + " API PUT exception"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception in request to update group from API - See Error.log on on the PAP."; - setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, + e.getMessage()); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.addHeader("error", ADD_GROUP_ERROR); response.addHeader("message", message); @@ -1452,8 +1517,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } /* - * HELPER to change Group status when PDP status is changed (Must NOT be called from a method that - * is synchronized on the papEngine or it may deadlock) + * HELPER to change Group status when PDP status is changed (Must NOT be called from a method + * that is synchronized on the papEngine or it may deadlock) */ public void setPDPSummaryStatus(OnapPDP pdp, PDPStatus.Status newStatus) throws PAPException { setPDPSummaryStatus(pdp, newStatus.toString()); @@ -1475,8 +1540,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } /* - * Callback methods telling this servlet to notify PDPs of changes made by the PAP StdEngine in the - * PDP group directories + * Callback methods telling this servlet to notify PDPs of changes made by the PAP StdEngine in + * the PDP group directories */ @Override public void changed() { @@ -1485,8 +1550,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList try { groups = papEngine.getOnapPDPGroups(); } catch (PAPException e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed"); - throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", + " getPDPGroups failed"); + throw new IllegalAccessError( + XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e); } for (OnapPDPGroup group : groups) { groupChanged(group); @@ -1499,8 +1566,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList try { groups = papEngine.getOnapPDPGroups(); } catch (PAPException e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed"); - throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", + " getPDPGroups failed"); + throw new IllegalAccessError( + XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e); } for (OnapPDPGroup group : groups) { groupChanged(group, loggingContext); @@ -1554,7 +1623,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } } - private void pdpChanged(OnapPDP pdp, ONAPLoggingContext loggingContext, List pdpDataByGroup) { + private void pdpChanged(OnapPDP pdp, ONAPLoggingContext loggingContext, + List pdpDataByGroup) { Thread t = new Thread(new UpdatePdpThread(pdp, loggingContext, pdpDataByGroup)); if (CheckPDP.validateID(pdp.getId())) { t.start(); @@ -1571,7 +1641,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList return dataToNotify.setPolicyConfigProperties(pdp, papEngine); } - private void testService(ONAPLoggingContext loggingContext, HttpServletResponse response) throws IOException { + private void testService(ONAPLoggingContext loggingContext, HttpServletResponse response) + throws IOException { LOGGER.info("Test request received"); try { im.evaluateSanity(); @@ -1582,7 +1653,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.audit("Transaction Failed - See Error.log"); response.setStatus(HttpServletResponse.SC_OK); return; - } catch (ForwardProgressException | AdministrativeStateException | StandbyStatusException e) { + } catch (ForwardProgressException | AdministrativeStateException + | StandbyStatusException e) { String submsg; if (e instanceof ForwardProgressException) { submsg = " is not making forward progress."; @@ -1592,8 +1664,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList submsg = " Standby Status is NOT PROVIDING SERVICE."; } - String message = "GET:/pap/test called and PAP " + papResourceName + submsg + " Exception Message: " - + e.getMessage(); + String message = "GET:/pap/test called and PAP " + papResourceName + submsg + + " Exception Message: " + e.getMessage(); LOGGER.info(message, e); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); loggingContext.transactionEnded(); @@ -1607,8 +1679,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList if (eMsg == null) { eMsg = "No Exception Message"; } - String message = "GET:/pap/test called and PAP " + papResourceName + " has had a subsystem failure." - + " Exception Message: " + eMsg; + String message = "GET:/pap/test called and PAP " + papResourceName + + " has had a subsystem failure." + " Exception Message: " + eMsg; LOGGER.info(message, e); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); loggingContext.transactionEnded(); @@ -1633,16 +1705,18 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } } - private void setLoggingContext(ONAPLoggingContext loggingContext, String methodType, String serviceName) { + private void setLoggingContext(ONAPLoggingContext loggingContext, String methodType, + String serviceName) { loggingContext.transactionStarted(); loggingContext.setServiceName(serviceName); if (loggingContext.getRequestID() == null || "".equals(loggingContext.getRequestID())) { UUID requestID = UUID.randomUUID(); loggingContext.setRequestID(requestID.toString()); - PolicyLogger.info( - "requestID not provided in call to XACMLPapServlet ('" + methodType + "') so we generated one"); + PolicyLogger.info("requestID not provided in call to XACMLPapServlet ('" + methodType + + "') so we generated one"); } else { - PolicyLogger.info("requestID was provided in call to XACMLPapServlet ('" + methodType + "')"); + PolicyLogger.info( + "requestID was provided in call to XACMLPapServlet ('" + methodType + "')"); } } @@ -1657,12 +1731,14 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList private static void loadWebapps() throws PAPException { if (actionHome == null || configHome == null) { - Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS)); + Path webappsPath = + Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS)); // Sanity Check if (webappsPath == null) { - PolicyLogger.error("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS); - throw new PAPException( - "Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS); + PolicyLogger.error("Invalid Webapps Path Location property : " + + XACMLRestProperties.PROP_PAP_WEBAPPS); + throw new PAPException("Invalid Webapps Path Location property : " + + XACMLRestProperties.PROP_PAP_WEBAPPS); } Path webappsPathConfig = Paths.get(webappsPath.toString() + File.separator + "Config"); Path webappsPathAction = Paths.get(webappsPath.toString() + File.separator + "Action"); @@ -1671,14 +1747,16 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList Files.createDirectories(webappsPathConfig); } catch (IOException e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", - "Failed to create config directory: " + webappsPathConfig.toAbsolutePath().toString()); + "Failed to create config directory: " + + webappsPathConfig.toAbsolutePath().toString()); } } if (Files.notExists(webappsPathAction)) { try { Files.createDirectories(webappsPathAction); } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create action directory: " + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Failed to create action directory: " + webappsPathAction.toAbsolutePath().toString(), e); } } @@ -1715,10 +1793,6 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList actionHome = getActionHome(); } - public static EntityManagerFactory getEmf() { - return emf; - } - public IntegrityAudit getIa() { return ia; } @@ -1736,7 +1810,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } public static PolicyDBDaoTransaction getDbDaoTransaction() { - return policyDBDao.getNewTransaction(); + return policyDbDao.getNewTransaction(); } public static String getPapDbDriver() { 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 index ba8057102..9f5933850 100644 --- 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 @@ -71,23 +71,6 @@ import org.springframework.stereotype.Component; @Component public class PolicyDBDao { private static final Logger logger = FlexLogger.getLogger(PolicyDBDao.class); - private List otherServers; - - public List getOtherServers() { - return otherServers; - } - - public void setOtherServers(List otherServers) { - this.otherServers = otherServers; - } - - private static PolicyDBDao currentInstance = null; - private PAPPolicyEngine papEngine; - - public PAPPolicyEngine getPapEngine() { - return papEngine; - } - public static final String JSON_CONFIG = "JSON"; public static final String XML_CONFIG = "XML"; public static final String PROPERTIES_CONFIG = "PROPERTIES"; @@ -103,33 +86,33 @@ public class PolicyDBDao { 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 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 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_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"; - - - public static boolean isJunit = false; - - public static void setJunit(boolean isJunit) { - PolicyDBDao.isJunit = isJunit; - } - + 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. + * @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"); @@ -157,8 +140,8 @@ public class PolicyDBDao { 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"); + PolicyLogger.error( + "This server's PolicyDBDao instance could not be registered and may not reveive updates"); } otherServers = getRemotePolicyDBDaoList(); @@ -173,16 +156,18 @@ public class PolicyDBDao { // 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) throws InterruptedException { - logger.debug("\n\nstartTransactionSynced(Hibernate Session,int waitTime) as " + "\n startTransactionSynced(" - + session + "," + waitTime + ") called\n\n"); + 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"); + logger.debug("\n\nstartTransactionSynced():" + "\n ATTEMPT to get the DB lock" + + "\n\n"); } - lock = (DatabaseLockEntity) session.get(DatabaseLockEntity.class, 1, LockMode.PESSIMISTIC_WRITE); + lock = (DatabaseLockEntity) session.get(DatabaseLockEntity.class, 1, + LockMode.PESSIMISTIC_WRITE); if (logger.isDebugEnabled()) { logger.debug("\n\nstartTransactionSynced():" + "\n GOT the DB lock" + "\n\n"); } @@ -216,7 +201,8 @@ public class PolicyDBDao { try { session.close(); } catch (Exception e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e); + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Closing Connection/Statement" + e); } } return policyDBDaoEntityList; @@ -236,9 +222,11 @@ public class PolicyDBDao { 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)); + 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)); + int auditTimeoutMs = Integer + .parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT)); return new PolicyDbDaoTransactionInstance(auditTimeoutMs, auditWaitMs); } @@ -249,7 +237,8 @@ public class PolicyDBDao { * @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"); + logger.debug("stringEquals(String one, String two) as stringEquals(" + one + ", " + two + + ") called"); if (one == null && two == null) { return true; } @@ -283,13 +272,15 @@ public class PolicyDBDao { urlUserPass[2] = commaSplit[2]; } if (urlUserPass[1] == null || "".equals(urlUserPass[1])) { - String usernamePropertyValue = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); + String usernamePropertyValue = + XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); if (usernamePropertyValue != null) { urlUserPass[1] = usernamePropertyValue; } } if (urlUserPass[2] == null || "".equals(urlUserPass[2])) { - String passwordPropertyValue = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS); + String passwordPropertyValue = + XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS); if (passwordPropertyValue != null) { urlUserPass[2] = passwordPropertyValue; } @@ -314,7 +305,7 @@ public class PolicyDBDao { Session session = sessionfactory.openSession(); try { startTransactionSynced(session, 1000); - } catch (InterruptedException | IllegalStateException e) { + } catch (IllegalStateException e) { logger.debug("\nPolicyDBDao.register() caught an IllegalStateException: \n" + e + "\n"); DatabaseLockEntity lock; lock = (DatabaseLockEntity) session.get(DatabaseLockEntity.class, 1); @@ -341,7 +332,8 @@ public class PolicyDBDao { } } } - logger.debug("\nPolicyDBDao.register. Database locking and concurrency control is initialized\n"); + 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])); @@ -356,7 +348,8 @@ public class PolicyDBDao { txt = CryptoUtils.encryptTxt(url[2].getBytes(StandardCharsets.UTF_8)); } catch (Exception e) { logger.debug(e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "Could not encrypt PAP password"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, + "Could not encrypt PAP password"); } if (foundPolicyDBDaoEntity == null) { PolicyDBDaoEntity newPolicyDBDaoEntity = new PolicyDBDaoEntity(); @@ -408,8 +401,8 @@ public class PolicyDBDao { * 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 { + public StdPDPGroup synchronizeGroupPoliciesInFileSystem(StdPDPGroup pdpGroup, + GroupEntity groupentity) throws PAPException, PolicyDBException { HashMap currentPolicyMap = new HashMap<>(); HashSet newPolicyIdSet = new HashSet<>(); @@ -429,19 +422,23 @@ public class PolicyDBDao { // convert PolicyEntity object to PDPPolicy String name = pdpPolicyId.replace(".xml", ""); name = name.substring(0, name.lastIndexOf('.')); - InputStream policyStream = new ByteArrayInputStream(policy.getPolicyData().getBytes()); + InputStream policyStream = + new ByteArrayInputStream(policy.getPolicyData().getBytes()); pdpGroup.copyPolicyToFile(pdpPolicyId, name, policyStream); - URI location = Paths.get(pdpGroup.getDirectory().toAbsolutePath().toString(), pdpPolicyId).toUri(); + 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); + 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 " + PolicyLogger.error( + "PolicyDBDao: Exception occurred while creating the StdPDPPolicy newPolicy object " + e.getMessage()); } } @@ -453,20 +450,22 @@ public class PolicyDBDao { 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. " + 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"); + 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 { + public String removeExtensionAndVersionFromPolicyName(String originalPolicyName) + throws PolicyDBException { return getPolicyNameAndVersionFromPolicyFileName(originalPolicyName)[0]; } @@ -476,7 +475,8 @@ public class PolicyDBDao { * @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 { + public String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) + throws PolicyDBException { String policyName = originalPolicyName; String[] nameAndVersion = new String[2]; try { @@ -520,7 +520,8 @@ public class PolicyDBDao { deleteAllGroupTables(); auditGroups(papEngine2); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "auditLocalDatabase() error"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, + "auditLocalDatabase() error"); logger.error("Exception Occured" + e); } } @@ -540,7 +541,8 @@ public class PolicyDBDao { 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()); + logger.info( + "Group was updated during file system audit: " + updatedGroup.toString()); } } catch (PAPException | PolicyDBException e) { logger.error(e); @@ -548,7 +550,8 @@ public class PolicyDBDao { 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"); + throw new PersistenceException( + "Query failed trying to check if group " + group.getId() + " exists"); } session.getTransaction().commit(); @@ -575,7 +578,8 @@ public class PolicyDBDao { 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); + Path webappsPath = Paths + .get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS), type); for (final T configData : configDataResult) { String configName = null; @@ -583,14 +587,16 @@ public class PolicyDBDao { try { if (CONFIG.equalsIgnoreCase(type)) { configName = ((ConfigurationDataEntity) configData).getConfigurationName(); - configBody = (((ConfigurationDataEntity) configData).getConfigBody() != null) - ? ((ConfigurationDataEntity) configData).getConfigBody() - .getBytes(StandardCharsets.UTF_8) - : "".getBytes(); + 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) + ? ((ActionBodyEntity) configData).getActionBody() + .getBytes(StandardCharsets.UTF_8) : "".getBytes(); } Path filePath = Paths.get(webappsPath.toString(), configName); @@ -663,13 +669,15 @@ public class PolicyDBDao { for (PDPPolicy policy : policies) { try { - String[] stringArray = getNameScopeAndVersionFromPdpPolicy(policy.getId()); + 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"); + Query getPolicyEntitiesQuery = + session.getNamedQuery("PolicyEntity.findByNameAndScope"); getPolicyEntitiesQuery.setParameter("name", stringArray[0]); getPolicyEntitiesQuery.setParameter(SCOPE, stringArray[1]); @@ -693,7 +701,8 @@ public class PolicyDBDao { } } catch (Exception e) { session.getTransaction().rollback(); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "Exception auditGroups outer catch"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, + "Exception auditGroups outer catch"); session.close(); return; } @@ -715,8 +724,9 @@ public class PolicyDBDao { // 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"); + logger.debug( + "getConfigFile(String filename, String scope, String configType) as getConfigFile(" + + filename + ", " + configType + ") called"); filename = FilenameUtils.removeExtension(filename); String id = configType; @@ -797,6 +807,27 @@ public class PolicyDBDao { 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(); } @@ -806,7 +837,8 @@ public class PolicyDBDao { return scope + "." + PolicyDBDao.this.getConfigFile(filename, policy); } - String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) throws PolicyDBException { + String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) + throws PolicyDBException { return PolicyDBDao.this.getPolicyNameAndVersionFromPolicyFileName(originalPolicyName); } 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 bc6c79583..a9d785169 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 @@ -42,6 +42,8 @@ import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathFactory; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.hibernate.Query; @@ -67,8 +69,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.w3c.dom.Document; import org.xml.sax.InputSource; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; @Component @@ -89,7 +89,7 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { private static final String DECISIONMS_MODEL = "MicroService_Model"; - public static boolean isJunit = false; + private static boolean isJunit = false; Session session; /** @@ -99,8 +99,10 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { */ public PolicyDbDaoTransactionInstance(String test) { // call the constructor with arguments - this(Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)), - Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT))); + this(Integer + .parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)), + Integer.parseInt( + XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT))); } public PolicyDbDaoTransactionInstance() { @@ -124,9 +126,10 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { * to start before */ public PolicyDbDaoTransactionInstance(int transactionTimeout, int transactionWaitTime) { - logger.info("\n\nPolicyDBDaoTransactionInstance() as PolicyDBDaoTransactionInstance() called:" - + "\n transactionTimeout = " + transactionTimeout + "\n transactionWaitTime = " - + transactionWaitTime + "\n\n"); + logger.info( + "\n\nPolicyDBDaoTransactionInstance() as PolicyDBDaoTransactionInstance() called:" + + "\n transactionTimeout = " + transactionTimeout + + "\n transactionWaitTime = " + transactionWaitTime + "\n\n"); policyId = -1; groupId = -1; @@ -135,11 +138,13 @@ 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( - "Could not lock transaction within " + transactionWaitTime + " milliseconds"); + logger.error("Could not lock transaction within " + transactionWaitTime + + " milliseconds" + e); + throw new PersistenceException("Could not lock transaction within " + + transactionWaitTime + " milliseconds"); } } class TransactionTimer implements Runnable { @@ -154,8 +159,9 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { public void run() { if (logger.isDebugEnabled()) { Date date = new java.util.Date(); - logger.debug("\n\nTransactionTimer.run() - SLEEPING: " + "\n sleepTime (ms) = " + sleepTime - + "\n TimeStamp = " + date.getTime() + "\n\n"); + logger.debug( + "\n\nTransactionTimer.run() - SLEEPING: " + "\n sleepTime (ms) = " + + sleepTime + "\n TimeStamp = " + date.getTime() + "\n\n"); } try { Thread.sleep(sleepTime); @@ -164,24 +170,26 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { // we want to do is roll back if (logger.isDebugEnabled()) { Date date = new java.util.Date(); - logger.debug("\n\nTransactionTimer.run() - WAKE Interrupt: " + "\n TimeStamp = " - + date.getTime() + "\n\n"); + logger.debug("\n\nTransactionTimer.run() - WAKE Interrupt: " + + "\n TimeStamp = " + date.getTime() + "\n\n"); } Thread.currentThread().interrupt(); return; } if (logger.isDebugEnabled()) { Date date = new java.util.Date(); - logger.debug("\n\nTransactionTimer.run() - WAKE Timeout: " + "\n TimeStamp = " + date.getTime() - + "\n\n"); + logger.debug("\n\nTransactionTimer.run() - WAKE Timeout: " + "\n TimeStamp = " + + date.getTime() + "\n\n"); } - logger.warn("PolicyDBDaoTransactionInstance - TransactionTimer - Rolling back transaction."); + logger.warn( + "PolicyDBDaoTransactionInstance - TransactionTimer - Rolling back transaction."); rollbackTransaction(); } } - transactionTimer = new Thread(new TransactionTimer(transactionTimeout), "transactionTimerThread"); + transactionTimer = + new Thread(new TransactionTimer(transactionTimeout), "transactionTimerThread"); transactionTimer.start(); } @@ -210,8 +218,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { NotifyOtherPaps otherPaps = new NotifyOtherPaps(); logger.debug("commitTransaction() as commitTransaction() called"); if (!isTransactionOpen()) { - logger.warn( - "There is no open transaction to commit - PolicyId - " + policyId + ", GroupId - " + groupId); + logger.warn("There is no open transaction to commit - PolicyId - " + policyId + + ", GroupId - " + groupId); try { session.close(); } catch (Exception e) { @@ -233,16 +241,18 @@ 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 + "," - + newGroupId + ")"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, + PolicyDBDao.POLICYDBDAO_VAR, + "Caught Exception on notifyOthers(" + 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 notifyOthers(" + + policyId + "," + POLICY_NOTIFICATION + ")"); } } } @@ -252,16 +262,18 @@ 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 + "," - + newGroupId + ")"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, + PolicyDBDao.POLICYDBDAO_VAR, + "Caught Exception on notifyOthers(" + 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 notifyOthers(" + + groupId + "," + GROUP_NOTIFICATION + ")"); } } } @@ -271,7 +283,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { otherPaps.notifyOthers(pdpId, PDP_NOTIFICATION); } catch (Exception e) { PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, - "Caught Exception on notifyOthers(" + pdpId + "," + PDP_NOTIFICATION + ")"); + "Caught Exception on notifyOthers(" + pdpId + "," + PDP_NOTIFICATION + + ")"); } } } @@ -311,12 +324,13 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } } - private void createPolicy(PolicyRestAdapter policy, String username, String policyScope, String inputPolicyName, - String policyDataString) { + private void createPolicy(PolicyRestAdapter policy, String username, String policyScope, + String inputPolicyName, String policyDataString) { String policyName = inputPolicyName; logger.debug("createPolicy(PolicyRestAdapter policy, String username, String policyScope," - + " String policyName, String policyDataString) as createPolicy(" + policy + ", " + username + ", " - + policyScope + ", " + policyName + ", " + policyDataString + ") called"); + + " String policyName, String policyDataString) as createPolicy(" + policy + ", " + + username + ", " + policyScope + ", " + policyName + ", " + policyDataString + + ") called"); synchronized (emLock) { PolicyDBDao policyDbDao = new PolicyDBDao(); checkBeforeOperationRun(); @@ -331,8 +345,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { policyName = policyName.replace(".Decision_", ":Decision_"); } policyName = policyName.split(":")[1]; - Query createPolicyQuery = session - .createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName"); + Query createPolicyQuery = session.createQuery( + "SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName"); createPolicyQuery.setParameter(PolicyDBDao.SCOPE, policyScope); createPolicyQuery.setParameter("policyName", policyName); List createPolicyQueryList = createPolicyQuery.list(); @@ -381,14 +395,17 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { newActionBodyEntity.setCreatedBy("PolicyDBDao.createPolicy()"); } if (logger.isDebugEnabled()) { - logger.debug("\nPolicyDBDao.createPolicy" + "\n newActionBodyEntity.getActionBody() = " + logger.debug("\nPolicyDBDao.createPolicy" + + "\n newActionBodyEntity.getActionBody() = " + newActionBodyEntity.getActionBody() + "\n newActionBodyEntity.getActionBodyName() = " + newActionBodyEntity.getActionBodyName() - + "\n newActionBodyEntity.getModifiedBy() = " + newActionBodyEntity.getModifiedBy() - + "\n newActionBodyEntity.getCreatedBy() = " + newActionBodyEntity.getCreatedBy() - + "\n newActionBodyEntity.isDeleted() = " + newActionBodyEntity.isDeleted() - + "\n FLUSHING to DB"); + + "\n newActionBodyEntity.getModifiedBy() = " + + newActionBodyEntity.getModifiedBy() + + "\n newActionBodyEntity.getCreatedBy() = " + + newActionBodyEntity.getCreatedBy() + + "\n newActionBodyEntity.isDeleted() = " + + newActionBodyEntity.isDeleted() + "\n FLUSHING to DB"); } // push the actionBodyEntity to the DB if (isJunit) { @@ -402,10 +419,13 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { // We have a actionBody in the policy but we found no // actionBody in the DB String msg = "\n\nPolicyDBDao.createPolicy - Incoming Action policy had an " - + "actionBody, but it could not be found in the DB for update." + "\n policyScope = " - + policyScope + "\n policyName = " + policyName + "\n\n"; - PolicyLogger.error("PolicyDBDao.createPolicy - Incoming Action policy had an actionBody, " - + "but it could not be found in the DB for update: policyName = " + policyName); + + "actionBody, but it could not be found in the DB for update." + + "\n policyScope = " + policyScope + "\n policyName = " + policyName + + "\n\n"; + PolicyLogger.error( + "PolicyDBDao.createPolicy - Incoming Action policy had an actionBody, " + + "but it could not be found in the DB for update: policyName = " + + policyName); throw new IllegalArgumentException(msg); } } @@ -418,7 +438,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { newConfigurationDataEntity = new ConfigurationDataEntity(); configUpdate = false; } else { - newConfigurationDataEntity = (ConfigurationDataEntity) session.get(ConfigurationDataEntity.class, + newConfigurationDataEntity = (ConfigurationDataEntity) session.get( + ConfigurationDataEntity.class, newPolicyEntity.getConfigurationData().getConfigurationDataId()); configUpdate = true; } @@ -426,10 +447,12 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { if (newConfigurationDataEntity != null) { if (!PolicyDBDao.stringEquals(newConfigurationDataEntity.getConfigurationName(), policyDbDao.getConfigFile(configName, policy))) { - newConfigurationDataEntity.setConfigurationName(policyDbDao.getConfigFile(configName, policy)); + newConfigurationDataEntity.setConfigurationName( + policyDbDao.getConfigFile(configName, policy)); } if (newConfigurationDataEntity.getConfigType() == null - || !newConfigurationDataEntity.getConfigType().equals(policy.getConfigType())) { + || !newConfigurationDataEntity.getConfigType() + .equals(policy.getConfigType())) { newConfigurationDataEntity.setConfigType(policy.getConfigType()); } if (!configUpdate) { @@ -445,9 +468,11 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } if (newConfigurationDataEntity.getConfigBody() == null || newConfigurationDataEntity.getConfigBody().isEmpty() - || (!newConfigurationDataEntity.getConfigBody().equals(policy.getConfigBodyData()))) { + || (!newConfigurationDataEntity.getConfigBody() + .equals(policy.getConfigBodyData()))) { // hopefully one of these won't be null - if (policy.getConfigBodyData() == null || policy.getConfigBodyData().isEmpty()) { + if (policy.getConfigBodyData() == null + || policy.getConfigBodyData().isEmpty()) { newConfigurationDataEntity.setConfigBody(policy.getJsonBody()); } else { newConfigurationDataEntity.setConfigBody(policy.getConfigBodyData()); @@ -467,10 +492,12 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { // found no configurationData body in the DB String msg = "\n\nPolicyDBDao.createPolicy - Incoming Config policy had a " + "configurationData body, but it could not be found in the DB for update." - + "\n policyScope = " + policyScope + "\n policyName = " + policyName + "\n\n"; - PolicyLogger - .error("PolicyDBDao.createPolicy - Incoming Config policy had a configurationData body, " - + "but it could not be found in the DB for update: policyName = " + policyName); + + "\n policyScope = " + policyScope + "\n policyName = " + policyName + + "\n\n"; + PolicyLogger.error( + "PolicyDBDao.createPolicy - Incoming Config policy had a configurationData body, " + + "but it could not be found in the DB for update: policyName = " + + policyName); throw new IllegalArgumentException(msg); } @@ -485,7 +512,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { 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)) { @@ -518,8 +546,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { public void createPolicy(Policy policy, String username) { InputStream policyXmlStream = null; try { - logger.debug("createPolicy(PolicyRestAdapter policy, String username) as createPolicy(" + policy + "," - + username + ") called"); + logger.debug("createPolicy(PolicyRestAdapter policy, String username) as createPolicy(" + + policy + "," + username + ") called"); String policyScope = policy.policyAdapter.getDomainDir().replace(File.separator, "."); // Does not need to be XACMLPolicyWriterWithPapNotify since it is // already in the PAP @@ -528,21 +556,23 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { try { if (policy.policyAdapter.getData() instanceof PolicySetType) { - policyXmlStream = XACMLPolicyWriter - .getPolicySetXmlAsInputStream((PolicySetType) policy.getCorrectPolicyDataObject()); + policyXmlStream = XACMLPolicyWriter.getPolicySetXmlAsInputStream( + (PolicySetType) policy.getCorrectPolicyDataObject()); } else { - policyXmlStream = XACMLPolicyWriter.getXmlAsInputStream(policy.getCorrectPolicyDataObject()); + policyXmlStream = XACMLPolicyWriter + .getXmlAsInputStream(policy.getCorrectPolicyDataObject()); } policyDataString = IOUtils.toString(policyXmlStream); } catch (IOException e) { policyDataString = "could not read"; 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."); + 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(); } @@ -566,7 +596,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { String prefix = null; if (PolicyDBDao.CONFIG.equalsIgnoreCase(policy.policyAdapter.getPolicyType()) || DECISIONMS_MODEL.equalsIgnoreCase(policy.policyAdapter.getRuleProvider())) { - prefix = configPath.substring(configPath.indexOf(policyScope + ".") + policyScope.concat(".").length(), + prefix = configPath.substring( + configPath.indexOf(policyScope + ".") + policyScope.concat(".").length(), configPath.lastIndexOf(policy.policyAdapter.getPolicyName())); if (PolicyDBDao.isNullOrEmpty(policy.policyAdapter.getConfigBodyData())) { String configData = ""; @@ -592,11 +623,13 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { if (!(policy.policyAdapter.getData() instanceof PolicyType) && !(policy.policyAdapter.getData() instanceof PolicySetType)) { PolicyLogger.error("The data field is not an instance of PolicyType"); - throw new IllegalArgumentException("The data field is not an instance of PolicyType"); + throw new IllegalArgumentException( + "The data field is not an instance of PolicyType"); } - String finalName = policyScope + "." + prefix + policy.policyAdapter.getPolicyName() + "." - + policy.policyAdapter.getHighestVersion() + ".xml"; - if (policy.policyAdapter.getConfigType() == null || "".equals(policy.policyAdapter.getConfigType())) { + String finalName = policyScope + "." + prefix + policy.policyAdapter.getPolicyName() + + "." + policy.policyAdapter.getHighestVersion() + ".xml"; + if (policy.policyAdapter.getConfigType() == null + || "".equals(policy.policyAdapter.getConfigType())) { // get the config file extension String ext = ""; if (configPath != null && !"".equalsIgnoreCase(configPath)) { @@ -640,10 +673,11 @@ 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"); + logger.debug("getPolicy(int policyId, String policyName) as " + " getPolicy(" + policyIdVar + + "," + policyName + ") 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"); + throw new IllegalArgumentException( + "policyID must be at least 0 or policyName must be not null or blank"); } synchronized (emLock) { @@ -653,8 +687,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { Query policyQuery; if (!PolicyDBDao.isNullOrEmpty(policyName, scope)) { policyId = policyName; - policyQuery = - session.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:name AND p.scope=:scope"); + policyQuery = session.createQuery( + "SELECT p FROM PolicyEntity p WHERE p.policyName=:name AND p.scope=:scope"); policyQuery.setParameter("name", policyId); policyQuery.setParameter("scope", scope); } else { @@ -673,10 +707,12 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { 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); + throw new PersistenceException( + "Group policy is being added to does not exist with id " + policyId); } 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); + throw new PersistenceException( + PolicyDBDao.DUP_POLICYID + policyId + PolicyDBDao.FOUND_IN_DB); } return (PolicyEntity) policyQueryList.get(0); } @@ -691,7 +727,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { synchronized (emLock) { checkBeforeOperationRun(true); // check if group exists - Query groupQuery = session.createQuery("SELECT g FROM GroupEntity g WHERE g.groupKey=:groupKey"); + Query groupQuery = + session.createQuery("SELECT g FROM GroupEntity g WHERE g.groupKey=:groupKey"); groupQuery.setParameter("groupKey", groupKey); List groupQueryList; try { @@ -705,10 +742,10 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { 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); - throw new PersistenceException( - "Somehow, more than one group with the groupKey " + groupKey + PolicyDBDao.FOUND_IN_DB); + PolicyLogger.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); } return (GroupEntity) groupQueryList.get(0); } @@ -723,7 +760,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { synchronized (emLock) { checkBeforeOperationRun(true); // check if group exists - Query groupQuery = session.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId"); + Query groupQuery = + session.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId"); groupQuery.setParameter(PolicyDBDao.GROUP_ID, groupId); List groupQueryList; try { @@ -737,8 +775,10 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { 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); } @@ -752,7 +792,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } synchronized (emLock) { checkBeforeOperationRun(true); - Query pdpsQuery = session.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group"); + Query pdpsQuery = + session.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group"); pdpsQuery.setParameter("group", getGroup(groupKey)); return pdpsQuery.list(); } @@ -767,7 +808,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { synchronized (emLock) { checkBeforeOperationRun(true); // check if group exists - Query pdpQuery = session.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpKey=:pdpKey"); + Query pdpQuery = + session.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpKey=:pdpKey"); pdpQuery.setParameter("pdpKey", pdpKey); List pdpQueryList; try { @@ -781,9 +823,10 @@ 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); - throw new PersistenceException( - "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); } return (PdpEntity) pdpQueryList.get(0); } @@ -822,10 +865,12 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { configContentStream = new FileInputStream(configPath); configDataString = IOUtils.toString(configContentStream); } catch (FileNotFoundException e) { - logger.error("Caught FileNotFoundException on new FileInputStream(" + configPath + ")", e); + logger.error("Caught FileNotFoundException on new FileInputStream(" + configPath + ")", + e); throw new IllegalArgumentException("The config file path does not exist"); } catch (IOException e2) { - logger.error("Caught IOException on newIOUtils.toString(" + configContentStream + ")", e2); + logger.error("Caught IOException on newIOUtils.toString(" + configContentStream + ")", + e2); throw new IllegalArgumentException("The config file path cannot be read"); } finally { IOUtils.closeQuietly(configContentStream); @@ -853,12 +898,14 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } @Override - public void createGroup(String groupId, String groupName, String inputGroupDescription, String username) { + 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"); + logger.debug("deletePolicy(String policyToDeletes) as createGroup(" + groupId + ", " + + groupName + ", " + groupDescription + ") called"); if (PolicyDBDao.isNullOrEmpty(groupId, groupName, username)) { - throw new IllegalArgumentException("groupId, groupName, and username must not be null or empty"); + throw new IllegalArgumentException( + "groupId, groupName, and username must not be null or empty"); } if (groupDescription == null) { groupDescription = ""; @@ -879,7 +926,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } if (!checkGroupQueryList.isEmpty()) { PolicyLogger.error("The group being added already exists with id " + groupId); - throw new PersistenceException("The group being added already exists with id " + groupId); + throw new PersistenceException( + "The group being added already exists with id " + groupId); } GroupEntity newGroup = new GroupEntity(); newGroup.setCreatedBy(username); @@ -898,13 +946,14 @@ 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"); + logger.info("PolicyDBDao: updateGroup(PDPGroup group) as updateGroup(" + group + "," + + requestType + "," + username + ") called"); if (group == null) { throw new IllegalArgumentException("PDPGroup group must not be null"); } if (PolicyDBDao.isNullOrEmpty(group.getId(), requestType)) { - throw new IllegalArgumentException("group.getId() and username must not be null or empty"); + throw new IllegalArgumentException( + "group.getId() and username must not be null or empty"); } synchronized (emLock) { @@ -919,28 +968,32 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } catch (Exception e) { 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); throw new PersistenceException( - PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + "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); + throw new PersistenceException(PolicyDBDao.DUPLICATE_GROUPID + group.getId() + + PolicyDBDao.DELETED_STATUS_FOUND); } GroupEntity groupToUpdateInDb = (GroupEntity) getGroupQueryList.get(0); if (!PolicyDBDao.stringEquals(groupToUpdateInDb.getModifiedBy(), requestType)) { groupToUpdateInDb.setModifiedBy(requestType); } - if (group.getDescription() != null - && !PolicyDBDao.stringEquals(group.getDescription(), groupToUpdateInDb.getDescription())) { + if (group.getDescription() != null && !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, "We cannot get the group from the papEngine to delete policies"); @@ -958,49 +1011,61 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { // should be fast since getPolicies uses a HashSet in // StdPDPGroup if (!newPolicySet.contains(pol.getId())) { - String[] scopeAndName = policyDbDaoVar.getNameScopeAndVersionFromPdpPolicy(pol.getId()); + String[] scopeAndName = + policyDbDaoVar.getNameScopeAndVersionFromPdpPolicy(pol.getId()); PolicyEntity policyToDelete = null; try { if (scopeAndName != null) { policyToDelete = getPolicy(scopeAndName[0], scopeAndName[1]); if ("XACMLPapServlet.doDelete".equals(requestType)) { - Iterator dbPolicyIt = groupToUpdateInDb.getPolicies().iterator(); - String policyName = policyDbDaoVar.getPolicyNameAndVersionFromPolicyFileName( - policyToDelete.getPolicyName())[0]; + Iterator dbPolicyIt = + groupToUpdateInDb.getPolicies().iterator(); + String policyName = policyDbDaoVar + .getPolicyNameAndVersionFromPolicyFileName( + policyToDelete.getPolicyName())[0]; logger.info("PolicyDBDao: delete policy from GroupEntity"); try { while (dbPolicyIt.hasNext()) { PolicyEntity dbpolicy = dbPolicyIt.next(); - if (policyToDelete.getScope().equals(dbpolicy.getScope()) - && policyDbDaoVar.getPolicyNameAndVersionFromPolicyFileName( - dbpolicy.getPolicyName())[0].equals(policyName)) { + if (policyToDelete.getScope() + .equals(dbpolicy.getScope()) + && policyDbDaoVar + .getPolicyNameAndVersionFromPolicyFileName( + dbpolicy.getPolicyName())[0] + .equals(policyName)) { dbPolicyIt.remove(); - logger.info("PolicyDBDao: deleting policy from the existing group:\n " - + "policyName is " + policyToDelete.getScope() + "." - + policyToDelete.getPolicyName() + "\n" + "group is " - + groupToUpdateInDb.getGroupId()); + logger.info( + "PolicyDBDao: deleting policy from the existing group:\n " + + "policyName is " + + policyToDelete.getScope() + "." + + policyToDelete.getPolicyName() + + "\n" + "group is " + + groupToUpdateInDb.getGroupId()); } } } catch (Exception e) { logger.debug(e); PolicyLogger.error("Could not delete policy with name: " - + policyToDelete.getScope() + "." + policyToDelete.getPolicyName() - + "\n ID: " + policyToDelete.getPolicyId()); + + policyToDelete.getScope() + "." + + policyToDelete.getPolicyName() + "\n ID: " + + policyToDelete.getPolicyId()); } } } } 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()); - throw new PersistenceException("Could not get policy to remove: " + pol.getId()); } } } } - if (group.getName() != null - && !PolicyDBDao.stringEquals(group.getName(), groupToUpdateInDb.getgroupName())) { + if (group.getName() != null && !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); @@ -1016,7 +1081,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } if (!checkGroupQueryList.isEmpty()) { PolicyLogger.error("The new group name already exists, group id " + newGrpId); - throw new PersistenceException("The new group name already exists, group id " + newGrpId); + throw new PersistenceException( + "The new group name already exists, group id " + newGrpId); } groupToUpdateInDb.setGroupId(newGrpId); groupToUpdateInDb.setGroupName(group.getName()); @@ -1028,14 +1094,15 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } @Override - public void addPdpToGroup(String pdpId, String groupIdVar, String pdpName, String pdpDescription, int pdpJmxPort, - String username) { + public void addPdpToGroup(String pdpId, String groupIdVar, String pdpName, + String pdpDescription, int pdpJmxPort, String username) { logger.debug("addPdpToGroup(String pdpID, String groupID, String pdpName, " - + "String pdpDescription, int pdpJmxPort, String username) as addPdpToGroup(" + pdpId + ", " - + groupIdVar + ", " + pdpName + ", " + pdpDescription + ", " + pdpJmxPort + ", " + username - + ") called"); + + "String pdpDescription, int pdpJmxPort, String username) as addPdpToGroup(" + + pdpId + ", " + groupIdVar + ", " + pdpName + ", " + pdpDescription + ", " + + pdpJmxPort + ", " + username + ") called"); if (PolicyDBDao.isNullOrEmpty(pdpId, groupIdVar, pdpName, username)) { - throw new IllegalArgumentException("pdpID, groupID, pdpName, and username must not be null or empty"); + throw new IllegalArgumentException( + "pdpID, groupID, pdpName, and username must not be null or empty"); } synchronized (emLock) { checkBeforeOperationRun(); @@ -1064,7 +1131,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { 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); + throw new PersistenceException( + "Query failed trying to check for duplicate PDP " + pdpId); } PdpEntity newPdp; if (!checkDuplicateList.isEmpty()) { @@ -1093,12 +1161,14 @@ 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 + + ") called"); if (pdp == null) { throw new IllegalArgumentException("PDP pdp must not be null"); } if (PolicyDBDao.isNullOrEmpty(pdp.getId(), username)) { - throw new IllegalArgumentException("pdp.getId() and username must not be null or empty"); + throw new IllegalArgumentException( + "pdp.getId() and username must not be null or empty"); } synchronized (emLock) { @@ -1116,21 +1186,24 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } if (getPdpQueryList.isEmpty()) { 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); throw new PersistenceException( - PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + "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); + throw new PersistenceException(PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + + PolicyDBDao.DELETED_STATUS_FOUND); } PdpEntity pdpToUpdate = (PdpEntity) getPdpQueryList.get(0); if (!PolicyDBDao.stringEquals(pdpToUpdate.getModifiedBy(), username)) { pdpToUpdate.setModifiedBy(username); } - if (pdp.getDescription() != null - && !PolicyDBDao.stringEquals(pdp.getDescription(), pdpToUpdate.getDescription())) { + if (pdp.getDescription() != null && !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())) { @@ -1144,13 +1217,14 @@ 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"); + logger.debug("movePdp(PDP pdp, PDPGroup group, String username) as movePdp(" + pdp + "," + + group + "," + username + ") 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())) { - throw new IllegalArgumentException("pdp.getId(), group.getId(), and username must not be null or empty"); + throw new IllegalArgumentException( + "pdp.getId(), group.getId(), and username must not be null or empty"); } synchronized (emLock) { @@ -1165,15 +1239,18 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } catch (Exception e) { 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()); + throw new PersistenceException( + "Query failed trying to get pdp to move with id " + pdp.getId()); } if (getPdpQueryList.isEmpty()) { 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); throw new PersistenceException( - PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + "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); + throw new PersistenceException(PolicyDBDao.MORE_THAN_ONE_PDP + pdp.getId() + + PolicyDBDao.DELETED_STATUS_FOUND); } // check if new group exists @@ -1186,7 +1263,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } catch (Exception e) { 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()); + throw new PersistenceException( + "Query failed trying to get new group " + group.getId()); } if (checkGroupQueryList.size() != 1) { PolicyLogger.error("The group " + group.getId() + " does not exist"); @@ -1206,13 +1284,14 @@ 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"); + logger.debug("changeDefaultGroup(PDPGroup group, String username) as changeDefaultGroup(" + + group + "," + username + ") called"); if (group == null) { throw new IllegalArgumentException("PDPGroup group must not be null"); } if (PolicyDBDao.isNullOrEmpty(group.getId(), username)) { - throw new IllegalArgumentException("group.getId() and username must not be null or empty"); + throw new IllegalArgumentException( + "group.getId() and username must not be null or empty"); } synchronized (emLock) { @@ -1229,12 +1308,15 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { 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("The group cannot be found to set default with id " + group.getId()); throw new PersistenceException( - PolicyDBDao.DUPLICATE_GROUPID + group.getId() + PolicyDBDao.DELETED_STATUS_FOUND); + "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); + throw new PersistenceException(PolicyDBDao.DUPLICATE_GROUPID + group.getId() + + PolicyDBDao.DELETED_STATUS_FOUND); } GroupEntity newDefaultGroup = (GroupEntity) getGroupQueryList.get(0); newDefaultGroup.setDefaultGroup(true); @@ -1244,14 +1326,16 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { session.flush(); this.groupId = newDefaultGroup.getGroupKey(); - Query setAllGroupsNotDefault = session.createQuery("UPDATE GroupEntity g SET g.defaultGroup=:defaultGroup " - + "WHERE g.deleted=:deleted AND g.groupKey<>:groupKey"); + Query setAllGroupsNotDefault = + session.createQuery("UPDATE GroupEntity g SET g.defaultGroup=:defaultGroup " + + "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("groupKey", newDefaultGroup.getGroupKey()); try { - logger.info("set " + setAllGroupsNotDefault.executeUpdate() + " groups as not default"); + logger.info( + "set " + setAllGroupsNotDefault.executeUpdate() + " groups as not default"); } catch (Exception e) { PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, PolicyDBDao.POLICYDBDAO_VAR, "Caught Exception on setAllGroupsNotDefault.executeUpdate()"); @@ -1262,18 +1346,22 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } @Override - 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"); + 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"); if (group == null) { throw new IllegalArgumentException("PDPGroup group cannot be null"); } if (PolicyDBDao.isNullOrEmpty(username, group.getId())) { - throw new IllegalArgumentException("group.getId() and and username must not be null or empty"); + 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."); + PolicyLogger.error("The default group " + group.getId() + + " was attempted to be deleted. It cannot be."); throw new PolicyDBException("You cannot delete the default group."); } synchronized (emLock) { @@ -1293,13 +1381,14 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { 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); - throw new PersistenceException( - 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); } - Query pdpsInGroupQuery = - session.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group and p.deleted=:deleted"); + 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); List pdpsInGroupList; @@ -1312,26 +1401,29 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } if (!pdpsInGroupList.isEmpty()) { if (moveToGroup != null) { - Query checkMoveToGroupQuery = session - .createQuery("SELECT o FROM GroupEntity o WHERE o.groupId=:groupId AND o.deleted=:deleted"); + 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); 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"); + 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()); - } else if (checkMoveToGroupList.size() > 1) { - PolicyLogger.error( - 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.GROUP_NOT_FOUND + moveToGroup.getId()); + } else if (checkMoveToGroupList.size() > 1) { + PolicyLogger.error(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); } else { GroupEntity newGroup = (GroupEntity) checkMoveToGroupList.get(0); for (Object pdpObject : pdpsInGroupList) { @@ -1344,16 +1436,19 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { 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 "); + throw new PersistenceException( + "Query failed trying to set pdp group to "); } } } } 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"); } } @@ -1369,13 +1464,15 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } @Override - public StdPDPGroup addPolicyToGroup(String groupIdVar, String policyIdVar, String requestType, String username) - throws PolicyDBException { + public StdPDPGroup addPolicyToGroup(String groupIdVar, String policyIdVar, String requestType, + String username) throws PolicyDBException { logger.info( "PolicyDBDao: addPolicyToGroup(String groupID, String policyID, String username) as addPolicyToGroup(" - + groupIdVar + ", " + policyIdVar + "," + requestType + "," + username + ") called"); + + groupIdVar + ", " + policyIdVar + "," + requestType + "," + username + + ") called"); if (PolicyDBDao.isNullOrEmpty(groupIdVar, policyIdVar, requestType)) { - throw new IllegalArgumentException("groupID, policyID, and username must not be null or empty"); + throw new IllegalArgumentException( + "groupID, policyID, and username must not be null or empty"); } synchronized (emLock) { checkBeforeOperationRun(); @@ -1389,27 +1486,34 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } catch (Exception e) { 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( + "Group policy is being added to does not exist with id " + groupIdVar); throw new PersistenceException( - PolicyDBDao.DUPLICATE_GROUPID + groupIdVar + PolicyDBDao.FOUND_IN_DB_NOT_DEL); + "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); + throw new PersistenceException(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(); - String[] policyNameScopeAndVersion = policyDbDao.getNameScopeAndVersionFromPdpPolicy(policyIdVar); + String[] policyNameScopeAndVersion = + policyDbDao.getNameScopeAndVersionFromPdpPolicy(policyIdVar); if (policyNameScopeAndVersion == null) { - throw new IllegalArgumentException("Invalid input - policyID must contain name, scope and version"); + throw new IllegalArgumentException( + "Invalid input - policyID must contain name, scope and version"); } - Query policyQuery = session.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:policyName " - + "AND p.scope=:scope AND p.deleted=:deleted"); + 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); @@ -1420,40 +1524,42 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { logger.debug(e); 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"); + throw new PersistenceException("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 " + policyNameScopeAndVersion[0]); - throw new PersistenceException("Policy being added to the group does not exist with policy id " - + policyNameScopeAndVersion[0]); - } else if (policyQueryList.size() > 1) { - PolicyLogger.error( - 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); + "Policy being added to the group does not exist with policy id " + + policyNameScopeAndVersion[0]); + } else if (policyQueryList.size() > 1) { + PolicyLogger.error(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); } logger.info("PolicyDBDao: Getting group and policy from database"); GroupEntity group = (GroupEntity) groupQueryList.get(0); PolicyEntity policy = (PolicyEntity) policyQueryList.get(0); Iterator policyIt = group.getPolicies().iterator(); - String policyName = policyDbDao.getPolicyNameAndVersionFromPolicyFileName(policy.getPolicyName())[0]; + String policyName = policyDbDao + .getPolicyNameAndVersionFromPolicyFileName(policy.getPolicyName())[0]; logger.info("PolicyDBDao: policyName retrieved is " + policyName); try { while (policyIt.hasNext()) { PolicyEntity pol = policyIt.next(); - if (policy.getScope().equals(pol.getScope()) - && policyDbDao.getPolicyNameAndVersionFromPolicyFileName(pol.getPolicyName())[0] + if (policy.getScope().equals(pol.getScope()) && policyDbDao + .getPolicyNameAndVersionFromPolicyFileName(pol.getPolicyName())[0] .equals(policyName)) { policyIt.remove(); } } } catch (Exception e) { logger.debug(e); - PolicyLogger.error("Could not delete old versions for policy " + policy.getPolicyName() + ", ID: " - + policy.getPolicyId()); + PolicyLogger.error("Could not delete old versions for policy " + + policy.getPolicyName() + ", ID: " + policy.getPolicyId()); } group.addPolicyToGroup(policy); session.flush(); @@ -1461,13 +1567,14 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { // After adding policy to the db group we need to make sure the // filesytem group is in sync with the db group try { - StdPDPGroup pdpGroup = - (StdPDPGroup) PolicyDBDao.getPolicyDBDaoInstance().getPapEngine().getGroup(group.getGroupId()); + StdPDPGroup pdpGroup = (StdPDPGroup) PolicyDBDao.getPolicyDBDaoInstance() + .getPapEngine().getGroup(group.getGroupId()); return policyDbDao.synchronizeGroupPoliciesInFileSystem(pdpGroup, group); } catch (PAPException e) { logger.debug(e); - PolicyLogger.error("PolicyDBDao: Could not synchronize the filesystem group with the database group. " - + e.getMessage()); + PolicyLogger.error( + "PolicyDBDao: Could not synchronize the filesystem group with the database group. " + + e.getMessage()); } return null; } @@ -1476,8 +1583,8 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { // this means delete pdp not just remove from group @Override public void removePdpFromGroup(String pdpId, String username) { - logger.debug("removePdpFromGroup(String pdpID, String username) as removePdpFromGroup(" + pdpId + "," + username - + ") called"); + logger.debug("removePdpFromGroup(String pdpID, String username) as removePdpFromGroup(" + + pdpId + "," + username + ") called"); if (PolicyDBDao.isNullOrEmpty(pdpId, username)) { throw new IllegalArgumentException("pdpID and username must not be null or empty"); } @@ -1492,12 +1599,14 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } catch (Exception e) { 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); - throw new PersistenceException( - "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); } else if (pdpList.isEmpty()) { PolicyLogger.error("Pdp being removed does not exist with id " + pdpId); return; @@ -1535,4 +1644,12 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } return description; } + + public static boolean isJunit() { + return isJunit; + } + + public static void setJunit(boolean isJunit) { + PolicyDbDaoTransactionInstance.isJunit = isJunit; + } } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTest.java index 0e89a7085..aa1e56988 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTest.java @@ -31,6 +31,8 @@ import java.util.Date; import java.util.List; import java.util.Properties; import javax.persistence.PersistenceException; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; @@ -60,8 +62,6 @@ import org.onap.policy.xacml.api.pap.OnapPDPGroup; import org.onap.policy.xacml.std.pap.StdEngine; import org.onap.policy.xacml.std.pap.StdPDPGroup; import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; public class PolicyDBDaoTest { private static Logger logger = FlexLogger.getLogger(PolicyDBDaoTest.class); @@ -119,7 +119,8 @@ public class PolicyDBDaoTest { SessionFactory sessionFac = sessionBuilder.buildSessionFactory(); new PolicyDBDao(sessionFac); - new PolicyDbDaoTransactionInstance(sessionFac).isJunit = true; + PolicyDbDaoTransactionInstance.setJunit(true); + new PolicyDbDaoTransactionInstance(sessionFac); CommonClassDaoImpl.setSessionfactory(sessionFac); new DataToNotifyPdp(new CommonClassDaoImpl()); PolicyCreation.setCommonClassDao(new CommonClassDaoImpl()); diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/MetricServiceTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/MetricServiceTest.java index 8c976d9aa..c90e59bf6 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/MetricServiceTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/MetricServiceTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,6 +22,7 @@ package org.onap.policy.pap.xacml.rest.service; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; +import com.mockrunner.mock.web.MockHttpServletResponse; import javax.servlet.http.HttpServletResponse; import org.junit.Test; import org.junit.runner.RunWith; @@ -30,8 +31,6 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import com.mockrunner.mock.web.MockHttpServletResponse; - @RunWith(PowerMockRunner.class) public class MetricServiceTest { @PrepareForTest({XACMLPapServlet.class}) @@ -40,7 +39,6 @@ public class MetricServiceTest { // Mock pap servlet PowerMockito.mockStatic(XACMLPapServlet.class); when(XACMLPapServlet.getPAPEngine()).thenReturn(null); - when(XACMLPapServlet.getEmf()).thenReturn(null); MockHttpServletResponse response = new MockHttpServletResponse(); MetricService.doGetPolicyMetrics(response); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java index 8349fab82..f91815992 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java @@ -4,13 +4,14 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. + * Modifications Copyright (C) 2019 Bell Canada * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -46,24 +47,23 @@ import org.onap.policy.xacml.api.XACMLErrorConstants; import com.att.research.xacml.util.XACMLProperties; /** - * What is not good about this class is that once a value has been set for pdpProperties path - * you cannot change it. That may be ok for a highly controlled production environment in which - * nothing changes, but not a very good implementation. - * - * The reset() method has been added to assist with the above problem in order to - * acquire >80% JUnit code coverage. - * - * This static class doesn't really check a PDP, it simply loads a properties file and tried - * to ensure that a valid URL exists for a PDP along with user/password. + * What is not good about this class is that once a value has been set for pdpProperties path you cannot change it. That + * may be ok for a highly controlled production environment in which nothing changes, but not a very good + * implementation. * + * The reset() method has been added to assist with the above problem in order to acquire >80% JUnit code coverage. + * + * This static class doesn't really check a PDP, it simply loads a properties file and tried to ensure that a valid URL + * exists for a PDP along with user/password. */ public class CheckPDP { + private static Path pdpPath = null; private static Long oldModified = null; private static HashMap pdpMap = null; private static final Logger LOGGER = FlexLogger.getLogger(CheckPDP.class); - private CheckPDP(){ + private CheckPDP() { //default constructor } @@ -92,28 +92,27 @@ public class CheckPDP { return pdpMap.containsKey(id); } - private static void readFile(){ - String pdpFile = null; - try{ + private static void readFile() { + String pdpFile; + try { pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE); - }catch (Exception e){ + } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot read the PDP ID File" + e); return; } if (pdpFile == null) { LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PDP File name not Valid : " + pdpFile); - } - if (pdpPath == null) { + } else if (pdpPath == null) { pdpPath = Paths.get(pdpFile); if (!pdpPath.toString().endsWith(".properties") || !pdpPath.toFile().exists()) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path : " + pdpPath.toString()); + LOGGER.error( + XACMLErrorConstants.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path : " + pdpPath + .toString()); CheckPDP.reset(); return; } readProps(); - } - // Check if File is updated recently - else { + } else { // Check if File is updated recently Long newModified = pdpPath.toFile().lastModified(); if (!newModified.equals(oldModified)) { // File has been updated. @@ -122,11 +121,11 @@ public class CheckPDP { } } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) private static void readProps() { Properties pdpProp; pdpProp = new Properties(); - try(InputStream in = new FileInputStream(pdpPath.toFile())) { + try (InputStream in = new FileInputStream(pdpPath.toFile())) { oldModified = pdpPath.toFile().lastModified(); pdpProp.load(in); // Read the Properties and Load the PDPs and encoding. @@ -147,7 +146,7 @@ public class CheckPDP { } } - private static void loadPDPProperties(String propKey, Properties pdpProp){ + private static void loadPDPProperties(String propKey, Properties pdpProp) { if (propKey.startsWith("PDP_URL")) { String checkVal = pdpProp.getProperty(propKey); if (checkVal == null) { @@ -165,39 +164,40 @@ public class CheckPDP { } } - private static void readPDPParam(String pdpVal){ - if(pdpVal.contains(",")){ + private static void readPDPParam(String pdpVal) { + if (pdpVal.contains(",")) { List pdpValues = new ArrayList<>(Arrays.asList(pdpVal.split("\\s*,\\s*"))); - if(pdpValues.size()==3){ + if (pdpValues.size() == 3) { // 1:2 will be UserID:Password String userID = pdpValues.get(1); String pass = pdpValues.get(2); Base64.Encoder encoder = Base64.getEncoder(); // 0 - PDPURL - pdpMap.put(pdpValues.get(0), encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8))); - }else{ + pdpMap.put(pdpValues.get(0), + encoder.encodeToString((userID + ":" + pass).getBytes(StandardCharsets.UTF_8))); + } else { LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpValues); } - }else{ + } else { LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpVal); } } - public static String getEncoding(String pdpID){ + public static String getEncoding(String pdpID) { try { readFile(); } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); } String encoding = null; - if(pdpMap!=null && (!pdpMap.isEmpty())){ - try{ + if (pdpMap != null && (!pdpMap.isEmpty())) { + try { encoding = pdpMap.get(pdpID); - } catch(Exception e){ + } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); } return encoding; - }else{ + } else { return null; } } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java index be660c803..6aa40dacf 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. + * Modifications Copyright (C) 2019 Bell Canada * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,7 +41,7 @@ import com.att.research.xacml.util.XACMLProperties; public class PolicyAdapter { - private static final Logger LOGGER = FlexLogger.getLogger(PolicyAdapter.class); + private static final Logger LOGGER = FlexLogger.getLogger(PolicyAdapter.class); public void configure(PolicyRestAdapter policyAdapter, PolicyEntity entity) { String policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf('_')); @@ -50,77 +51,70 @@ public class PolicyAdapter { if (configPolicyName != null) { policyAdapter.setConfigPolicyType(configPolicyName); } - - if("Action".equalsIgnoreCase(policyAdapter.getPolicyType())){ - new ActionPolicyController().prePopulateActionPolicyData(policyAdapter, entity); + if ("Action".equalsIgnoreCase(policyAdapter.getPolicyType())) { + new ActionPolicyController().prePopulateActionPolicyData(policyAdapter); } - if("Decision".equalsIgnoreCase(policyAdapter.getPolicyType())){ + if ("Decision".equalsIgnoreCase(policyAdapter.getPolicyType())) { new DecisionPolicyController().prePopulateDecisionPolicyData(policyAdapter, entity); } - if("Config".equalsIgnoreCase(policyAdapter.getPolicyType())){ + if ("Config".equalsIgnoreCase(policyAdapter.getPolicyType())) { prePopulatePolicyData(policyAdapter, entity); } } private String getConfigPolicyName(PolicyRestAdapter policyAdapter) { - String configPolicyName = null ; - if(policyAdapter.getPolicyName().startsWith("Config_PM")){ + String configPolicyName = null; + if (policyAdapter.getPolicyName().startsWith("Config_PM")) { configPolicyName = "ClosedLoop_PM"; - }else if(policyAdapter.getPolicyName().startsWith("Config_Fault")){ + } else if (policyAdapter.getPolicyName().startsWith("Config_Fault")) { configPolicyName = "ClosedLoop_Fault"; - }else if(policyAdapter.getPolicyName().startsWith("Config_FW")){ + } else if (policyAdapter.getPolicyName().startsWith("Config_FW")) { configPolicyName = "Firewall Config"; - }else if(policyAdapter.getPolicyName().startsWith("Config_BRMS_Raw")){ + } else if (policyAdapter.getPolicyName().startsWith("Config_BRMS_Raw")) { configPolicyName = "BRMS_Raw"; - }else if(policyAdapter.getPolicyName().startsWith("Config_BRMS_Param")){ + } else if (policyAdapter.getPolicyName().startsWith("Config_BRMS_Param")) { configPolicyName = "BRMS_Param"; - }else if(policyAdapter.getPolicyName().startsWith("Config_MS")){ + } else if (policyAdapter.getPolicyName().startsWith("Config_MS")) { configPolicyName = "Micro Service"; - }else if(policyAdapter.getPolicyName().startsWith("Config_OOF")){ + } else if (policyAdapter.getPolicyName().startsWith("Config_OOF")) { configPolicyName = "Optimization"; - }else if(policyAdapter.getPolicyName().startsWith("Action") || policyAdapter.getPolicyName().startsWith("Decision") ){ + } else if (policyAdapter.getPolicyName().startsWith("Action") || policyAdapter.getPolicyName() + .startsWith("Decision")) { // No configPolicyName is applicable - }else{ + } else { configPolicyName = "Base"; } return configPolicyName; } private void prePopulatePolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - if("Base".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + if ("Base".equalsIgnoreCase(policyAdapter.getConfigPolicyType())) { new CreatePolicyController().prePopulateBaseConfigPolicyData(policyAdapter, entity); - } - else if("BRMS_Raw".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + } else if ("BRMS_Raw".equalsIgnoreCase(policyAdapter.getConfigPolicyType())) { new CreateBRMSRawController().prePopulateBRMSRawPolicyData(policyAdapter, entity); - } - else if("BRMS_Param".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + } else if ("BRMS_Param".equalsIgnoreCase(policyAdapter.getConfigPolicyType())) { new CreateBRMSParamController().prePopulateBRMSParamPolicyData(policyAdapter, entity); - } - else if("ClosedLoop_Fault".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + } else if ("ClosedLoop_Fault".equalsIgnoreCase(policyAdapter.getConfigPolicyType())) { new CreateClosedLoopFaultController().prePopulateClosedLoopFaultPolicyData(policyAdapter, entity); - } - else if("ClosedLoop_PM".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + } else if ("ClosedLoop_PM".equalsIgnoreCase(policyAdapter.getConfigPolicyType())) { new CreateClosedLoopPMController().prePopulateClosedLoopPMPolicyData(policyAdapter, entity); - } - else if("Micro Service".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + } else if ("Micro Service".equalsIgnoreCase(policyAdapter.getConfigPolicyType())) { new CreateDcaeMicroServiceController().prePopulateDCAEMSPolicyData(policyAdapter, entity); - } - else if("Optimization".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + } else if ("Optimization".equalsIgnoreCase(policyAdapter.getConfigPolicyType())) { new CreateOptimizationController().prePopulatePolicyData(policyAdapter, entity); - } - else if("Firewall Config".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + } else if ("Firewall Config".equalsIgnoreCase(policyAdapter.getConfigPolicyType())) { new CreateFirewallController().prePopulateFWPolicyData(policyAdapter, entity); } } public static PolicyAdapter getInstance() { try { - Class policyAdapter = Class.forName(XACMLProperties.getProperty("policyAdapter.impl.className", PolicyAdapter.class.getName())); + Class policyAdapter = Class + .forName(XACMLProperties.getProperty("policyAdapter.impl.className", PolicyAdapter.class.getName())); return (PolicyAdapter) policyAdapter.newInstance(); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException e) { - LOGGER.error("Exception Occured"+e); + LOGGER.error("Exception Occurred" + e); } return null; } - -} \ No newline at end of file +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java index baf27b06f..d289feaaf 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. + * Modifications Copyright (C) 2019 Bell Canada * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,6 +56,7 @@ import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.http.HttpStatus; +import org.elasticsearch.common.Strings; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -393,8 +395,7 @@ public class PolicyManagerServlet extends HttpServlet { if (scopes.isEmpty()) { return false; } - Set tempScopes = scopes; - for (String scope : tempScopes) { + for (String scope : scopes) { addScope(scopes, scope); } } @@ -416,8 +417,8 @@ public class PolicyManagerServlet extends HttpServlet { if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) { policyData = controller.getData(PolicyVersion.class); } else { - List filterdatas = controller.getData(PolicyVersion.class); - for (Object filter : filterdatas) { + List filterData = controller.getData(PolicyVersion.class); + for (Object filter : filterData) { addFilterData(policyData, scopes, (PolicyVersion) filter); } } @@ -579,12 +580,7 @@ public class PolicyManagerServlet extends HttpServlet { SimpleBindings peParams = new SimpleBindings(); peParams.put(SPLIT_1, split[1]); peParams.put(SPLIT_0, split[0]); - List queryData; - if (PolicyController.isjUnit()) { - queryData = controller.getDataByQuery(query, null); - } else { - queryData = controller.getDataByQuery(query, peParams); - } + List queryData = getDataByQueryFromController(controller, query, peParams); if (queryData.isEmpty()) { return error("Error Occured while Describing the Policy - query is empty"); } @@ -644,7 +640,7 @@ public class PolicyManagerServlet extends HttpServlet { return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin"); } else { if (!FORWARD_SLASH.equals(path)) { - String tempScope = path.substring(1, path.length()); + String tempScope = path.substring(1); tempScope = tempScope.replace(FORWARD_SLASH, File.separator); scopes.add(tempScope); } @@ -656,13 +652,11 @@ public class PolicyManagerServlet extends HttpServlet { String scopeName = path.substring(path.indexOf('/') + 1); activePolicyList(scopeName, resultList, roles, scopes, roleByScope); } catch (Exception ex) { - LOGGER.error("Error Occured While reading Policy Files List" + ex); + LOGGER.error("Error Occurred While reading Policy Files List" + ex); } return new JSONObject().put(RESULT, resultList); } - processRoles(scopes, roles, resultList, roleByScope); - return new JSONObject().put(RESULT, resultList); } @@ -670,9 +664,11 @@ public class PolicyManagerServlet extends HttpServlet { Map roleByScope) { if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) { List scopesList = queryPolicyEditorScopes(null); - for (Object list : scopesList) { - PolicyEditorScopes scope = (PolicyEditorScopes) list; - if (!(scope.getScopeName().contains(File.separator))) { + scopesList.stream() + .map(list -> (PolicyEditorScopes) list) + .filter(scope -> !(scope.getScopeName().contains(File.separator)) + && !scopes.contains(scope.getScopeName())) + .forEach(scope -> { JSONObject el = new JSONObject(); el.put(NAME, scope.getScopeName()); el.put(DATE, scope.getModifiedDate()); @@ -681,17 +677,14 @@ public class PolicyManagerServlet extends HttpServlet { el.put(CREATED_BY, scope.getUserCreatedBy().getUserName()); el.put(MODIFIED_BY, scope.getUserModifiedBy().getUserName()); el.put(ROLETYPE, roleByScope.get(ALLSCOPES)); - if (!scopes.contains(scope.getScopeName())) { - resultList.add(el); - } - } - } + resultList.add(el); + }); } if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)) { - for (Object scope : scopes) { - JSONObject el = new JSONObject(); - List scopesList = queryPolicyEditorScopes(scope.toString()); - if (!scopesList.isEmpty()) { + scopes.stream().map(this::queryPolicyEditorScopes) + .filter(scopesList -> !scopesList.isEmpty()) + .forEach(scopesList -> { + JSONObject el = new JSONObject(); PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0); el.put(NAME, scopeById.getScopeName()); el.put(DATE, scopeById.getModifiedDate()); @@ -699,35 +692,28 @@ public class PolicyManagerServlet extends HttpServlet { el.put(TYPE, "dir"); el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName()); el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName()); - if (!(resultList).stream().anyMatch(item -> item.get("name").equals(scopeById.getScopeName()))) { + if ((resultList).stream().noneMatch(item -> item.get("name").equals(scopeById.getScopeName()))) { el.put(ROLETYPE, roleByScope.get(scopeById.getScopeName())); resultList.add(el); } - } - } + }); } } private List queryPolicyEditorScopes(String scopeName) { - String scopeNamequery; + String scopeNameQuery; SimpleBindings params = new SimpleBindings(); if (scopeName == null) { - scopeNamequery = "from PolicyEditorScopes"; + scopeNameQuery = "from PolicyEditorScopes"; } else { - scopeNamequery = FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME; + scopeNameQuery = FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME; params.put(SCOPE_NAME, scopeName + "%"); } PolicyController controller = getPolicyControllerInstance(); - List scopesList; - if (PolicyController.isjUnit()) { - scopesList = controller.getDataByQuery(scopeNamequery, null); - } else { - scopesList = controller.getDataByQuery(scopeNamequery, params); - } - return scopesList; + return getDataByQueryFromController(controller, scopeNameQuery, params); } - // Get Active Policy List based on Scope Selection form Policy Version table + // Get Active Policy List based on Scope Selection from Policy Version table private void activePolicyList(String inScopeName, List resultList, List roles, Set scopes, Map roleByScope) { PolicyController controller = getPolicyControllerInstance(); @@ -739,51 +725,39 @@ public class PolicyManagerServlet extends HttpServlet { scopeName = scopeName.replace(BACKSLASH, ESCAPE_BACKSLASH); } String query = "from PolicyVersion where POLICY_NAME like :scopeName"; - String scopeNamequery = FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME; SimpleBindings params = new SimpleBindings(); params.put(SCOPE_NAME, scopeName + "%"); - List activePolicies; - List scopesList; - if (PolicyController.isjUnit()) { - activePolicies = controller.getDataByQuery(query, null); - scopesList = controller.getDataByQuery(scopeNamequery, null); - } else { - activePolicies = controller.getDataByQuery(query, params); - scopesList = controller.getDataByQuery(scopeNamequery, params); - } + List activePolicies = getDataByQueryFromController(controller, query, params); + List scopesList = getDataByQueryFromController(controller, + FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME, params); for (Object list : scopesList) { scopeName = checkScope(resultList, scopeName, (PolicyEditorScopes) list, roleByScope); } - String scopeNameCheck; for (Object list : activePolicies) { PolicyVersion policy = (PolicyVersion) list; String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator)); if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) { - if (scopeName.contains(ESCAPE_BACKSLASH)) { - scopeNameCheck = scopeName.replace(ESCAPE_BACKSLASH, File.separator); - } else { - scopeNameCheck = scopeName; - } - if (scopeNameValue.equals(scopeNameCheck)) { - JSONObject el = new JSONObject(); - el.put(NAME, - policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator) + 1)); - el.put(DATE, policy.getModifiedDate()); - el.put(VERSION, policy.getActiveVersion()); - el.put(SIZE, ""); - el.put(TYPE, "file"); - el.put(CREATED_BY, getUserName(policy.getCreatedBy())); - el.put(MODIFIED_BY, getUserName(policy.getModifiedBy())); - String roleType = roleByScope.get(scopeNameValue); - if (roleType == null) { - roleType = roleByScope.get(ALLSCOPES); - } - el.put(ROLETYPE, roleType); - resultList.add(el); + String scopeNameCheck = + scopeName.contains(ESCAPE_BACKSLASH) ? scopeName.replace(ESCAPE_BACKSLASH, File.separator) : + scopeName; + if (!scopeNameValue.equals(scopeNameCheck)) { + continue; } + JSONObject el = new JSONObject(); + el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator) + 1)); + el.put(DATE, policy.getModifiedDate()); + el.put(VERSION, policy.getActiveVersion()); + el.put(SIZE, ""); + el.put(TYPE, "file"); + el.put(CREATED_BY, getUserName(policy.getCreatedBy())); + el.put(MODIFIED_BY, getUserName(policy.getModifiedBy())); + String roleType = Strings.isNullOrEmpty(roleByScope.get(scopeNameValue)) ? + roleByScope.get(ALLSCOPES) : roleByScope.get(scopeNameValue); + el.put(ROLETYPE, roleType); + resultList.add(el); } else if (!scopes.isEmpty() && scopes.contains(scopeNameValue)) { JSONObject el = new JSONObject(); el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator) + 1)); @@ -798,38 +772,49 @@ public class PolicyManagerServlet extends HttpServlet { } } + private List getDataByQueryFromController(final PolicyController controller, final String query, + final SimpleBindings params) { + final List activePolicies; + if (PolicyController.isjUnit()) { + activePolicies = controller.getDataByQuery(query, null); + } else { + activePolicies = controller.getDataByQuery(query, params); + } + return activePolicies; + } + private String checkScope(List resultList, String scopeName, PolicyEditorScopes scopeById, Map roleByScope) { String scope = scopeById.getScopeName(); + if (!scope.contains(File.separator)) { + return scopeName; + } + String targetScope = scope.substring(0, scope.lastIndexOf(File.separator)); + if (scopeName.contains(ESCAPE_BACKSLASH)) { + scopeName = scopeName.replace(ESCAPE_BACKSLASH, File.separator); + } if (scope.contains(File.separator)) { - String targetScope = scope.substring(0, scope.lastIndexOf(File.separator)); - if (scopeName.contains(ESCAPE_BACKSLASH)) { - scopeName = scopeName.replace(ESCAPE_BACKSLASH, File.separator); - } + scope = scope.substring(targetScope.length() + 1); if (scope.contains(File.separator)) { - scope = scope.substring(targetScope.length() + 1); - if (scope.contains(File.separator)) { - scope = scope.substring(0, scope.indexOf(File.separator)); - } + scope = scope.substring(0, scope.indexOf(File.separator)); } - if (scopeName.equalsIgnoreCase(targetScope)) { - JSONObject el = new JSONObject(); - el.put(NAME, scope); - el.put(DATE, scopeById.getModifiedDate()); - el.put(SIZE, ""); - el.put(TYPE, "dir"); - el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName()); - el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName()); - String roleType = roleByScope.get(scopeName); - if (roleType == null) { - roleType = roleByScope.get(scopeName + File.separator + scope); - if (roleType == null) { - roleType = roleByScope.get(ALLSCOPES); - } - } - el.put(ROLETYPE, roleType); - resultList.add(el); + } + if (scopeName.equalsIgnoreCase(targetScope)) { + JSONObject el = new JSONObject(); + el.put(NAME, scope); + el.put(DATE, scopeById.getModifiedDate()); + el.put(SIZE, ""); + el.put(TYPE, "dir"); + el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName()); + el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName()); + String roleType = roleByScope.get(ALLSCOPES); // Set default role type to ALL_SCOPES + if (!Strings.isNullOrEmpty(roleByScope.get(scopeName))) { + roleType = roleByScope.get(scopeName); + } else if (!Strings.isNullOrEmpty(roleByScope.get(scopeName + File.separator + scope))) { + roleType = roleByScope.get(scopeName + File.separator + scope); } + el.put(ROLETYPE, roleType); + resultList.add(el); } return scopeName; } @@ -866,7 +851,7 @@ public class PolicyManagerServlet extends HttpServlet { if (oldPath.endsWith(".xml")) { checkValidation = newPath.replace(".xml", ""); checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, - checkValidation.lastIndexOf(".")); + checkValidation.lastIndexOf('.')); checkValidation = checkValidation.substring(checkValidation.lastIndexOf(FORWARD_SLASH) + 1); if (!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)) { return error("Policy Rename Failed. The Name contains special characters."); @@ -892,11 +877,10 @@ public class PolicyManagerServlet extends HttpServlet { } PolicyController controller = getPolicyControllerInstance(); String query = "from PolicyVersion where POLICY_NAME like :scopeName"; - String scopeNamequery = FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME; SimpleBindings pvParams = new SimpleBindings(); pvParams.put(SCOPE_NAME, scopeName + "%"); List activePolicies = controller.getDataByQuery(query, pvParams); - List scopesList = controller.getDataByQuery(scopeNamequery, pvParams); + List scopesList = controller.getDataByQuery(FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME, pvParams); for (Object object : activePolicies) { PolicyVersion activeVersion = (PolicyVersion) object; String policyOldPath = activeVersion.getPolicyName().replace(File.separator, FORWARD_SLASH) + "." @@ -910,24 +894,20 @@ public class PolicyManagerServlet extends HttpServlet { scopeOfPolicyActiveInPDP.add(scope.replace(FORWARD_SLASH, File.separator)); } } - boolean rename = false; - if (activePolicies.size() != policyActiveInPDP.size()) { - rename = true; - } - - UserInfo userInfo = new UserInfo(); - userInfo.setUserLoginId(userId); + boolean rename = activePolicies.size() != policyActiveInPDP.size(); if (policyActiveInPDP.isEmpty()) { renameScope(scopesList, scopeName, newScopeName, controller); } else if (rename) { renameScope(scopesList, scopeName, newScopeName, controller); - for (String scope : scopeOfPolicyActiveInPDP) { + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId(userId); + scopeOfPolicyActiveInPDP.forEach(scope -> { PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes(); editorScopeEntity.setScopeName(scope.replace(BACKSLASH, BACKSLASH_8TIMES)); editorScopeEntity.setUserCreatedBy(userInfo); editorScopeEntity.setUserModifiedBy(userInfo); controller.saveData(editorScopeEntity); - } + }); } if (isActive) { return error("The Following policies rename failed. Since they are active in PDP Groups" @@ -981,11 +961,12 @@ public class PolicyManagerServlet extends HttpServlet { // Query the Policy Entity with oldPolicy Name String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf('.')); - String oldpolicyEntityquery = "FROM PolicyEntity where policyName like :policyEntityCheck and scope = :oldPolicySplit_0"; + String oldPolicyEntityQuery = "FROM PolicyEntity where policyName like :policyEntityCheck and scope = " + + ":oldPolicySplit_0"; SimpleBindings params = new SimpleBindings(); params.put("policyEntityCheck", policyEntityCheck + "%"); params.put("oldPolicySplit_0", oldPolicySplit[0]); - List oldEntityData = controller.getDataByQuery(oldpolicyEntityquery, params); + List oldEntityData = controller.getDataByQuery(oldPolicyEntityQuery, params); if (oldEntityData.isEmpty()) { return error( "Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin."); @@ -1019,7 +1000,6 @@ public class PolicyManagerServlet extends HttpServlet { oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId); } } - return success(); } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Renaming Policy" + e); @@ -1043,17 +1023,17 @@ public class PolicyManagerServlet extends HttpServlet { return policyName.split(":"); } - private void checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, - String oldScope, String removeoldPolicyExtension, String policyName, String newpolicyName, - String oldpolicyName, String userId) { + private void checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removeNewPolicyExtension, + String oldScope, String removeOldPolicyExtension, String policyName, String newPolicyName, + String oldPolicyName, String userId) { try { ConfigurationDataEntity configEntity = entity.getConfigurationData(); ActionBodyEntity actionEntity = entity.getActionBodyEntity(); PolicyController controller = getPolicyControllerInstance(); - String oldPolicyNameWithoutExtension = removeoldPolicyExtension; - String newPolicyNameWithoutExtension = removenewPolicyExtension; - if (removeoldPolicyExtension.endsWith(".xml")) { + String oldPolicyNameWithoutExtension = removeOldPolicyExtension; + String newPolicyNameWithoutExtension = removeNewPolicyExtension; + if (removeOldPolicyExtension.endsWith(".xml")) { oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf('.')); newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, @@ -1068,7 +1048,7 @@ public class PolicyManagerServlet extends HttpServlet { String oldConfigurationName = null; String newConfigurationName = null; - if (newpolicyName.contains(CONFIG2)) { + if (newPolicyName.contains(CONFIG2)) { oldConfigurationName = configEntity.getConfigurationName(); configEntity.setConfigurationName( configEntity.getConfigurationName().replace(oldScope + "." + oldPolicyNameWithoutExtension, @@ -1077,11 +1057,11 @@ public class PolicyManagerServlet extends HttpServlet { newConfigurationName = configEntity.getConfigurationName(); File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName); if (file.exists()) { - File renamefile = new File( + File renameFile = new File( PolicyController.getConfigHome() + File.separator + newConfigurationName); - file.renameTo(renamefile); + file.renameTo(renameFile); } - } else if (newpolicyName.contains(ACTION2)) { + } else if (newPolicyName.contains(ACTION2)) { oldConfigurationName = actionEntity.getActionBodyName(); actionEntity.setActionBody( actionEntity.getActionBody().replace(oldScope + "." + oldPolicyNameWithoutExtension, @@ -1090,9 +1070,9 @@ public class PolicyManagerServlet extends HttpServlet { newConfigurationName = actionEntity.getActionBodyName(); File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName); if (file.exists()) { - File renamefile = new File( + File renameFile = new File( PolicyController.getActionHome() + File.separator + newConfigurationName); - file.renameTo(renamefile); + file.renameTo(renameFile); } } controller.updateData(entity); @@ -1100,16 +1080,16 @@ public class PolicyManagerServlet extends HttpServlet { PolicyRestController restController = new PolicyRestController(); restController.notifyOtherPAPSToUpdateConfigurations("rename", newConfigurationName, oldConfigurationName); PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", - oldpolicyName); + oldPolicyName); versionEntity.setPolicyName(policyName); versionEntity.setModifiedBy(userId); controller.updateData(versionEntity); String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator) + 1); - String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator) + 1); + String moveOldPolicyCheck = oldPolicyName.substring(oldPolicyName.lastIndexOf(File.separator) + 1); if (movePolicyCheck.equals(moveOldPolicyCheck)) { - controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move"); + controller.watchPolicyFunction(versionEntity, oldPolicyName, "Move"); } else { - controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename"); + controller.watchPolicyFunction(versionEntity, oldPolicyName, "Rename"); } } catch (Exception e) { LOGGER.error(EXCEPTION_OCCURED + e); @@ -1204,11 +1184,11 @@ public class PolicyManagerServlet extends HttpServlet { String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')) .replace(FORWARD_SLASH, File.separator); - String newpolicyName = newPath.replace(FORWARD_SLASH, "."); + String newPolicyName = newPath.replace(FORWARD_SLASH, "."); - String orignalPolicyName = oldPath.replace(FORWARD_SLASH, "."); + String originalPolicyName = oldPath.replace(FORWARD_SLASH, "."); - String newPolicyCheck = newpolicyName; + String newPolicyCheck = newPolicyName; if (newPolicyCheck.contains(CONFIG2)) { newPolicyCheck = newPolicyCheck.replace(CONFIG, CONFIG1); } else if (newPolicyCheck.contains(ACTION2)) { @@ -1223,12 +1203,12 @@ public class PolicyManagerServlet extends HttpServlet { String checkValidation = newPolicySplit[1].replace(".xml", ""); checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, - checkValidation.lastIndexOf(".")); + checkValidation.lastIndexOf('.')); if (!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)) { return error("Policy Clone Failed. The Name contains special characters."); } - String[] oldPolicySplit = modifyPolicyName(orignalPolicyName); + String[] oldPolicySplit = modifyPolicyName(originalPolicyName); PolicyController controller = getPolicyControllerInstance(); @@ -1250,11 +1230,7 @@ public class PolicyManagerServlet extends HttpServlet { SimpleBindings peParams = new SimpleBindings(); peParams.put("oldPolicySplit_1", oldPolicySplit[1]); peParams.put("oldPolicySplit_0", oldPolicySplit[0]); - if (PolicyController.isjUnit()) { - queryData = controller.getDataByQuery(policyEntityquery, null); - } else { - queryData = controller.getDataByQuery(policyEntityquery, peParams); - } + queryData = getDataByQueryFromController(controller, policyEntityquery, peParams); if (!queryData.isEmpty()) { entity = (PolicyEntity) queryData.get(0); } @@ -1263,7 +1239,6 @@ public class PolicyManagerServlet extends HttpServlet { newPolicySplit[1], entity, userId); success = true; } - if (success) { PolicyVersion entityItem = new PolicyVersion(); entityItem.setActiveVersion(Integer.parseInt(version)); @@ -1274,9 +1249,7 @@ public class PolicyManagerServlet extends HttpServlet { entityItem.setModifiedDate(new Date()); controller.saveData(entityItem); } - LOGGER.debug("copy from: {} to: {}" + oldPath + newPath); - return success(); } catch (Exception e) { LOGGER.error("copy", e); @@ -1316,15 +1289,15 @@ public class PolicyManagerServlet extends HttpServlet { policyParams.put("exactScope", policyNamewithoutExtension); } - List policyEntityobjects = controller.getDataByQuery(query, policyParams); + List policyEntityObjects = controller.getDataByQuery(query, policyParams); String activePolicyName = null; boolean pdpCheck = false; if (path.endsWith(".xml")) { policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator); int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf('.') + 1)); if ("ALL".equals(deleteVersion)) { - if (!policyEntityobjects.isEmpty()) { - for (Object object : policyEntityobjects) { + if (!policyEntityObjects.isEmpty()) { + for (Object object : policyEntityObjects) { policyEntity = (PolicyEntity) object; String groupEntityquery = "from PolicyGroupEntity where policyid ='" + policyEntity.getPolicyId() + "'"; @@ -1334,24 +1307,8 @@ public class PolicyManagerServlet extends HttpServlet { pdpCheck = true; activePolicyName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); } else { - // Delete the entity from Elastic Search Database - String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); - restController.deleteElasticData(searchFileName); - // Delete the entity from Policy Entity table - controller.deleteData(policyEntity); - if (policyNamewithoutExtension.contains(CONFIG2)) { - Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator - + policyEntity.getConfigurationData().getConfigurationName())); - controller.deleteData(policyEntity.getConfigurationData()); - restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, - policyEntity.getConfigurationData().getConfigurationName()); - } else if (policyNamewithoutExtension.contains(ACTION2)) { - Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator - + policyEntity.getActionBodyEntity().getActionBodyName())); - controller.deleteData(policyEntity.getActionBodyEntity()); - restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, - policyEntity.getActionBodyEntity().getActionBodyName()); - } + deleteEntityFromEsAndPolicyEntityTable(controller, restController, policyEntity, + policyNamewithoutExtension); } } } @@ -1408,28 +1365,13 @@ public class PolicyManagerServlet extends HttpServlet { } // Delete the entity from Elastic Search Database - String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); - restController.deleteElasticData(searchFileName); - // Delete the entity from Policy Entity table - controller.deleteData(policyEntity); - if (policyNamewithoutExtension.contains(CONFIG2)) { - Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator - + policyEntity.getConfigurationData().getConfigurationName())); - controller.deleteData(policyEntity.getConfigurationData()); - restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, - policyEntity.getConfigurationData().getConfigurationName()); - } else if (policyNamewithoutExtension.contains(ACTION2)) { - Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator - + policyEntity.getActionBodyEntity().getActionBodyName())); - controller.deleteData(policyEntity.getActionBodyEntity()); - restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, - policyEntity.getActionBodyEntity().getActionBodyName()); - } + deleteEntityFromEsAndPolicyEntityTable(controller, restController, policyEntity, + policyNamewithoutExtension); if (version > 1) { int highestVersion = 0; - if (!policyEntityobjects.isEmpty()) { - for (Object object : policyEntityobjects) { + if (!policyEntityObjects.isEmpty()) { + for (Object object : policyEntityObjects) { policyEntity = (PolicyEntity) object; String policyEntityName = policyEntity.getPolicyName().replace(".xml", ""); int policyEntityVersion = Integer @@ -1465,18 +1407,18 @@ public class PolicyManagerServlet extends HttpServlet { } } else { List activePoliciesInPDP = new ArrayList<>(); - if (policyEntityobjects.isEmpty()) { + if (policyEntityObjects.isEmpty()) { String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '" + path.replace(BACKSLASH, ESCAPE_BACKSLASH) + PERCENT_AND_ID_GT_0; controller.executeQuery(policyScopeQuery); return success(); } - for (Object object : policyEntityobjects) { + for (Object object : policyEntityObjects) { policyEntity = (PolicyEntity) object; - String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId"; + String groupEntityQuery = "from PolicyGroupEntity where policyid = :policyEntityId"; SimpleBindings geParams = new SimpleBindings(); geParams.put("policyEntityId", policyEntity.getPolicyId()); - List groupobject = controller.getDataByQuery(groupEntityquery, geParams); + List groupobject = controller.getDataByQuery(groupEntityQuery, geParams); if (!groupobject.isEmpty()) { pdpCheck = true; activePoliciesInPDP.add(policyEntity.getScope() + "." + policyEntity.getPolicyName()); @@ -1520,15 +1462,14 @@ public class PolicyManagerServlet extends HttpServlet { .parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf('.') + 1)); activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf('.')) .replace(".", File.separator); - PolicyVersion insertactivePDPVersion = new PolicyVersion(); - insertactivePDPVersion.setPolicyName(activePDPPolicyName); - insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion); - insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion); - insertactivePDPVersion.setCreatedBy(userId); - insertactivePDPVersion.setModifiedBy(userId); - controller.saveData(insertactivePDPVersion); + PolicyVersion insertActivePDPVersion = new PolicyVersion(); + insertActivePDPVersion.setPolicyName(activePDPPolicyName); + insertActivePDPVersion.setHigherVersion(activePDPPolicyVersion); + insertActivePDPVersion.setActiveVersion(activePDPPolicyVersion); + insertActivePDPVersion.setCreatedBy(userId); + insertActivePDPVersion.setModifiedBy(userId); + controller.saveData(insertActivePDPVersion); } - return error("All the Policies has been deleted in Scope. Except the following list of Policies:" + activePoliciesInPDP); } else { @@ -1545,6 +1486,29 @@ public class PolicyManagerServlet extends HttpServlet { } } + private void deleteEntityFromEsAndPolicyEntityTable(final PolicyController controller, + final PolicyRestController restController, final PolicyEntity policyEntity, + final String policyNamewithoutExtension) throws IOException { + // Delete the entity from Elastic Search Database + String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); + restController.deleteElasticData(searchFileName); + // Delete the entity from Policy Entity table + controller.deleteData(policyEntity); + if (policyNamewithoutExtension.contains(CONFIG2)) { + Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + + policyEntity.getConfigurationData().getConfigurationName())); + controller.deleteData(policyEntity.getConfigurationData()); + restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, + policyEntity.getConfigurationData().getConfigurationName()); + } else if (policyNamewithoutExtension.contains(ACTION2)) { + Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + + policyEntity.getActionBodyEntity().getActionBodyName())); + controller.deleteData(policyEntity.getActionBodyEntity()); + restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, + policyEntity.getActionBodyEntity().getActionBodyName()); + } + } + // Edit the Policy private JSONObject editFile(JSONObject params) throws ServletException { // get content @@ -1566,12 +1530,7 @@ public class PolicyManagerServlet extends HttpServlet { SimpleBindings peParams = new SimpleBindings(); peParams.put(SPLIT_1, split[1]); peParams.put(SPLIT_0, split[0]); - List queryData; - if (PolicyController.isjUnit()) { - queryData = controller.getDataByQuery(query, null); - } else { - queryData = controller.getDataByQuery(query, peParams); - } + List queryData = getDataByQueryFromController(controller, query, peParams); PolicyEntity entity = (PolicyEntity) queryData.get(0); InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8)); @@ -1593,8 +1552,8 @@ public class PolicyManagerServlet extends HttpServlet { policyName = policyName.substring(0, policyName.lastIndexOf('.')); policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf('.') + 1)); - PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance(); - Objects.requireNonNull(setpolicyAdapter).configure(policyAdapter, entity); + PolicyAdapter setPolicyAdapter = PolicyAdapter.getInstance(); + Objects.requireNonNull(setPolicyAdapter).configure(policyAdapter, entity); policyAdapter.setParentPath(null); ObjectMapper mapper = new ObjectMapper(); @@ -1611,53 +1570,32 @@ public class PolicyManagerServlet extends HttpServlet { // Add Scopes private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException { PolicyController controller = getPolicyControllerInstance(); - String name = ""; try { - String userId = UserUtils.getUserSession(request).getOrgUserId(); - String path = params.getString("path"); - try { - if (params.has(SUB_SCOPENAME)) { - if (!"".equals(params.getString(SUB_SCOPENAME))) { - name = params.getString("path").replace(FORWARD_SLASH, File.separator) + File.separator - + params.getString(SUB_SCOPENAME); - } - } else { - name = params.getString(NAME); - } - } catch (Exception e) { - name = params.getString(NAME); - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope" + e); - } - String validateName; - if (name.contains(File.separator)) { - validateName = name.substring(name.lastIndexOf(File.separator) + 1); - } else { - validateName = name; - } + String name = getNameFromParams(params); + String validateName = + name.contains(File.separator) ? name.substring(name.lastIndexOf(File.separator) + 1) : name; if (!name.isEmpty()) { String validate = PolicyUtils.policySpecialCharValidator(validateName); if (!validate.contains(SUCCESS)) { return error(validate); } - } - LOGGER.debug("addFolder path: {} name: {}" + path + name); - if (!"".equals(name)) { + LOGGER.debug("addFolder path: {} name: {}" + params.getString("path") + name); if (name.startsWith(File.separator)) { name = name.substring(1); } PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, - SCOPE_NAME, name); - if (entity == null) { - UserInfo userInfo = new UserInfo(); - userInfo.setUserLoginId(userId); - PolicyEditorScopes newScope = new PolicyEditorScopes(); - newScope.setScopeName(name); - newScope.setUserCreatedBy(userInfo); - newScope.setUserModifiedBy(userInfo); - controller.saveData(newScope); - } else { + SCOPE_NAME, name); + if (entity != null) { return error("Scope Already Exists"); } + String userId = UserUtils.getUserSession(request).getOrgUserId(); + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId(userId); + PolicyEditorScopes newScope = new PolicyEditorScopes(); + newScope.setScopeName(name); + newScope.setUserCreatedBy(userInfo); + newScope.setUserModifiedBy(userInfo); + controller.saveData(newScope); } return success(); } catch (Exception e) { @@ -1666,6 +1604,24 @@ public class PolicyManagerServlet extends HttpServlet { } } + private String getNameFromParams(final JSONObject params) { + String name = ""; + try { + if (params.has(SUB_SCOPENAME)) { + if (!"".equals(params.getString(SUB_SCOPENAME))) { + name = params.getString("path").replace(FORWARD_SLASH, File.separator) + File.separator + + params.getString(SUB_SCOPENAME); + } + } else { + name = params.getString(NAME); + } + } catch (Exception e) { + name = params.getString(NAME); + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occurred While Adding Scope" + e); + } + return name; + } + // Return Error Object private JSONObject error(String msg) throws ServletException { try { @@ -1701,4 +1657,4 @@ public class PolicyManagerServlet extends HttpServlet { public static void setTestUserId(String testUserId) { PolicyManagerServlet.testUserId = testUserId; } -} \ No newline at end of file +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java index a1bb73354..1fccfda78 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. + * Modifications Copyright (C) 2019 Bell Canada * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,11 +25,11 @@ package org.onap.policy.admin; import java.io.File; import java.text.DateFormat; import java.text.SimpleDateFormat; +import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Properties; -import javax.mail.MessagingException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.script.SimpleBindings; @@ -82,9 +83,8 @@ public class PolicyNotificationMail{ * @param policyName Name of the policy for which notification is to be sent * @param mode kind of operation done on the policy * @param policyNotificationDao database access object for policy - * @throws MessagingException */ - public void sendMail(PolicyVersion entityItem, String policyName, String mode, CommonClassDao policyNotificationDao) throws MessagingException { + public void sendMail(PolicyVersion entityItem, String policyName, String mode, CommonClassDao policyNotificationDao) { String subject = ""; String message = ""; @@ -130,26 +130,25 @@ public class PolicyNotificationMail{ String policyFileName = findPolicyFileName(entityItem); String query = "from WatchPolicyNotificationTable where policyName like:policyFileName"; List watchList = findWatchList(policyNotificationDao, policyFileName, query); - if (watchList == null) { - return; + if (!watchList.isEmpty()) { + composeAndSendMail(mode, policyNotificationDao, subject, message, checkPolicyName, watchList); } - - composeAndSendMail(mode, policyNotificationDao, subject, message, checkPolicyName, watchList); } private List findWatchList(CommonClassDao policyNotificationDao, String policyFileName, String query) { SimpleBindings params = new SimpleBindings(); params.put("policyFileName", policyFileName); List watchList; - if(PolicyController.isjUnit()){ + if (PolicyController.isjUnit()) { watchList = policyNotificationDao.getDataByQuery(query, null); - }else{ + } else { watchList = policyNotificationDao.getDataByQuery(query, params); } - if(watchList == null || watchList.isEmpty()) { - policyLogger.debug("List of policy being watched is either null or empty, hence return without sending mail"); - return null; + if (watchList == null || watchList.isEmpty()) { + policyLogger + .debug("List of policy being watched is either null or empty, hence return without sending mail"); + watchList = new ArrayList<>(); } return watchList; } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java index d77f52b0e..6935c7203 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. + * Modifications Copyright (C) 2019 Bell Canada * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,7 +34,6 @@ import java.util.ArrayList; import java.util.Base64; import java.util.List; -import javax.mail.MessagingException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -136,25 +136,28 @@ public class PolicyRestController extends RestrictedBaseController{ } } - private void updateAndSendToPAP(HttpServletRequest request, HttpServletResponse response, String userId, ObjectMapper mapper) throws IOException, MessagingException { + private void updateAndSendToPAP(HttpServletRequest request, HttpServletResponse response, String userId, ObjectMapper mapper) throws IOException { JsonNode root = mapper.readTree(request.getReader()); - - policyLogger.info("****************************************Logging UserID while Create/Update Policy**************************************************"); - policyLogger.info(USER_ID + userId + "Policy Data Object: "+ root.get(PolicyController.getPolicydata()).get("policy").toString()); - policyLogger.info("***********************************************************************************************************************************"); - - PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class); - + policyLogger.info( + "****************************************Logging UserID while Create/Update Policy**************************************************"); + policyLogger.info( + USER_ID + userId + "Policy Data Object: " + root.get(PolicyController.getPolicydata()).get("policy") + .toString()); + policyLogger.info( + "***********************************************************************************************************************************"); + + PolicyRestAdapter policyData = mapper + .readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class); modifyPolicyData(root, policyData); - if(policyData.getConfigPolicyType() != null){ - if(CLOSED_LOOP_FAULT.equalsIgnoreCase(policyData.getConfigPolicyType())){ + if (policyData.getConfigPolicyType() != null) { + if (CLOSED_LOOP_FAULT.equalsIgnoreCase(policyData.getConfigPolicyType())) { policyData = new CreateClosedLoopFaultController().setDataToPolicyRestAdapter(policyData, root); - }else if(FIREWALL_CONFIG.equalsIgnoreCase(policyData.getConfigPolicyType())){ + } else if (FIREWALL_CONFIG.equalsIgnoreCase(policyData.getConfigPolicyType())) { policyData = new CreateFirewallController().setDataToPolicyRestAdapter(policyData); - }else if(MICRO_SERVICE.equalsIgnoreCase(policyData.getConfigPolicyType())){ + } else if (MICRO_SERVICE.equalsIgnoreCase(policyData.getConfigPolicyType())) { policyData = new CreateDcaeMicroServiceController().setDataToPolicyRestAdapter(policyData, root); - }else if(OPTIMIZATION.equalsIgnoreCase(policyData.getConfigPolicyType())){ + } else if (OPTIMIZATION.equalsIgnoreCase(policyData.getConfigPolicyType())) { policyData = new CreateOptimizationController().setDataToPolicyRestAdapter(policyData, root); } } @@ -165,17 +168,18 @@ public class PolicyRestController extends RestrictedBaseController{ String body = PolicyUtils.objectToJsonString(policyData); String uri = request.getRequestURI(); ResponseEntity responseEntity = sendToPAP(body, uri, HttpMethod.POST); - if(responseEntity != null && responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)){ + if (responseEntity != null && responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)) { result = "PolicyExists"; - }else if(responseEntity != null){ - result = responseEntity.getBody().toString(); + } else if (responseEntity != null) { + result = responseEntity.getBody().toString(); String policyName = responseEntity.getHeaders().get(POLICY_NAME).get(0); - if(policyData.isEditPolicy() && SUCCESS.equalsIgnoreCase(result)){ + if (policyData.isEditPolicy() && SUCCESS.equalsIgnoreCase(result)) { PolicyNotificationMail email = new PolicyNotificationMail(); String mode = "EditPolicy"; String watchPolicyName = policyName.replace(XML, ""); - String version = watchPolicyName.substring(watchPolicyName.lastIndexOf('.')+1); - watchPolicyName = watchPolicyName.substring(0, watchPolicyName.lastIndexOf('.')).replace(".", File.separator); + String version = watchPolicyName.substring(watchPolicyName.lastIndexOf('.') + 1); + watchPolicyName = watchPolicyName.substring(0, watchPolicyName.lastIndexOf('.')) + .replace(".", File.separator); String policyVersionName = watchPolicyName.replace(".", File.separator); watchPolicyName = watchPolicyName + "." + version + XML; PolicyVersion entityItem = new PolicyVersion(); @@ -184,8 +188,8 @@ public class PolicyRestController extends RestrictedBaseController{ entityItem.setModifiedBy(userId); email.sendMail(entityItem, watchPolicyName, mode, commonClassDao); } - }else{ - result = "Response is null from PAP"; + } else { + result = "Response is null from PAP"; } response.setCharacterEncoding(PolicyController.getCharacterencoding()); @@ -343,10 +347,11 @@ public class PolicyRestController extends RestrictedBaseController{ return null; } - private void checkURI(HttpServletRequest request, String uri, HttpURLConnection connection, FileItem item) throws IOException { + private void checkURI(HttpServletRequest request, String uri, HttpURLConnection connection, FileItem item) + throws IOException { String boundary; - if(!(uri.endsWith("set_BRMSParamData") || uri.contains(IMPORT_DICTIONARY))){ - connection.setRequestProperty(CONTENT_TYPE,PolicyController.getContenttype()); + if (!(uri.endsWith("set_BRMSParamData") || uri.contains(IMPORT_DICTIONARY))) { + connection.setRequestProperty(CONTENT_TYPE, PolicyController.getContenttype()); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = getJsonNode(request, mapper); @@ -358,26 +363,24 @@ public class PolicyRestController extends RestrictedBaseController{ String json = mapper1.writeValueAsString(obj); // send current configuration - try(InputStream content = new ByteArrayInputStream(json.getBytes()); + try (InputStream content = new ByteArrayInputStream(json.getBytes()); OutputStream os = connection.getOutputStream()) { int count = IOUtils.copy(content, os); if (policyLogger.isDebugEnabled()) { policyLogger.debug("copied to output, bytes=" + count); } } - }else{ - if(uri.endsWith("set_BRMSParamData")){ - connection.setRequestProperty(CONTENT_TYPE,PolicyController.getContenttype()); - try (OutputStream os = connection.getOutputStream()) { - IOUtils.copy((InputStream) request.getInputStream(), os); - } - }else{ - boundary = "===" + System.currentTimeMillis() + "==="; - connection.setRequestProperty(CONTENT_TYPE,"multipart/form-data; boundary=" + boundary); - try (OutputStream os = connection.getOutputStream()) { - if(item != null){ - IOUtils.copy((InputStream) item.getInputStream(), os); - } + } else if (uri.endsWith("set_BRMSParamData")) { + connection.setRequestProperty(CONTENT_TYPE, PolicyController.getContenttype()); + try (OutputStream os = connection.getOutputStream()) { + IOUtils.copy(request.getInputStream(), os); + } + } else { + boundary = "===" + System.currentTimeMillis() + "==="; + connection.setRequestProperty(CONTENT_TYPE, "multipart/form-data; boundary=" + boundary); + try (OutputStream os = connection.getOutputStream()) { + if (item != null) { + IOUtils.copy(item.getInputStream(), os); } } } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java index 96205c5b1..7e0aef2e9 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java @@ -3,13 +3,14 @@ * ONAP Policy Engine * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Bell Canada * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -39,24 +40,23 @@ import com.fasterxml.jackson.databind.ObjectMapper; @Controller @RequestMapping("/") -public class PolicyUserInfoController extends RestrictedBaseController{ - - private static final Logger LOGGER = FlexLogger.getLogger(PolicyUserInfoController.class); - - @RequestMapping(value="/get_PolicyUserInfo", method = RequestMethod.GET) - public void getPolicyUserInfo(HttpServletRequest request, HttpServletResponse response){ - JsonMessage msg = null; - try { - String userId = UserUtils.getUserSession(request).getOrgUserId(); - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("userid", userId); - msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } catch (Exception e) { - LOGGER.error("Exception Occured"+e); - } - } +public class PolicyUserInfoController extends RestrictedBaseController { + private static final Logger LOGGER = FlexLogger.getLogger(PolicyUserInfoController.class); + + @RequestMapping(value = "/get_PolicyUserInfo", method = RequestMethod.GET) + public void getPolicyUserInfo(HttpServletRequest request, HttpServletResponse response) { + JsonMessage msg; + try { + String userId = UserUtils.getUserSession(request).getOrgUserId(); + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("userid", userId); + msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } catch (Exception e) { + LOGGER.error("Exception Occurred" + e); + } + } } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java index c09944c2f..2ccc92eb3 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. + * Modifications Copyright (C) 2019 Bell Canada * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,8 +22,6 @@ package org.onap.policy.admin; - - import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -33,6 +32,7 @@ import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; +import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.HashMap; @@ -74,7 +74,7 @@ import org.onap.policy.common.logging.flexlogger.Logger; public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyEngine { private static final Logger LOGGER = FlexLogger.getLogger(RESTfulPAPEngine.class); - private static final String groupID = "groupId="; + private static final String GROUP_ID = "groupId="; // // URL of the PAP Servlet that this Admin Console talks to @@ -83,7 +83,7 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP /** * Set up link with PAP Servlet and get our initial set of Groups - * @throws Exception + * @throws PAPException When failing to register with PAP */ public RESTfulPAPEngine (String myURLString) throws PAPException { // @@ -112,40 +112,38 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP } } - // // High-level commands used by the Admin Console code through the PAPEngine Interface // @Override public OnapPDPGroup getDefaultGroup() throws PAPException { - return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID, "default="); + return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID, "default="); } @Override public void setDefaultGroup(OnapPDPGroup group) throws PAPException { - sendToPAP("POST", null, null, null, groupID + group.getId(), "default=true"); + sendToPAP("POST", null, null, null, GROUP_ID + group.getId(), "default=true"); } @SuppressWarnings("unchecked") @Override public Set getOnapPDPGroups() throws PAPException { Set newGroupSet; - newGroupSet = (Set) this.sendToPAP("GET", null, Set.class, StdPDPGroup.class, groupID); + newGroupSet = (Set) this.sendToPAP("GET", null, Set.class, StdPDPGroup.class, GROUP_ID); return Collections.unmodifiableSet(newGroupSet); } - @Override public OnapPDPGroup getGroup(String id) throws PAPException { - return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID + id); + return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID + id); } @Override public void newGroup(String name, String description) throws PAPException { - String escapedName = null; - String escapedDescription = null; + String escapedName; + String escapedDescription; try { escapedName = URLEncoder.encode(name, "UTF-8"); escapedDescription = URLEncoder.encode(description, "UTF-8"); @@ -153,10 +151,9 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP throw new PAPException("Unable to send name or description to PAP: " + e.getMessage() +e); } - this.sendToPAP("POST", null, null, null, groupID, "groupName="+escapedName, "groupDescription=" + escapedDescription); + this.sendToPAP("POST", null, null, null, GROUP_ID, "groupName="+escapedName, "groupDescription=" + escapedDescription); } - /** * Update the configuration on the PAP for a single Group. * @@ -166,24 +163,17 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP */ @Override public void updateGroup(OnapPDPGroup group) throws PAPException { - try { - // // ASSUME that all of the policies mentioned in this group are already located in the correct directory on the PAP! // // Whenever a Policy is added to the group, that file must be automatically copied to the PAP from the Workspace. // - - // Copy all policies from the local machine's workspace to the PAP's PDPGroup directory. // This is not efficient since most of the policies will already exist there. // However, the policy files are (probably!) not too huge, and this is a good way to ensure that any corrupted files on the PAP get refreshed. - - // now update the group object on the PAP - - sendToPAP("PUT", group, null, null, groupID + group.getId()); + sendToPAP("PUT", group, null, null, GROUP_ID + group.getId()); } catch (Exception e) { String message = "Unable to PUT policy '" + group.getId() + "', e:" + e; LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); @@ -191,15 +181,13 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP } } - @Override - public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup) - throws PAPException { + public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup) throws PAPException { String moveToGroupString = null; if (newGroup != null) { moveToGroupString = "movePDPsToGroupId=" + newGroup.getId(); } - sendToPAP("DELETE", null, null, null, groupID + group.getId(), moveToGroupString); + sendToPAP("DELETE", null, null, null, GROUP_ID + group.getId(), moveToGroupString); } @Override @@ -207,41 +195,36 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP return getPDPGroup(pdp.getId()); } - public OnapPDPGroup getPDPGroup(String pdpId) throws PAPException { - return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID, "pdpId=" + pdpId, "getPDPGroup="); + return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID, "pdpId=" + pdpId, "getPDPGroup="); } @Override public OnapPDP getPDP(String pdpId) throws PAPException { - return (OnapPDP)sendToPAP("GET", null, null, StdPDP.class, groupID, "pdpId=" + pdpId); + return (OnapPDP)sendToPAP("GET", null, null, StdPDP.class, GROUP_ID, "pdpId=" + pdpId); } @Override public void newPDP(String id, OnapPDPGroup group, String name, String description, int jmxport) throws PAPException { StdPDP newPDP = new StdPDP(id, name, description, jmxport); - sendToPAP("PUT", newPDP, null, null, groupID + group.getId(), "pdpId=" + id); - return; + sendToPAP("PUT", newPDP, null, null, GROUP_ID + group.getId(), "pdpId=" + id); } @Override public void movePDP(OnapPDP pdp, OnapPDPGroup newGroup) throws PAPException { - sendToPAP("POST", null, null, null, groupID + newGroup.getId(), "pdpId=" + pdp.getId()); - return; + sendToPAP("POST", null, null, null, GROUP_ID + newGroup.getId(), "pdpId=" + pdp.getId()); } @Override public void updatePDP(OnapPDP pdp) throws PAPException { OnapPDPGroup group = getPDPGroup(pdp); - sendToPAP("PUT", pdp, null, null, groupID + group.getId(), "pdpId=" + pdp.getId()); - return; + sendToPAP("PUT", pdp, null, null, GROUP_ID + group.getId(), "pdpId=" + pdp.getId()); } @Override public void removePDP(OnapPDP pdp) throws PAPException { OnapPDPGroup group = getPDPGroup(pdp); - sendToPAP("DELETE", null, null, null, groupID + group.getId(), "pdpId=" + pdp.getId()); - return; + sendToPAP("DELETE", null, null, null, GROUP_ID + group.getId(), "pdpId=" + pdp.getId()); } //Validate the Policy Data @@ -257,8 +240,6 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP @Override public void publishPolicy(String id, String name, boolean isRoot, InputStream policy, OnapPDPGroup group) throws PAPException { - - // copy the (one) file into the target directory on the PAP servlet copyFile(id, group, policy); @@ -268,8 +249,6 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP // tell the PAP servlet to include the policy in the configuration updateGroup(group); - - return; } /** @@ -285,7 +264,7 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP public void copyFile(String policyId, OnapPDPGroup group, InputStream policy) throws PAPException { // send the policy file to the PAP Servlet try { - sendToPAP("POST", policy, null, null, groupID + group.getId(), "policyId="+policyId); + sendToPAP("POST", policy, null, null, GROUP_ID + group.getId(), "policyId="+policyId); } catch (Exception e) { String message = "Unable to PUT policy '" + policyId + "', e:" + e; LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); @@ -293,9 +272,8 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP } } - @Override - public void copyPolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException { + public void copyPolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException { if (policy == null || group == null) { throw new PAPException("Null input policy="+policy+" group="+group); } @@ -309,12 +287,10 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP } @Override - public void removePolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException { + public void removePolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException { throw new PAPException("NOT IMPLEMENTED"); - } - /** * Special operation - Similar to the normal PAP operations but this one contacts the PDP directly * to get detailed status info. @@ -328,7 +304,6 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP return (StdPDPStatus)sendToPAP("GET", pdp, null, StdPDPStatus.class); } - // // Internal Operations called by the PAPEngine Interface methods // @@ -347,7 +322,7 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP * @param responseContentClass * @param parameters * @return - * @throws Exception + * @throws PAPException */ @SuppressWarnings({ "rawtypes", "unchecked" }) private Object sendToPAP(String method, Object content, Class collectionTypeClass, Class responseContentClass, String... parameters ) throws PAPException { @@ -356,37 +331,34 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP LOGGER.info("User Id is " + papID); String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)); Base64.Encoder encoder = Base64.getEncoder(); - String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8)); + String encoding = encoder.encodeToString((papID + ":" + papPass).getBytes(StandardCharsets.UTF_8)); Object contentObj = content; LOGGER.info("Encoding for the PAP is: " + encoding); try { String fullURL = papServletURLString; if (parameters != null && parameters.length > 0) { StringBuilder queryString = new StringBuilder(); - for (String p : parameters) { - queryString.append("&" + p); - } + Arrays.stream(parameters).map(p -> "&" + p).forEach(queryString::append); fullURL += "?" + queryString.substring(1); } // special case - Status (actually the detailed status) comes from the PDP directly, not the PAP - if ("GET".equals(method) && (contentObj instanceof OnapPDP) && responseContentClass == StdPDPStatus.class) { + if ("GET".equals(method) && (contentObj instanceof OnapPDP) && responseContentClass == StdPDPStatus.class) { // Adjust the url and properties appropriately - String pdpID =((OnapPDP)contentObj).getId(); + String pdpID = ((OnapPDP) contentObj).getId(); fullURL = pdpID + "?type=Status"; contentObj = null; - if(CheckPDP.validateID(pdpID)){ + if (CheckPDP.validateID(pdpID)) { encoding = CheckPDP.getEncoding(pdpID); } } - URL url = new URL(fullURL); // // Open up the connection // - connection = (HttpURLConnection)url.openConnection(); + connection = (HttpURLConnection) url.openConnection(); // // Setup our method and headers // @@ -410,7 +382,7 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP } else { // The contentObj is an object to be encoded in JSON ObjectMapper mapper = new ObjectMapper(); - mapper.writeValue(connection.getOutputStream(), contentObj); + mapper.writeValue(connection.getOutputStream(), contentObj); } } // @@ -425,18 +397,18 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP String isValidData = connection.getHeaderField("isValidData"); String isSuccess = connection.getHeaderField("successMapKey"); Map successMap = new HashMap<>(); - if (isValidData != null && "true".equalsIgnoreCase(isValidData)){ + if ("true".equalsIgnoreCase(isValidData)) { LOGGER.info("Policy Data is valid."); return true; - } else if (isValidData != null && "false".equalsIgnoreCase(isValidData)) { + } else if ("false".equalsIgnoreCase(isValidData)) { LOGGER.info("Policy Data is invalid."); return false; - } else if (isSuccess != null && "success".equalsIgnoreCase(isSuccess)) { - LOGGER.info("Policy Created Successfully!" ); + } else if ("success".equalsIgnoreCase(isSuccess)) { + LOGGER.info("Policy Created Successfully!"); String finalPolicyPath = connection.getHeaderField("finalPolicyPath"); successMap.put("success", finalPolicyPath); return successMap; - } else if (isSuccess != null && "error".equalsIgnoreCase(isSuccess)) { + } else if ("error".equalsIgnoreCase(isSuccess)) { LOGGER.info("There was an error while creating the policy!"); successMap.put("error", "error"); return successMap; @@ -450,21 +422,21 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP if (collectionTypeClass != null) { // collection of objects expected final CollectionType javaType = - mapper.getTypeFactory().constructCollectionType(collectionTypeClass, responseContentClass); - + mapper.getTypeFactory().constructCollectionType(collectionTypeClass, responseContentClass); return mapper.readValue(json, javaType); } else { // single value object expected return mapper.readValue(json, responseContentClass); } } - - } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) { + } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) { // redirection String newURL = connection.getHeaderField("Location"); if (newURL == null) { - LOGGER.error("No Location header to redirect to when response code="+connection.getResponseCode()); - throw new IOException("No redirect Location header when response code="+connection.getResponseCode()); + LOGGER + .error("No Location header to redirect to when response code=" + connection.getResponseCode()); + throw new IOException( + "No redirect Location header when response code=" + connection.getResponseCode()); } int qIndex = newURL.indexOf('?'); if (qIndex > 0) { @@ -473,12 +445,13 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP LOGGER.info("Redirect seen. Redirecting " + fullURL + " to " + newURL); return newURL; } else { - LOGGER.warn("Unexpected response code: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); - throw new IOException("Server Response: " + connection.getResponseCode() + ": " + connection.getResponseMessage()); + LOGGER.warn("Unexpected response code: " + connection.getResponseCode() + " message: " + connection + .getResponseMessage()); + throw new IOException( + "Server Response: " + connection.getResponseCode() + ": " + connection.getResponseMessage()); } - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "HTTP Request/Response to PAP: " + e,e); + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "HTTP Request/Response to PAP: " + e, e); throw new PAPException("Request/Response threw :" + e); } finally { // cleanup the connection @@ -515,7 +488,7 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP } private String getJsonString(final HttpURLConnection connection) throws IOException { - String json = null; + String json; // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file) try(java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream())) { scanner.useDelimiter("\\A"); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java index ea0dce2c0..b116af6ef 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java @@ -3,6 +3,7 @@ * ONAP Policy Engine * ================================================================================ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Bell Canada * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,8 +66,6 @@ import org.onap.policy.rest.jpa.FunctionDefinition; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.onap.policy.xacml.util.XACMLPolicyScanner; - - public class HumanPolicyComponent { private static final Logger LOGGER = FlexLogger.getLogger(HumanPolicyComponent.class); @@ -218,8 +217,7 @@ class HtmlProcessor extends SimpleCallback { throw new IllegalArgumentException(msg); } - if (policyObject == null - || (!(policyObject instanceof PolicySetType) && !(policyObject instanceof PolicyType))) { + if ((!(policyObject instanceof PolicySetType) && !(policyObject instanceof PolicyType))) { String msg = "Invalid unmarshalled object: " + policyObject; LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + msg); throw new IllegalArgumentException(msg); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java index a556beeaa..578258403 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java @@ -3,6 +3,7 @@ * ONAP Policy Engine * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Bell Canada * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +23,6 @@ package org.onap.policy.controller; import java.util.ArrayList; import java.util.HashMap; -import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -33,7 +33,6 @@ import javax.xml.bind.JAXBElement; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.rest.adapter.PolicyRestAdapter; -import org.onap.policy.rest.jpa.PolicyEntity; import org.onap.portalsdk.core.controller.RestrictedBaseController; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @@ -56,132 +55,149 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; @RequestMapping({ "/" }) public class ActionPolicyController extends RestrictedBaseController { private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicyController.class); + private static final String PERFORMER_ATTRIBUTE_ID = "performer"; + private static final String DYNAMIC_RULE_ALGORITHM_FIELD_1 = "dynamicRuleAlgorithmField1"; + private static final String DYNAMIC_RULE_ALGORITHM_FIELD_2 = "dynamicRuleAlgorithmField2"; + private LinkedList ruleAlgorithmTracker; + private Map performer = new HashMap<>(); + private List ruleAlgorithmList; public ActionPolicyController() { // Default Constructor } - private ArrayList attributeList; - protected LinkedList ruleAlgoirthmTracker; - public static final String PERFORMER_ATTRIBUTEID = "performer"; - protected Map performer = new HashMap<>(); - private ArrayList ruleAlgorithmList; - - public void prePopulateActionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - attributeList = new ArrayList<>(); + public void prePopulateActionPolicyData(PolicyRestAdapter policyAdapter) { ruleAlgorithmList = new ArrayList<>(); performer.put("PDP", "PDPAction"); performer.put("PEP", "PEPAction"); if (policyAdapter.getPolicyData() instanceof PolicyType) { - Object policyData = policyAdapter.getPolicyData(); - PolicyType policy = (PolicyType) policyData; - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - String policyNameValue = policyAdapter.getPolicyName() - .substring(policyAdapter.getPolicyName().indexOf('_') + 1); - policyAdapter.setPolicyName(policyNameValue); - String description = ""; - try { - description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); - } catch (Exception e) { - LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e); - description = policy.getDescription(); - } - policyAdapter.setPolicyDescription(description); - // Get the target data under policy for Action. + PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); + + // 1. Set policy-name, policy-filename and description to Policy Adapter + setPolicyAdapterPolicyNameAndDesc(policyAdapter, policy); + + // 2a. Get the target data under policy for Action. TargetType target = policy.getTarget(); - if (target != null) { - // under target we have AnyOFType - List anyOfList = target.getAnyOf(); - if (anyOfList != null) { - Iterator iterAnyOf = anyOfList.iterator(); - while (iterAnyOf.hasNext()) { - AnyOfType anyOf = iterAnyOf.next(); - // Under AntOfType we have AllOfType - List allOfList = anyOf.getAllOf(); - if (allOfList != null) { - Iterator iterAllOf = allOfList.iterator(); - while (iterAllOf.hasNext()) { - AllOfType allOf = iterAllOf.next(); - // Under AllOfType we have Mathch. - List matchList = allOf.getMatch(); - if (matchList != null) { - Iterator iterMatch = matchList.iterator(); - while (iterMatch.hasNext()) { - MatchType match = iterMatch.next(); - // - // Under the match we have attributevalue and - // attributeDesignator. So,finally down to the actual attribute. - // - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - // Component attributes are saved under Target here we are fetching them back. - // One row is default so we are not adding dynamic component at index 0. - Map attribute = new HashMap<>(); - attribute.put("key", attributeId); - attribute.put("value", value); - attributeList.add(attribute); - } - } - policyAdapter.setAttributes(attributeList); - } - } - } + if (target == null) { + return; + } + + // 2b. Set attributes to Policy Adapter + setPolicyAdapterAttributes(policyAdapter, target.getAnyOf()); + + List ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); + // Under rule we have Condition and obligation. + for (Object o : ruleList) { + if (!(o instanceof RuleType)) { + continue; } + // 3. Set rule-algorithm choices to Policy Adapter + setPolicyAdapterRuleAlgorithmschoices(policyAdapter, (RuleType) o); - List ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); - // Under rule we have Condition and obligation. - for (Object o : ruleList) { - if (o instanceof RuleType) { - ConditionType condition = ((RuleType) o).getCondition(); - ObligationExpressionsType obligations = ((RuleType) o).getObligationExpressions(); - if (condition != null) { - int index = 0; - ApplyType actionApply = (ApplyType) condition.getExpression().getValue(); - ruleAlgoirthmTracker = new LinkedList<>(); - // Populating Rule Algorithms starting from compound. - prePopulateCompoundRuleAlgorithm(index, actionApply); - } - policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList); - // get the Obligation data under the rule for Form elements. - if (obligations != null) { - // Under the obligationExpressions we have obligationExpression. - List obligationList = obligations.getObligationExpression(); - if (obligationList != null) { - Iterator iterObligation = obligationList.iterator(); - while (iterObligation.hasNext()) { - ObligationExpressionType obligation = iterObligation.next(); - policyAdapter.setActionAttributeValue(obligation.getObligationId()); - // Under the obligationExpression we have attributeAssignmentExpression. - List attributeAssignmentExpressionList = obligation - .getAttributeAssignmentExpression(); - if (attributeAssignmentExpressionList != null) { - Iterator iterAttributeAssignmentExpression = attributeAssignmentExpressionList - .iterator(); - while (iterAttributeAssignmentExpression.hasNext()) { - AttributeAssignmentExpressionType attributeAssignmentExpression = iterAttributeAssignmentExpression - .next(); - String attributeID = attributeAssignmentExpression.getAttributeId(); - AttributeValueType attributeValue = (AttributeValueType) attributeAssignmentExpression - .getExpression().getValue(); - if (attributeID.equals(PERFORMER_ATTRIBUTEID)) { - for ( Entry entry: performer.entrySet()) { - String key = entry.getKey(); - String keyValue = entry.getValue(); - if (keyValue.equals(attributeValue.getContent().get(0))) { - policyAdapter.setActionPerformer(key); - } - } - } - } - } - } - } - } + // 4a. Get the Obligation data under the rule for Form elements. + ObligationExpressionsType obligations = ((RuleType) o).getObligationExpressions(); + + // 4b. Set action attribute-value and action-performer to Policy Adapter + setPolicyAdapterActionData(policyAdapter, obligations); + } + } + } + + private void setPolicyAdapterActionData(PolicyRestAdapter policyAdapter, ObligationExpressionsType obligations) { + if (obligations == null) { + return; + } + // Under the obligationExpressions we have obligationExpression. + List obligationList = obligations.getObligationExpression(); + if (obligationList == null) { + return; + } + for (ObligationExpressionType obligation : obligationList) { + policyAdapter.setActionAttributeValue(obligation.getObligationId()); + // Under the obligationExpression we have attributeAssignmentExpression. + List attributeAssignmentExpressionList = obligation + .getAttributeAssignmentExpression(); + if (attributeAssignmentExpressionList == null) { + continue; + } + for (AttributeAssignmentExpressionType attributeAssignmentExpression : attributeAssignmentExpressionList) { + String attributeID = attributeAssignmentExpression.getAttributeId(); + AttributeValueType attributeValue = (AttributeValueType) attributeAssignmentExpression + .getExpression().getValue(); + if (!attributeID.equals(PERFORMER_ATTRIBUTE_ID)) { + continue; + } + performer.forEach((key, keyValue) -> { + if (keyValue.equals(attributeValue.getContent().get(0))) { + policyAdapter.setActionPerformer(key); } + }); + } + } + } + + private void setPolicyAdapterPolicyNameAndDesc(PolicyRestAdapter policyAdapter, PolicyType policy) { + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = policyAdapter.getPolicyName() + .substring(policyAdapter.getPolicyName().indexOf('_') + 1); + policyAdapter.setPolicyName(policyNameValue); + String description; + try { + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + } catch (Exception e) { + LOGGER.error("Error while collecting the description tag in ActionPolicy " + policyNameValue, e); + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + } + + private void setPolicyAdapterRuleAlgorithmschoices(PolicyRestAdapter policyAdapter, RuleType o) { + ConditionType condition = o.getCondition(); + if (condition != null) { + int index = 0; + ApplyType actionApply = (ApplyType) condition.getExpression().getValue(); + ruleAlgorithmTracker = new LinkedList<>(); + // Populating Rule Algorithms starting from compound. + prePopulateCompoundRuleAlgorithm(index, actionApply); + } + policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList); + } + + private void setPolicyAdapterAttributes(PolicyRestAdapter policyAdapter, List anyOfList) { + List attributeList = new ArrayList<>(); + if (anyOfList == null) { + return; + } + // under target we have AnyOFType + for (AnyOfType anyOf : anyOfList) { + // Under AntOfType we have AllOfType + List allOfList = anyOf.getAllOf(); + if (allOfList == null) { + continue; + } + // Under AllOfType we have Match. + for (AllOfType allOfType : allOfList) { + List matchList = allOfType.getMatch(); + if (matchList != null) { + // + // Under the match we have attributeValue and + // attributeDesignator. So,finally down to the actual attribute. + // + // Component attributes are saved under Target here we are fetching them back. + // One row is default so we are not adding dynamic component at index 0. + matchList.forEach(match -> { + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + Map attribute = new HashMap<>(); + attribute.put("key", attributeId); + attribute.put("value", value); + attributeList.add(attribute); + }); } + policyAdapter.setAttributes(attributeList); } } } @@ -197,7 +213,7 @@ public class ActionPolicyController extends RestrictedBaseController { // Check to see if Attribute Value exists, if yes then it is not a compound rule if (jaxbElement.getValue() instanceof AttributeValueType) { prePopulateRuleAlgorithms(index, actionApply, jaxbActionTypes); - ruleAlgoirthmTracker.addLast(index); + ruleAlgorithmTracker.addLast(index); isCompoundRule = false; index++; } @@ -221,11 +237,11 @@ public class ActionPolicyController extends RestrictedBaseController { } rule.put("id", "A" + (index + 1)); // Populate Key and values for Compound Rule - rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1)); - ruleAlgoirthmTracker.removeLast(); - rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1)); - ruleAlgoirthmTracker.removeLast(); - ruleAlgoirthmTracker.addLast(index); + rule.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, "A" + (ruleAlgorithmTracker.getLast() + 1)); + ruleAlgorithmTracker.removeLast(); + rule.put(DYNAMIC_RULE_ALGORITHM_FIELD_2, "A" + (ruleAlgorithmTracker.getLast() + 1)); + ruleAlgorithmTracker.removeLast(); + ruleAlgorithmTracker.addLast(index); ruleAlgorithmList.add(rule); index++; } @@ -250,26 +266,25 @@ public class ActionPolicyController extends RestrictedBaseController { List> jaxbInnerActionTypes = innerActionApply.getExpression(); AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0) .getValue(); - ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId()); + ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, attributeDesignator.getAttributeId()); // Get from Attribute Value AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbActionTypes.get(1).getValue(); String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); - ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); + ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_2, attributeValue); } // Rule Attribute added as value else if ((jaxbActionTypes.get(0).getValue()) instanceof AttributeValueType) { AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbActionTypes.get(0).getValue(); String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); - ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); + ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_2, attributeValue); ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(1).getValue(); List> jaxbInnerActionTypes = innerActionApply.getExpression(); AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0) .getValue(); - ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId()); + ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, attributeDesignator.getAttributeId()); } ruleAlgorithmList.add(ruleMap); } - } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java index 346b95aff..fc25e29f0 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java @@ -3,13 +3,14 @@ * ONAP Policy Engine * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Bell Canada * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,7 +21,6 @@ package org.onap.policy.controller; - import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; @@ -50,77 +50,82 @@ import com.fasterxml.jackson.databind.ObjectMapper; @Controller @RequestMapping({"/"}) -public class AdminTabController extends RestrictedBaseController{ - - private static final Logger LOGGER = FlexLogger.getLogger(AdminTabController.class); - - private static CommonClassDao commonClassDao; - - public AdminTabController() { - //default constructor - } - - @Autowired - private AdminTabController(CommonClassDao commonClassDao){ - AdminTabController.commonClassDao = commonClassDao; - } - - public static CommonClassDao getCommonClassDao() { - return commonClassDao; - } - - public static void setCommonClassDao(CommonClassDao commonClassDao) { - AdminTabController.commonClassDao = commonClassDao; - } - - @RequestMapping(value={"/get_LockDownData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getAdminTabEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("lockdowndata", mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error("Exception Occured"+e); - } - } - - @RequestMapping(value={"/adminTabController/save_LockDownValue.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveAdminTabLockdownValue(HttpServletRequest request, HttpServletResponse response) throws IOException{ - try { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - String userId = UserUtils.getUserSession(request).getOrgUserId(); - LOGGER.info("****************************************Logging UserID for Application Lockdown Function*****************************************"); - LOGGER.info("UserId: " + userId); - LOGGER.info("*********************************************************************************************************************************"); - JsonNode root = mapper.readTree(request.getReader()); - GlobalRoleSettings globalRole = mapper.readValue(root.get("lockdowndata").toString(), GlobalRoleSettings.class); - globalRole.setRole("super-admin"); - commonClassDao.update(globalRole); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class)); - JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}"); - - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error("Exception Occured"+e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); - } - return null; - } +public class AdminTabController extends RestrictedBaseController { + + private static final Logger LOGGER = FlexLogger.getLogger(AdminTabController.class); + private static final String CHARACTER_ENCODING = "UTF-8"; + + private static CommonClassDao commonClassDao; + + public AdminTabController() { + //default constructor + } + + @Autowired + private AdminTabController(CommonClassDao commonClassDao) { + AdminTabController.commonClassDao = commonClassDao; + } + + public static CommonClassDao getCommonClassDao() { + return commonClassDao; + } + + public static void setCommonClassDao(CommonClassDao commonClassDao) { + AdminTabController.commonClassDao = commonClassDao; + } + + @RequestMapping(value = {"/get_LockDownData"}, method = { + org.springframework.web.bind.annotation.RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) + public void getAdminTabEntityData(HttpServletRequest request, HttpServletResponse response) { + try { + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("lockdowndata", mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } catch (Exception e) { + LOGGER.error("Exception Occured" + e); + } + } + + @RequestMapping(value = {"/adminTabController/save_LockDownValue.htm"}, method = { + org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveAdminTabLockdownValue(HttpServletRequest request, HttpServletResponse response) + throws IOException { + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + String userId = UserUtils.getUserSession(request).getOrgUserId(); + LOGGER.info( + "****************************************Logging UserID for Application Lockdown Function*****************************************"); + LOGGER.info("UserId: " + userId); + LOGGER.info( + "*********************************************************************************************************************************"); + JsonNode root = mapper.readTree(request.getReader()); + GlobalRoleSettings globalRole = mapper + .readValue(root.get("lockdowndata").toString(), GlobalRoleSettings.class); + globalRole.setRole("super-admin"); + commonClassDao.update(globalRole); + + response.setCharacterEncoding(CHARACTER_ENCODING); + response.setContentType("application / json"); + request.setCharacterEncoding(CHARACTER_ENCODING); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class)); + JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}"); + + out.write(j.toString()); + + return null; + } catch (Exception e) { + LOGGER.error("Exception Occured" + e); + response.setCharacterEncoding(CHARACTER_ENCODING); + request.setCharacterEncoding(CHARACTER_ENCODING); + PrintWriter out = response.getWriter(); + out.write(PolicyUtils.CATCH_EXCEPTION); + } + return null; + } } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java index 018668fc7..3af430f45 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java @@ -3,6 +3,7 @@ * ONAP Policy Engine * ================================================================================ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Bell Canada * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,6 +38,9 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; import javax.script.SimpleBindings; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -63,6 +67,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.att.research.xacml.api.pap.PAPException; @@ -82,11 +87,9 @@ public class AutoPushController extends RestrictedBaseController { CommonClassDao commonClassDao; private PDPGroupContainer container; - protected List groups = Collections.synchronizedList(new ArrayList()); - private PDPPolicyContainer policyContainer; - private PolicyController policyController; + protected List groups = Collections.synchronizedList(new ArrayList<>()); public PolicyController getPolicyController() { return policyController; @@ -96,8 +99,6 @@ public class AutoPushController extends RestrictedBaseController { this.policyController = policyController; } - private List data; - public synchronized void refreshGroups() { synchronized (this.groups) { this.groups.clear(); @@ -116,35 +117,26 @@ public class AutoPushController extends RestrictedBaseController { return policyController != null ? getPolicyController() : new PolicyController(); } - @RequestMapping(value = { "/get_AutoPushPoliciesContainerData" }, method = { - org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value = {"/get_AutoPushPoliciesContainerData"}, method = { + RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response) { try { - Set scopes; - List roles; - data = new ArrayList<>(); - String userId = UserUtils.getUserSession(request).getOrgUserId(); + Set scopes = new HashSet<>(); + List roles = new ArrayList<>(); + List data = new ArrayList<>(); Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); + + String userId = UserUtils.getUserSession(request).getOrgUserId(); + PolicyController controller = policyController != null ? getPolicyController() : new PolicyController(); List userRoles = controller.getRoles(userId); - roles = new ArrayList<>(); - scopes = new HashSet<>(); for (Object role : userRoles) { Roles userRole = (Roles) role; roles.add(userRole.getRole()); - if (userRole.getScope() != null) { - if (userRole.getScope().contains(",")) { - String[] multipleScopes = userRole.getScope().split(","); - for (int i = 0; i < multipleScopes.length; i++) { - scopes.add(multipleScopes[i].replace("[", "").replace("]", "").replace("\"", "").trim()); - } - } else { - if (!"".equals(userRole.getScope())) { - scopes.add(userRole.getScope().replace("[", "").replace("]", "").replace("\"", "").trim()); - } - } - } + scopes.addAll(Stream.of(userRole.getScope().split(",")) + .map(String::new) + .collect(Collectors.toSet()) + ); } if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) { data = commonClassDao.getData(PolicyVersion.class); @@ -157,29 +149,27 @@ public class AutoPushController extends RestrictedBaseController { params.put("scope", scope); List filterdatas = commonClassDao.getDataByQuery(query, params); if (filterdatas != null) { - for (int i = 0; i < filterdatas.size(); i++) { - data.add(filterdatas.get(i)); - } + data.addAll(filterdatas); } } } else { PolicyVersion emptyPolicyName = new PolicyVersion(); emptyPolicyName - .setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you"); + .setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you"); data.add(emptyPolicyName); } } + ObjectMapper mapper = new ObjectMapper(); model.put("policydatas", mapper.writeValueAsString(data)); JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); JSONObject j = new JSONObject(msg); response.getWriter().write(j.toString()); } catch (Exception e) { - logger.error("Exception Occured" + e); + logger.error("Exception Occurred" + e); } } - @RequestMapping(value = { "/auto_Push/PushPolicyToPDP.htm" }, method = { - org.springframework.web.bind.annotation.RequestMethod.POST }) + @RequestMapping(value = { "/auto_Push/PushPolicyToPDP.htm" }, method = { RequestMethod.POST }) public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException { try { @@ -224,16 +214,15 @@ public class AutoPushController extends RestrictedBaseController { // // Get the current selection - String selectedItem = policyId; // - assert selectedItem != null; + assert policyId != null; // create the id of the target file // Our standard for file naming is: // ...xml // since the file name usually has a ".xml", we need to strip // that // before adding the other parts - String name = selectedItem.replace(File.separator, "."); + String name = policyId.replace(File.separator, "."); String id = name; if (id.endsWith(".xml")) { id = id.replace(".xml", ""); @@ -265,7 +254,6 @@ public class AutoPushController extends RestrictedBaseController { bw.close(); URI selectedURI = temp.toURI(); try { - // // Create the policy selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI); } catch (IOException e) { @@ -352,8 +340,7 @@ public class AutoPushController extends RestrictedBaseController { } @SuppressWarnings("unchecked") - @RequestMapping(value = { "/auto_Push/remove_GroupPolicies.htm" }, method = { - org.springframework.web.bind.annotation.RequestMethod.POST }) + @RequestMapping(value = { "/auto_Push/remove_GroupPolicies.htm" }, method = { RequestMethod.POST }) public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException { try { PolicyController controller = getPolicyControllerInstance(); @@ -374,12 +361,10 @@ public class AutoPushController extends RestrictedBaseController { policyContainer = new PDPPolicyContainer(group); if (removePolicyData.size() > 0) { - for (int i = 0; i < removePolicyData.size(); i++) { - String polData = removePolicyData.get(i).toString(); - this.policyContainer.removeItem(polData); - } - Set changedPolicies = new HashSet<>(); - changedPolicies.addAll((Collection) this.policyContainer.getItemIds()); + IntStream.range(0, removePolicyData.size()).mapToObj(i -> removePolicyData.get(i).toString()) + .forEach(polData -> this.policyContainer.removeItem(polData)); + Set changedPolicies = new HashSet<>( + (Collection) this.policyContainer.getItemIds()); StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(), group.getDescription(), null); updatedGroupObject.setPolicies(changedPolicies); @@ -411,5 +396,4 @@ public class AutoPushController extends RestrictedBaseController { } return null; } - } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java index 69444c478..3485163e4 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. + * Modifications Copyright (C) 2019 Bell Canada * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,6 +29,7 @@ import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -35,12 +37,12 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; -import java.nio.charset.StandardCharsets; import javax.annotation.PostConstruct; -import javax.mail.MessagingException; import javax.script.SimpleBindings; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import org.json.JSONObject; import org.onap.policy.admin.PolicyNotificationMail; import org.onap.policy.admin.RESTfulPAPEngine; @@ -71,8 +73,6 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; @Controller @RequestMapping("/") @@ -182,8 +182,9 @@ public class PolicyController extends RestrictedBaseController { try { String fileName; if (jUnit) { - fileName = new File(".").getCanonicalPath() + File.separator + "src" + File.separator + "test" - + File.separator + "resources" + File.separator + "JSONConfig.json"; + fileName = new File(".").getCanonicalPath() + File.separator + "src" + + File.separator + "test" + File.separator + "resources" + File.separator + + "JSONConfig.json"; } else { fileName = "xacml.admin.properties"; } @@ -234,17 +235,19 @@ public class PolicyController extends RestrictedBaseController { // Get the Property Values for Dashboard tab Limit try { setLogTableLimit(prop.getProperty("xacml.onap.dashboard.logTableLimit")); - setSystemAlertTableLimit(prop.getProperty("xacml.onap.dashboard.systemAlertTableLimit")); + setSystemAlertTableLimit( + prop.getProperty("xacml.onap.dashboard.systemAlertTableLimit")); } catch (Exception e) { - policyLogger - .error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Dashboard tab Property fields are missing" + e); + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + + "Dashboard tab Property fields are missing" + e); setLogTableLimit("5000"); setSystemAlertTableLimit("2000"); } System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "xacml.admin.properties"); } catch (IOException ex) { policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE - + "Exception Occured while reading the Smtp properties from xacml.admin.properties file" + ex); + + "Exception Occured while reading the Smtp properties from xacml.admin.properties file" + + ex); } // Initialize the FunctionDefinition table at Server Start up @@ -260,7 +263,7 @@ public class PolicyController extends RestrictedBaseController { /** * Get FunctionData Type from DB. - * + * * @return list of FunctionData. */ public static Map> getFunctionDatatypeMap() { @@ -274,7 +277,7 @@ public class PolicyController extends RestrictedBaseController { /** * Get Function ID. - * + * * @return Function ID. */ public static Map getFunctionIdMap() { @@ -294,7 +297,8 @@ public class PolicyController extends RestrictedBaseController { FunctionDefinition value = (FunctionDefinition) functiondefinitions.get(i); mapID2Function.put(value.getXacmlid(), value); if (!mapDatatype2Function.containsKey(value.getDatatypeBean())) { - mapDatatype2Function.put(value.getDatatypeBean(), new ArrayList()); + mapDatatype2Function.put(value.getDatatypeBean(), + new ArrayList()); } mapDatatype2Function.get(value.getDatatypeBean()).add(value); } @@ -302,31 +306,33 @@ public class PolicyController extends RestrictedBaseController { /** * Get Functional Definition data. - * - * @param request HttpServletRequest. + * + * @param request HttpServletRequest. * @param response HttpServletResponse. */ - @RequestMapping(value = { "/get_FunctionDefinitionDataByName" }, method = { - org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) - public void getFunctionDefinitionData(HttpServletRequest request, HttpServletResponse response) { + @RequestMapping(value = {"/get_FunctionDefinitionDataByName"}, + method = {org.springframework.web.bind.annotation.RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getFunctionDefinitionData(HttpServletRequest request, + HttpServletResponse response) { try { Map model = new HashMap<>(); ObjectMapper mapper = new ObjectMapper(); - model.put("functionDefinitionDatas", - mapper.writeValueAsString(commonClassDao.getDataByColumn(FunctionDefinition.class, "shortname"))); + model.put("functionDefinitionDatas", mapper.writeValueAsString( + commonClassDao.getDataByColumn(FunctionDefinition.class, "shortname"))); JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); JSONObject j = new JSONObject(msg); response.getWriter().write(j.toString()); } catch (Exception e) { - policyLogger.error( - XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while retriving the Function Definition data" + e); + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + + "Error while retriving the Function Definition data" + e); } } /** * Get PolicyEntity Data from db. - * - * @param scope scopeName. + * + * @param scope scopeName. * @param policyName policyName. * @return policyEntity data. */ @@ -338,7 +344,7 @@ public class PolicyController extends RestrictedBaseController { /** * Get Policy User Roles from db. - * + * * @param userId LoginID. * @return list of Roles. */ @@ -357,12 +363,13 @@ public class PolicyController extends RestrictedBaseController { /** * Get List of User Roles. - * - * @param request HttpServletRequest. + * + * @param request HttpServletRequest. * @param response HttpServletResponse. */ - @RequestMapping(value = { "/get_UserRolesData" }, method = { - org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value = {"/get_UserRolesData"}, + method = {org.springframework.web.bind.annotation.RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) public void getUserRolesEntityData(HttpServletRequest request, HttpServletResponse response) { try { String userId = UserUtils.getUserSession(request).getOrgUserId(); @@ -379,11 +386,11 @@ public class PolicyController extends RestrictedBaseController { /** * Policy tabs Model and View. - * + * * @param request Request input. * @return view model. */ - @RequestMapping(value = { "/policy", "/policy/Editor" }, method = RequestMethod.GET) + @RequestMapping(value = {"/policy", "/policy/Editor"}, method = RequestMethod.GET) public ModelAndView view(HttpServletRequest request) { getUserRoleFromSession(request); String myRequestUrl = request.getRequestURL().toString(); @@ -394,7 +401,8 @@ public class PolicyController extends RestrictedBaseController { setPapEngine(new RESTfulPAPEngine(myRequestUrl)); new PDPGroupContainer(new RESTfulPAPEngine(myRequestUrl)); } catch (Exception e) { - policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception Occured while loading PAP" + e); + policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "Exception Occured while loading PAP" + e); } Map model = new HashMap<>(); return new ModelAndView("policy_Editor", "model", model); @@ -402,7 +410,7 @@ public class PolicyController extends RestrictedBaseController { /** * Read the role from session for inserting into the database. - * + * * @param request Request input for Role. */ public void getUserRoleFromSession(HttpServletRequest request) { @@ -429,7 +437,8 @@ public class PolicyController extends RestrictedBaseController { savePolicyRoles(name, filteredRole, userId); } else { userRoles = getRoles(userId); - Pair, List> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles); + Pair, List> pair = + org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles); roles = pair.u; if (!roles.contains(filteredRole)) { savePolicyRoles(name, filteredRole, userId); @@ -440,9 +449,9 @@ public class PolicyController extends RestrictedBaseController { /** * Build a delete query for cleaning up roles and execute it. - * + * * @param filteredRoles Filtered roles list. - * @param userId UserID. + * @param userId UserID. */ private void cleanUpRoles(List filteredRoles, String userId) { StringBuilder query = new StringBuilder(); @@ -460,10 +469,10 @@ public class PolicyController extends RestrictedBaseController { /** * Save the Role to DB. - * - * @param name User Name. + * + * @param name User Name. * @param filteredRole Role Name. - * @param userId User LoginID. + * @param userId User LoginID. */ private void savePolicyRoles(String name, String filteredRole, String userId) { UserInfo userInfo = new UserInfo(); @@ -479,7 +488,7 @@ public class PolicyController extends RestrictedBaseController { /** * Filter the list of roles hierarchy wise. - * + * * @param newRoles list of roles from request. * @return */ @@ -501,7 +510,8 @@ public class PolicyController extends RestrictedBaseController { roles.clear(); roles.add(SUPERADMIN); } - if (!roles.contains(SUPERADMIN) || (POLICYGUEST.equalsIgnoreCase(role) && !superCheck)) { + if (!roles.contains(SUPERADMIN) + || (POLICYGUEST.equalsIgnoreCase(role) && !superCheck)) { if ("Policy Admin".equalsIgnoreCase(role.trim())) { roles.add("admin"); } else if ("Policy Editor".equalsIgnoreCase(role.trim())) { @@ -524,7 +534,7 @@ public class PolicyController extends RestrictedBaseController { /** * Get UserName based on LoginID. - * + * * @param createdBy loginID. * @return name. */ @@ -536,7 +546,7 @@ public class PolicyController extends RestrictedBaseController { /** * Check if the Policy is Active or not. - * + * * @param query sql query. * @return boolean. */ @@ -565,7 +575,8 @@ public class PolicyController extends RestrictedBaseController { } public PolicyVersion getPolicyEntityFromPolicyVersion(String query) { - return (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", query); + return (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", + query); } public List getDataByQuery(String query, SimpleBindings params) { @@ -579,24 +590,19 @@ public class PolicyController extends RestrictedBaseController { /** * Watch Policy Function. - * - * @param entity PolicyVersion entity. + * + * @param entity PolicyVersion entity. * @param policyName updated policy name. - * @param mode type of action rename/delete/import. + * @param mode type of action rename/delete/import. */ public void watchPolicyFunction(PolicyVersion entity, String policyName, String mode) { PolicyNotificationMail email = new PolicyNotificationMail(); - try { - email.sendMail(entity, policyName, mode, commonClassDao); - } catch (MessagingException e) { - policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR - + "Excepton Occured while Renaming/Deleting a Policy or Scope" + e); - } + email.sendMail(entity, policyName, mode, commonClassDao); } /** * Switch Version Policy Content. - * + * * @param pName which is used to find associated versions. * @return list of available versions based on policy name. */ @@ -613,7 +619,8 @@ public class PolicyController extends RestrictedBaseController { dbCheckName = dbCheckName.replace(".Decision_", ":Decision_"); } String[] splitDbCheckName = dbCheckName.split(":"); - String query = "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0"; + String query = + "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0"; SimpleBindings params = new SimpleBindings(); params.put("splitDBCheckName1", splitDbCheckName[1] + "%"); params.put("splitDBCheckName0", splitDbCheckName[0]); @@ -629,8 +636,8 @@ public class PolicyController extends RestrictedBaseController { if (policyName.contains("/")) { policyName = policyName.replace("/", File.separator); } - PolicyVersion entity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", - policyName); + PolicyVersion entity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, + "policyName", policyName); JSONObject el = new JSONObject(); el.put("activeVersion", entity.getActiveVersion()); el.put("availableVersions", av); @@ -654,14 +661,16 @@ public class PolicyController extends RestrictedBaseController { } public String getDescription(PolicyEntity data) { - InputStream stream = new ByteArrayInputStream(data.getPolicyData().getBytes(StandardCharsets.UTF_8)); + InputStream stream = + new ByteArrayInputStream(data.getPolicyData().getBytes(StandardCharsets.UTF_8)); Object policy = XACMLPolicyScanner.readPolicy(stream); if (policy instanceof PolicySetType) { return ((PolicySetType) policy).getDescription(); } else if (policy instanceof PolicyType) { return ((PolicyType) policy).getDescription(); } else { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Expecting a PolicySet/Policy/Rule object. Got: " + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + + "Expecting a PolicySet/Policy/Rule object. Got: " + policy.getClass().getCanonicalName()); return null; } @@ -670,14 +679,20 @@ public class PolicyController extends RestrictedBaseController { public String[] getUserInfo(PolicyEntity data, List activePolicies) { String policyName = data.getScope().replace(".", File.separator) + File.separator + data.getPolicyName().substring(0, data.getPolicyName().indexOf('.')); - PolicyVersion pVersion = activePolicies.stream().filter(a -> policyName.equals(a.getPolicyName())).findAny() - .orElse(null); + PolicyVersion polVersion = activePolicies.stream() + .filter(a -> policyName.equals(a.getPolicyName())).findAny().orElse(null); String[] result = new String[2]; + UserInfo userCreate = null; + UserInfo userModify = null; + if (polVersion != null) { + userCreate = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", + polVersion.getCreatedBy()); + userModify = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", + polVersion.getModifiedBy()); + } - UserInfo userCreate = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", pVersion.getCreatedBy()); - UserInfo userModify = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", pVersion.getModifiedBy()); - result[0] = userCreate != null ? userCreate.getUserName() : "super-admin"; - result[1] = userModify != null ? userModify.getUserName() : "super-admin"; + result[0] = userCreate != null ? userCreate.getUserName() : SUPERADMIN; + result[1] = userModify != null ? userModify.getUserName() : SUPERADMIN; return result; } @@ -710,7 +725,8 @@ public class PolicyController extends RestrictedBaseController { return mapDatatype2Function; } - public static void setMapDatatype2Function(Map> mapDatatype2Function) { + public static void setMapDatatype2Function( + Map> mapDatatype2Function) { PolicyController.mapDatatype2Function = mapDatatype2Function; } @@ -936,7 +952,7 @@ public class PolicyController extends RestrictedBaseController { /** * Set File Size limit. - * + * * @param uploadSize value. */ public static void setFileSizeLimit(String uploadSize) { @@ -954,7 +970,7 @@ public class PolicyController extends RestrictedBaseController { /** * Function to convert date. - * + * * @param dateTTL input date value. * @return */ diff --git a/docs/platform/PolicyEngineApiList.png b/docs/platform/PolicyEngineApiList.png index a00c363e0..8d8b51e04 100755 Binary files a/docs/platform/PolicyEngineApiList.png and b/docs/platform/PolicyEngineApiList.png differ diff --git a/docs/platform/api-docs.json b/docs/platform/api-docs.json index f9296d274..42f8d181f 100755 --- a/docs/platform/api-docs.json +++ b/docs/platform/api-docs.json @@ -1 +1 @@ -{"swagger":"2.0","info":{"description":"This API helps to make queries against Policy Engine","version":"3.0","title":"Policy Engine REST API"},"host":"104.239.197.207:8081","basePath":"/pdp/api","tags":[{"name":"policy-engine-services","description":"Policy Engine Services"}],"paths":{"/createConfig":{"put":{"tags":["policy-engine-services"],"summary":"Creates a Config Policy based on given Policy Parameters.","operationId":"createConfigUsingPUT","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"configPolicyAPIRequest","description":"configPolicyAPIRequest","required":true,"schema":{"$ref":"#/definitions/ConfigPolicyAPIRequest"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"deprecated":true}},"/createDictionaryItem":{"put":{"tags":["policy-engine-services"],"summary":"Creates a Dictionary Item for a specific dictionary based on given Parameters.","operationId":"createDictionaryItemUsingPUT","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"dictionaryParameters","description":"dictionaryParameters","required":true,"schema":{"$ref":"#/definitions/DictionaryParameters"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/createFirewallConfig":{"put":{"tags":["policy-engine-services"],"summary":"Creates a Config Firewall Policy","operationId":"createFirewallConfigUsingPUT","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"configFirewallPolicyAPIRequest","description":"configFirewallPolicyAPIRequest","required":true,"schema":{"$ref":"#/definitions/ConfigFirewallPolicyAPIRequest"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"deprecated":true}},"/createPolicy":{"put":{"tags":["policy-engine-services"],"summary":"Creates a Policy based on given Policy Parameters.","operationId":"createPolicyUsingPUT","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"policyParameters","description":"policyParameters","required":true,"schema":{"$ref":"#/definitions/PolicyParameters"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/deletePolicy":{"delete":{"tags":["policy-engine-services"],"summary":"Deletes the specified policy from the PDP Group or PAP.","operationId":"deletePolicyUsingDELETE","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"deletePolicyParameters","description":"deletePolicyParameters","required":true,"schema":{"$ref":"#/definitions/DeletePolicyParameters"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"204":{"description":"No Content"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"}}}},"/getConfig":{"post":{"tags":["policy-engine-services"],"summary":"Gets the configuration from the PolicyDecisionPoint(PDP)","operationId":"getConfigUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"configRequestParameters","description":"configRequestParameters","required":true,"schema":{"$ref":"#/definitions/ConfigRequestParameters"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"$ref":"#/definitions/Collection«PolicyConfig»"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/getConfigByPolicyName":{"post":{"tags":["policy-engine-services"],"summary":"Gets the configuration from the PolicyDecisionPoint(PDP) using PolicyName","operationId":"getConfigByPolicyNameUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"configNameRequest","description":"configNameRequest","required":true,"schema":{"$ref":"#/definitions/ConfigNameRequest"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"$ref":"#/definitions/Collection«PolicyConfig»"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"deprecated":true}},"/getDecision":{"post":{"tags":["policy-engine-services"],"summary":"Gets the Decision using specified decision parameters","operationId":"getDecisionUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"decisionRequestParameters","description":"decisionRequestParameters","required":true,"schema":{"$ref":"#/definitions/DecisionRequestParameters"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"$ref":"#/definitions/DecisionResponse"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/getDictionaryItems":{"post":{"tags":["policy-engine-services"],"summary":"Gets the dictionary items from the PAP","operationId":"getDictionaryItemsUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"dictionaryParameters","description":"dictionaryParameters","required":true,"schema":{"$ref":"#/definitions/DictionaryParameters"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"$ref":"#/definitions/DictionaryResponse"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/getMetrics":{"get":{"tags":["policy-engine-services"],"summary":"Gets the policy metrics from the PolicyAccessPoint(PAP)","operationId":"getMetricsUsingGET","consumes":["application/json"],"produces":["*/*"],"parameters":[{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"$ref":"#/definitions/MetricsResponse"}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/getNotification":{"post":{"tags":["policy-engine-services"],"summary":"Registers DMaaP Topic to recieve notification from Policy Engine","operationId":"getNotificationUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"notificationTopic","description":"notificationTopic","required":true,"schema":{"type":"string"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/listConfig":{"post":{"tags":["policy-engine-services"],"summary":"Gets the list of configuration policies from the PDP","operationId":"listConfigUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"configRequestParameters","description":"configRequestParameters","required":true,"schema":{"$ref":"#/definitions/ConfigRequestParameters"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"$ref":"#/definitions/Collection«string»"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/listPolicy":{"post":{"tags":["policy-engine-services"],"summary":"Gets the list of policies from the PAP","operationId":"listPolicyUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"configNameRequest","description":"configNameRequest","required":true,"schema":{"$ref":"#/definitions/ConfigNameRequest"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"$ref":"#/definitions/Collection«string»"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/policyEngineImport":{"post":{"tags":["policy-engine-services"],"summary":"Imports Policy based on the parameters which represent the service used to create a policy Service.","operationId":"policyEngineImportUsingPOST","consumes":["multipart/form-data"],"produces":["*/*"],"parameters":[{"name":"importParametersJson","in":"query","description":"importParametersJson","required":true,"type":"string"},{"name":"file","in":"formData","description":"file","required":true,"type":"file"},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/pushPolicy":{"put":{"tags":["policy-engine-services"],"summary":"Pushes the specified policy to the PDP Group.","operationId":"pushPolicyUsingPUT","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"pushPolicyParameters","description":"pushPolicyParameters","required":true,"schema":{"$ref":"#/definitions/PushPolicyParameters"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/sendEvent":{"post":{"tags":["policy-engine-services"],"summary":"Sends the Events specified to the Policy Engine","operationId":"sendEventUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"eventRequestParameters","description":"eventRequestParameters","required":true,"schema":{"$ref":"#/definitions/EventRequestParameters"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"$ref":"#/definitions/Collection«PolicyResponse»"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/sendHeartbeat":{"post":{"tags":["policy-engine-services"],"summary":"Sends Heartbeat to DMaaP Topic Registry to continue recieving notifications from Policy Engine","operationId":"sendHeartbeatUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"notificationTopic","description":"notificationTopic","required":true,"schema":{"type":"string"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/stopNotification":{"post":{"tags":["policy-engine-services"],"summary":"De-Registers DMaaP Topic to stop recieving notifications from Policy Engine","operationId":"stopNotificationUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"notificationTopic","description":"notificationTopic","required":true,"schema":{"type":"string"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/updateConfig":{"put":{"tags":["policy-engine-services"],"summary":"Updates a Config Policy based on given Policy Parameters.","operationId":"updateConfigUsingPUT","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"configPolicyAPIRequest","description":"configPolicyAPIRequest","required":true,"schema":{"$ref":"#/definitions/ConfigPolicyAPIRequest"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"deprecated":true}},"/updateDictionaryItem":{"put":{"tags":["policy-engine-services"],"summary":"Updates a Dictionary Item for a specific dictionary based on given Parameters.","operationId":"updateDictionaryItemUsingPUT","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"dictionaryParameters","description":"dictionaryParameters","required":true,"schema":{"$ref":"#/definitions/DictionaryParameters"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/updateFirewallConfig":{"put":{"tags":["policy-engine-services"],"summary":"Updates a Config Firewall Policy","operationId":"updateFirewallConfigUsingPUT","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"configFirewallPolicyAPIRequest","description":"configFirewallPolicyAPIRequest","required":true,"schema":{"$ref":"#/definitions/ConfigFirewallPolicyAPIRequest"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"deprecated":true}},"/updatePolicy":{"put":{"tags":["policy-engine-services"],"summary":"Updates a Policy based on given Policy Parameters.","operationId":"updatePolicyUsingPUT","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"policyParameters","description":"policyParameters","required":true,"schema":{"$ref":"#/definitions/PolicyParameters"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}}},"definitions":{"PolicyParameters":{"type":"object","properties":{"actionAttribute":{"type":"string"},"actionPerformer":{"type":"string"},"attributes":{"type":"object","additionalProperties":{"$ref":"#/definitions/Map«string,string»"}},"configBody":{"type":"string"},"configBodyType":{"type":"string","enum":["Properties","json","xml","other"]},"configName":{"type":"string"},"controllerName":{"type":"string"},"dependencyNames":{"type":"array","items":{"type":"string"}},"dynamicRuleAlgorithmField1":{"type":"array","items":{"type":"string"}},"dynamicRuleAlgorithmField2":{"type":"array","items":{"type":"string"}},"dynamicRuleAlgorithmFunctions":{"type":"array","items":{"type":"string"}},"dynamicRuleAlgorithmLabels":{"type":"array","items":{"type":"string"}},"ecompName":{"type":"string"},"extendedOption":{"type":"string"},"guard":{"type":"boolean"},"onapName":{"type":"string"},"policyClass":{"type":"string","enum":["Config","Action","Decision"]},"policyConfigType":{"type":"string","enum":["Base","Fault","PM","FW","BRMS_Raw","BRMS_Param","MS","EXTENDED"]},"policyDescription":{"type":"string"},"policyName":{"type":"string"},"priority":{"type":"string"},"requestID":{"type":"string"},"riskLevel":{"type":"string"},"riskType":{"type":"string"},"ruleProvider":{"type":"string","enum":["Custom","AAF","GUARD_YAML","GUARD_BL_YAML","GUARD_MIN_MAX"]},"ttlDate":{"type":"string","format":"date-time"}}},"ConfigRequestParameters":{"type":"object","properties":{"configAttributes":{"type":"object","additionalProperties":{"type":"string"}},"configName":{"type":"string"},"ecompName":{"type":"string"},"onapName":{"type":"string"},"policyName":{"type":"string"},"requestID":{"type":"string"},"unique":{"type":"boolean"}}},"Collection«PolicyResponse»":{"type":"object"},"DecisionResponse":{"type":"object","properties":{"decision":{"type":"string","enum":["permit","deny","error"]},"details":{"type":"string"}}},"DictionaryParameters":{"type":"object","properties":{"dictionary":{"type":"string"},"dictionaryJson":{"type":"string"},"dictionaryType":{"type":"string","enum":["Common","Action","ClosedLoop","Firewall","Decision","BRMS","MicroService","DescriptiveScope","PolicyScope","Enforcer","SafePolicy","Extended"]},"requestID":{"type":"string"}}},"JsonValue":{"type":"object","properties":{"valueType":{"type":"string","enum":["ARRAY","OBJECT","STRING","NUMBER","TRUE","FALSE","NULL"]}}},"DecisionRequestParameters":{"type":"object","properties":{"decisionAttributes":{"type":"object","additionalProperties":{"type":"string"}},"ecompcomponentName":{"type":"string"},"onapName":{"type":"string"},"requestID":{"type":"string"}}},"ConfigPolicyAPIRequest":{"type":"object","properties":{"body":{"type":"string"},"configAttributes":{"type":"object","additionalProperties":{"type":"string"}},"configName":{"type":"string"},"configType":{"type":"string"},"ecompName":{"type":"string"},"guard":{"type":"string"},"onapName":{"type":"string"},"policyDescription":{"type":"string"},"policyName":{"type":"string"},"policyScope":{"type":"string"},"riskLevel":{"type":"string"},"riskType":{"type":"string"},"ttlDate":{"type":"string"}}},"PushPolicyParameters":{"type":"object","properties":{"pdpGroup":{"type":"string"},"policyName":{"type":"string"},"policyType":{"type":"string"},"requestID":{"type":"string"}}},"ConfigFirewallPolicyAPIRequest":{"type":"object","properties":{"firewallJson":{"type":"string"},"guard":{"type":"string"},"policyName":{"type":"string"},"policyScope":{"type":"string"},"riskLevel":{"type":"string"},"riskType":{"type":"string"},"ttlDate":{"type":"string"}}},"PolicyConfig":{"type":"object","properties":{"config":{"type":"string"},"matchingConditions":{"type":"object","additionalProperties":{"type":"string"}},"policyConfigMessage":{"type":"string"},"policyConfigStatus":{"type":"string","enum":["retrieved","not_found"]},"policyName":{"type":"string"},"policyVersion":{"type":"string"},"property":{"type":"object","additionalProperties":{"type":"string"}},"responseAttributes":{"type":"object","additionalProperties":{"type":"string"}},"type":{"type":"string","enum":["Properties","json","xml","other"]}}},"EventRequestParameters":{"type":"object","properties":{"eventAttributes":{"type":"object","additionalProperties":{"type":"string"}},"requestID":{"type":"string"}}},"Map«string,string»":{"type":"object","additionalProperties":{"type":"string"}},"Collection«PolicyConfig»":{"type":"object"},"DictionaryResponse":{"type":"object","properties":{"dictionaryData":{"type":"object","additionalProperties":{"type":"string"}},"dictionaryJson":{"type":"object","additionalProperties":{"$ref":"#/definitions/JsonValue"}},"responseCode":{"type":"integer","format":"int32"},"responseMessage":{"type":"string"}}},"ConfigNameRequest":{"type":"object","properties":{"policyName":{"type":"string"}}},"MetricsResponse":{"type":"object","properties":{"metricsTotal":{"type":"integer","format":"int32"},"papMetrics":{"type":"integer","format":"int32"},"pdpMetrics":{"type":"integer","format":"int32"},"responseCode":{"type":"integer","format":"int32"},"responseMessage":{"type":"string"}}},"Collection«string»":{"type":"object"},"PolicyResponse":{"type":"object","properties":{"actionAdvised":{"type":"object","additionalProperties":{"type":"string"}},"actionTaken":{"type":"object","additionalProperties":{"type":"string"}},"policyResponseMessage":{"type":"string"},"policyResponseStatus":{"type":"string","enum":["no_action","action_advised","action_taken"]},"requestAttributes":{"type":"object","additionalProperties":{"type":"string"}}}},"DeletePolicyParameters":{"type":"object","properties":{"deleteCondition":{"type":"string","enum":["Current Version","All Versions"]},"pdpGroup":{"type":"string"},"policyComponent":{"type":"string"},"policyName":{"type":"string"},"policyType":{"type":"string"},"requestID":{"type":"string"}}}}} \ No newline at end of file +{"swagger":"2.0","info":{"description":"This API helps to make queries against Policy Engine","version":"3.0","title":"Policy Engine REST API"},"host":"localhost:8082","basePath":"/pdp/api","tags":[{"name":"policy-engine-services","description":"Policy Engine Services"}],"paths":{"/createConfig":{"put":{"tags":["policy-engine-services"],"summary":"Creates a Config Policy based on given Policy Parameters.","operationId":"createConfigUsingPUT","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"configPolicyAPIRequest","description":"configPolicyAPIRequest","required":true,"schema":{"$ref":"#/definitions/ConfigPolicyAPIRequest"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"deprecated":true}},"/createDictionaryItem":{"put":{"tags":["policy-engine-services"],"summary":"Creates a Dictionary Item for a specific dictionary based on given Parameters.","operationId":"createDictionaryItemUsingPUT","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"dictionaryParameters","description":"dictionaryParameters","required":true,"schema":{"$ref":"#/definitions/DictionaryParameters"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/createFirewallConfig":{"put":{"tags":["policy-engine-services"],"summary":"Creates a Config Firewall Policy","operationId":"createFirewallConfigUsingPUT","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"configFirewallPolicyAPIRequest","description":"configFirewallPolicyAPIRequest","required":true,"schema":{"$ref":"#/definitions/ConfigFirewallPolicyAPIRequest"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"deprecated":true}},"/createPolicy":{"put":{"tags":["policy-engine-services"],"summary":"Creates a Policy based on given Policy Parameters.","operationId":"createPolicyUsingPUT","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"policyParameters","description":"policyParameters","required":true,"schema":{"$ref":"#/definitions/PolicyParameters"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/deletePolicy":{"delete":{"tags":["policy-engine-services"],"summary":"Deletes the specified policy from the PDP Group or PAP.","operationId":"deletePolicyUsingDELETE","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"deletePolicyParameters","description":"deletePolicyParameters","required":true,"schema":{"$ref":"#/definitions/DeletePolicyParameters"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"401":{"description":"Unauthorized"},"204":{"description":"No Content"},"403":{"description":"Forbidden"}}}},"/getConfig":{"post":{"tags":["policy-engine-services"],"summary":"Gets the configuration from the PolicyDecisionPoint(PDP)","operationId":"getConfigUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"configRequestParameters","description":"configRequestParameters","required":true,"schema":{"$ref":"#/definitions/ConfigRequestParameters"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"$ref":"#/definitions/Collection«PolicyConfig»"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/getConfigByPolicyName":{"post":{"tags":["policy-engine-services"],"summary":"Gets the configuration from the PolicyDecisionPoint(PDP) using PolicyName","operationId":"getConfigByPolicyNameUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"configNameRequest","description":"configNameRequest","required":true,"schema":{"$ref":"#/definitions/ConfigNameRequest"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"$ref":"#/definitions/Collection«PolicyConfig»"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"deprecated":true}},"/getDecision":{"post":{"tags":["policy-engine-services"],"summary":"Gets the Decision using specified decision parameters","operationId":"getDecisionUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"decisionRequestParameters","description":"decisionRequestParameters","required":true,"schema":{"$ref":"#/definitions/DecisionRequestParameters"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"$ref":"#/definitions/DecisionResponse"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/getDictionaryItems":{"post":{"tags":["policy-engine-services"],"summary":"Gets the dictionary items from the PAP","operationId":"getDictionaryItemsUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"dictionaryParameters","description":"dictionaryParameters","required":true,"schema":{"$ref":"#/definitions/DictionaryParameters"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"$ref":"#/definitions/DictionaryResponse"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/getMetrics":{"get":{"tags":["policy-engine-services"],"summary":"Gets the policy metrics from the PolicyAccessPoint(PAP)","operationId":"getMetricsUsingGET","consumes":["application/json"],"produces":["*/*"],"parameters":[{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"$ref":"#/definitions/MetricsResponse"}},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/getNotification":{"post":{"tags":["policy-engine-services"],"summary":"Registers DMaaP Topic to recieve notification from Policy Engine","operationId":"getNotificationUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"notificationTopic","description":"notificationTopic","required":true,"schema":{"type":"string"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/listConfig":{"post":{"tags":["policy-engine-services"],"summary":"Gets the list of configuration policies from the PDP","operationId":"listConfigUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"configRequestParameters","description":"configRequestParameters","required":true,"schema":{"$ref":"#/definitions/ConfigRequestParameters"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"$ref":"#/definitions/Collection«string»"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/listPolicy":{"post":{"tags":["policy-engine-services"],"summary":"Gets the list of policies from the PDP","operationId":"listPolicyUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"configNameRequest","description":"configNameRequest","required":true,"schema":{"$ref":"#/definitions/ConfigNameRequest"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"$ref":"#/definitions/Collection«string»"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/policyEngineImport":{"post":{"tags":["policy-engine-services"],"summary":"Imports Policy based on the parameters which represent the service used to create a policy Service.","operationId":"policyEngineImportUsingPOST","consumes":["multipart/form-data"],"produces":["*/*"],"parameters":[{"name":"importParametersJson","in":"query","description":"importParametersJson","required":true,"type":"string"},{"name":"file","in":"formData","description":"file","required":true,"type":"file"},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/pushPolicy":{"put":{"tags":["policy-engine-services"],"summary":"Pushes the specified policy to the PDP Group.","operationId":"pushPolicyUsingPUT","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"pushPolicyParameters","description":"pushPolicyParameters","required":true,"schema":{"$ref":"#/definitions/PushPolicyParameters"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/sendEvent":{"post":{"tags":["policy-engine-services"],"summary":"Sends the Events specified to the Policy Engine","operationId":"sendEventUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"eventRequestParameters","description":"eventRequestParameters","required":true,"schema":{"$ref":"#/definitions/EventRequestParameters"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"$ref":"#/definitions/Collection«PolicyResponse»"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/sendHeartbeat":{"post":{"tags":["policy-engine-services"],"summary":"Sends Heartbeat to DMaaP Topic Registry to continue recieving notifications from Policy Engine","operationId":"sendHeartbeatUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"notificationTopic","description":"notificationTopic","required":true,"schema":{"type":"string"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/stopNotification":{"post":{"tags":["policy-engine-services"],"summary":"De-Registers DMaaP Topic to stop recieving notifications from Policy Engine","operationId":"stopNotificationUsingPOST","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"notificationTopic","description":"notificationTopic","required":true,"schema":{"type":"string"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/updateConfig":{"put":{"tags":["policy-engine-services"],"summary":"Updates a Config Policy based on given Policy Parameters.","operationId":"updateConfigUsingPUT","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"configPolicyAPIRequest","description":"configPolicyAPIRequest","required":true,"schema":{"$ref":"#/definitions/ConfigPolicyAPIRequest"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"deprecated":true}},"/updateDictionaryItem":{"put":{"tags":["policy-engine-services"],"summary":"Updates a Dictionary Item for a specific dictionary based on given Parameters.","operationId":"updateDictionaryItemUsingPUT","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"dictionaryParameters","description":"dictionaryParameters","required":true,"schema":{"$ref":"#/definitions/DictionaryParameters"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}},"/updateFirewallConfig":{"put":{"tags":["policy-engine-services"],"summary":"Updates a Config Firewall Policy","operationId":"updateFirewallConfigUsingPUT","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"configFirewallPolicyAPIRequest","description":"configFirewallPolicyAPIRequest","required":true,"schema":{"$ref":"#/definitions/ConfigFirewallPolicyAPIRequest"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}},"deprecated":true}},"/updatePolicy":{"put":{"tags":["policy-engine-services"],"summary":"Updates a Policy based on given Policy Parameters.","operationId":"updatePolicyUsingPUT","consumes":["application/json"],"produces":["*/*"],"parameters":[{"in":"body","name":"policyParameters","description":"policyParameters","required":true,"schema":{"$ref":"#/definitions/PolicyParameters"}},{"name":"ClientAuth","in":"header","description":"ClientAuth","required":true,"type":"string"},{"name":"X-ECOMP-RequestID","in":"header","description":"X-ECOMP-RequestID","required":false,"type":"string"},{"name":"Authorization","in":"header","required":true,"type":"string"},{"name":"Environment","in":"header","required":true,"type":"string"}],"responses":{"200":{"description":"OK","schema":{"type":"string"}},"201":{"description":"Created"},"401":{"description":"Unauthorized"},"403":{"description":"Forbidden"},"404":{"description":"Not Found"}}}}},"definitions":{"PolicyParameters":{"type":"object","properties":{"actionAttribute":{"type":"string"},"actionPerformer":{"type":"string"},"attributes":{"type":"object","additionalProperties":{"$ref":"#/definitions/Map«string,string»"}},"configBody":{"type":"string"},"configBodyType":{"type":"string","enum":["Properties","json","xml","other"]},"configName":{"type":"string"},"configPolicyParameters":{"$ref":"#/definitions/PolicyConfigParams"},"controllerName":{"type":"string"},"dependencyNames":{"type":"array","items":{"type":"string"}},"dynamicRuleAlgorithmField1":{"type":"array","items":{"type":"string"}},"dynamicRuleAlgorithmField2":{"type":"array","items":{"type":"string"}},"dynamicRuleAlgorithmFunctions":{"type":"array","items":{"type":"string"}},"dynamicRuleAlgorithmLabels":{"type":"array","items":{"type":"string"}},"ecompName":{"type":"string"},"extendedOption":{"type":"string"},"guard":{"type":"boolean"},"onapName":{"type":"string"},"policyClass":{"type":"string","enum":["Config","Action","Decision"]},"policyConfigType":{"type":"string","enum":["Base","Fault","PM","FW","BRMS_Raw","BRMS_Param","MS","Optimization","EXTENDED"]},"policyDescription":{"type":"string"},"policyName":{"type":"string"},"priority":{"type":"string"},"rawXacmlPolicy":{"type":"string"},"requestID":{"type":"string"},"riskLevel":{"type":"string"},"riskType":{"type":"string"},"ruleProvider":{"type":"string","enum":["Custom","AAF","GUARD_YAML","GUARD_MIN_MAX","GUARD_BL_YAML","Rainy_Day","Raw"]},"treatments":{"type":"object","additionalProperties":{"type":"string"}},"ttlDate":{"type":"string","format":"date-time"}}},"ConfigRequestParameters":{"type":"object","properties":{"configAttributes":{"type":"object","additionalProperties":{"type":"string"}},"configName":{"type":"string"},"ecompName":{"type":"string"},"onapName":{"type":"string"},"policyName":{"type":"string"},"requestID":{"type":"string"},"unique":{"type":"boolean"}}},"Collection«PolicyResponse»":{"type":"object"},"DecisionResponse":{"type":"object","properties":{"decision":{"type":"string","enum":["permit","deny","error"]},"details":{"type":"string"}}},"DictionaryParameters":{"type":"object","properties":{"dictionary":{"type":"string"},"dictionaryJson":{"type":"string"},"dictionaryType":{"type":"string","enum":["Common","Action","ClosedLoop","Firewall","Decision","BRMS","MicroService","Optimization","DescriptiveScope","PolicyScope","Enforcer","SafePolicy","Extended"]},"requestID":{"type":"string"}}},"JsonValue":{"type":"object","properties":{"valueType":{"type":"string","enum":["ARRAY","OBJECT","STRING","NUMBER","TRUE","FALSE","NULL"]}}},"DecisionRequestParameters":{"type":"object","properties":{"decisionAttributes":{"type":"object","additionalProperties":{"type":"string"}},"ecompcomponentName":{"type":"string"},"onapName":{"type":"string"},"requestID":{"type":"string"}}},"ConfigPolicyAPIRequest":{"type":"object","properties":{"body":{"type":"string"},"configAttributes":{"type":"object","additionalProperties":{"type":"string"}},"configName":{"type":"string"},"configType":{"type":"string"},"ecompName":{"type":"string"},"guard":{"type":"string"},"onapName":{"type":"string"},"policyDescription":{"type":"string"},"policyName":{"type":"string"},"policyScope":{"type":"string"},"riskLevel":{"type":"string"},"riskType":{"type":"string"},"ttlDate":{"type":"string"}}},"PushPolicyParameters":{"type":"object","properties":{"pdpGroup":{"type":"string"},"policyName":{"type":"string"},"policyType":{"type":"string"},"requestID":{"type":"string"}}},"ConfigFirewallPolicyAPIRequest":{"type":"object","properties":{"firewallJson":{"type":"string"},"guard":{"type":"string"},"policyName":{"type":"string"},"policyScope":{"type":"string"},"riskLevel":{"type":"string"},"riskType":{"type":"string"},"ttlDate":{"type":"string"}}},"PolicyConfig":{"type":"object","properties":{"config":{"type":"string"},"matchingConditions":{"type":"object","additionalProperties":{"type":"string"}},"policyConfigMessage":{"type":"string"},"policyConfigStatus":{"type":"string","enum":["retrieved","not_found"]},"policyName":{"type":"string"},"policyType":{"type":"string","enum":["Base","Fault","PM","FW","BRMS_Raw","BRMS_Param","MS","Optimization","EXTENDED"]},"policyVersion":{"type":"string"},"property":{"type":"object","additionalProperties":{"type":"string"}},"responseAttributes":{"type":"object","additionalProperties":{"type":"string"}},"type":{"type":"string","enum":["Properties","json","xml","other"]}}},"EventRequestParameters":{"type":"object","properties":{"eventAttributes":{"type":"object","additionalProperties":{"type":"string"}},"requestID":{"type":"string"}}},"Map«string,string»":{"type":"object","additionalProperties":{"type":"string"}},"Collection«PolicyConfig»":{"type":"object"},"DictionaryResponse":{"type":"object","properties":{"dictionaryData":{"type":"object","additionalProperties":{"type":"string"}},"dictionaryJson":{"type":"object","additionalProperties":{"$ref":"#/definitions/JsonValue"}},"responseCode":{"type":"integer","format":"int32"},"responseMessage":{"type":"string"}}},"ConfigNameRequest":{"type":"object","properties":{"policyName":{"type":"string"}}},"MetricsResponse":{"type":"object","properties":{"metricsTotal":{"type":"integer","format":"int32"},"papMetrics":{"type":"integer","format":"int32"},"pdpMetrics":{"type":"integer","format":"int32"},"responseCode":{"type":"integer","format":"int32"},"responseMessage":{"type":"string"}}},"PolicyConfigParams":{"type":"object","properties":{"attributes":{"type":"object","additionalProperties":{"$ref":"#/definitions/Map«string,string»"}},"configBody":{"type":"string"},"configName":{"type":"string"},"onapName":{"type":"string"},"policyDescription":{"type":"string"},"policyName":{"type":"string"},"requestID":{"type":"string"}}},"Collection«string»":{"type":"object"},"PolicyResponse":{"type":"object","properties":{"actionAdvised":{"type":"object","additionalProperties":{"type":"string"}},"actionTaken":{"type":"object","additionalProperties":{"type":"string"}},"policyResponseMessage":{"type":"string"},"policyResponseStatus":{"type":"string","enum":["no_action","action_advised","action_taken"]},"requestAttributes":{"type":"object","additionalProperties":{"type":"string"}}}},"DeletePolicyParameters":{"type":"object","properties":{"deleteCondition":{"type":"string","enum":["Current Version","All Versions"]},"pdpGroup":{"type":"string"},"policyComponent":{"type":"string"},"policyName":{"type":"string"},"policyType":{"type":"string"},"requestID":{"type":"string"}}}}} \ No newline at end of file diff --git a/docs/platform/ctrlog_config.png b/docs/platform/ctrlog_config.png new file mode 100755 index 000000000..8d5aeb650 Binary files /dev/null and b/docs/platform/ctrlog_config.png differ diff --git a/docs/platform/ctrlog_enablefeature.png b/docs/platform/ctrlog_enablefeature.png new file mode 100755 index 000000000..dc1abf342 Binary files /dev/null and b/docs/platform/ctrlog_enablefeature.png differ diff --git a/docs/platform/ctrlog_logback.png b/docs/platform/ctrlog_logback.png new file mode 100755 index 000000000..252f3fe1e Binary files /dev/null and b/docs/platform/ctrlog_logback.png differ diff --git a/docs/platform/ctrlog_view.png b/docs/platform/ctrlog_view.png new file mode 100755 index 000000000..118bd64d4 Binary files /dev/null and b/docs/platform/ctrlog_view.png differ diff --git a/docs/platform/feature_controllerlogging.rst b/docs/platform/feature_controllerlogging.rst new file mode 100644 index 000000000..0677030ed --- /dev/null +++ b/docs/platform/feature_controllerlogging.rst @@ -0,0 +1,50 @@ + +.. This work is licensed under a Creative Commons Attribution 4.0 International License. +.. http://creativecommons.org/licenses/by/4.0 + +*************************** +Feature: Controller Logging +*************************** + +.. contents:: + :depth: 3 + +Summary +^^^^^^^ +The controller logging feature provides a way to log network topic messages to a separate controller log file for each controller. This allows a clear separation of network traffic between all of the controllers. + +Enabling Controller Logging +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Type "features enable controller-logging". The feature will now display as "enabled". + + .. image:: ctrlog_enablefeature.png + +When the feature's enable script is executed, it will search the $POLICY_HOME/config directory for any logback files containing the prefix "logback-include-". These logger configuration files are typically provided with a feature that installs a controlloop (ex: controlloop-amsterdam and controlloop-casablanca features). Once these configuration files are found by the enable script, the logback.xml config file will be updated to include the configurations. + + .. image:: ctrlog_logback.png + + +Controller Logger Configuration +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +The contents of a logback-include-``*``.xml file follows the same configuration syntax as the logback.xml file. It will contain the configurations for the logger associated with the given controller. + + .. note:: A controller logger MUST be configured with the same name as the controller (ex: a controller named "casablanca" will have a logger named "casablanca"). + + .. image:: ctrlog_config.png + + +Viewing the Controller Logs +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Once a logger for the controller is configured, start the drools-pdp and navigate to the $POLICY_LOGS directory. A new controller specific network log will be added that contains all the network topic traffic of the controller. + + .. image:: ctrlog_view.png + +The original network log remains and will append traffic information from all topics regardless of which controller it is for. To abbreviate and customize messages for the network log, refer to the `Feature MDC Filters `_ documentation. + + +End of Document + + diff --git a/docs/platform/feature_mdcfilters.rst b/docs/platform/feature_mdcfilters.rst new file mode 100644 index 000000000..b0f5543d7 --- /dev/null +++ b/docs/platform/feature_mdcfilters.rst @@ -0,0 +1,121 @@ + +.. This work is licensed under a Creative Commons Attribution 4.0 International License. +.. http://creativecommons.org/licenses/by/4.0 + +******************** +Feature: MDC Filters +******************** + +.. contents:: + :depth: 3 + +Summary +^^^^^^^ +The MDC Filter Feature provides configurable properties for network topics to extract fields from JSON strings and place them in a mapped diagnostic context (MDC). + +Network Log Structure Before Feature Enabled +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Before enabling the feature, the network log contains the entire content of each message received on a topic. Below is a sample message from the network log. Note that the topic used for this tutorial is DCAE-CL. + + .. code-block:: bash + + [2019-03-22T16:36:42.942+00:00|DMAAP-source-DCAE-CL][IN|DMAAP|DCAE-CL] + {"closedLoopControlName":"ControlLoop-vCPE-48f0c2c3-a172-4192-9ae3-052274181b6e","closedLoopAlarmStart":1463679805324,"closedLoopEventClient":"DCAE_INSTANCE_ID.dcae-tca","closedLoopEventStatus":"ONSET","requestID":"664be3d2-6c12-4f4b-a3e7-c349acced200","target_type":"VNF","target":"generic-vnf.vnf-id","AAI":{"vserver.is-closed-loop-disabled":"false","vserver.prov-status":"ACTIVE","generic-vnf.vnf-id":"vCPE_Infrastructure_vGMUX_demo_app"},"from":"DCAE","version":"1.0.2"} + +The network log can become voluminous if messages received from various topics carry large messages for various controllers. With the MDC Filter Feature, users can define keywords in JSON messages to extract and structure according to a desired format. This is done through configuring the feature's properties. + +Configuring the MDC Filter Feature +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +To configure the feature, the feature must be enabled using the following command: + + .. code-block:: bash + + features enable mdc-filters + + + .. image:: mdc_enablefeature.png + +Once the feature is enabled, there will be a new properties file in *$POLICY_HOME/config* called **feature-mdc-filters.properties**. + + .. image:: mdc_properties.png + +The properties file contains filters to extract key data from messages on the network topics that are saved in an MDC, which can be referenced in logback.xml. The configuration format is as follows: + + .. code-block:: bash + + ..topics..mdcFilters= + + Where: + = ueb, dmaap, noop + = source, sink + = Name of DMaaP or UEB topic + = Comma separated list of key/json-path(s) + +The filters consist of an MDC key used by **logback.xml** (see below) and the JSON path(s) to the desired data. The path always begins with '$', which signifies the root of the JSON document. The underlying library, JsonPath, uses a query syntax for searching through a JSON file. The query syntax and some examples can be found at https://github.com/json-path/JsonPath. An example filter for the *DCAE-CL* is provided below: + + .. code-block:: bash + + dmaap.source.topics.DCAE-CL.mdcFilters=requestID=$.requestID + +This filter is specifying that the dmaap source topic *DCAE-CL* will search each message received for requestID by following the path starting at the root ($) and searching for the field *requestID*. If the field is found, it is placed in the MDC with the key "requestID" as signified by the left hand side of the filter before the "=". + + +Configuring Multiple Filters and Paths +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Multiple fields can be found for a given JSON document by a comma separated list of pairs. For the previous example, another filter is added by adding a comma and specifying the filter as follows: + + .. code-block:: bash + + dmaap.source.topics.DCAE-CL.mdcFilters=requestID=$.requestID,closedLoopName=$.closedLoopControlName + +The feature will now search for both requestID and closedLoopControlName in a JSON message using the specified "$." path notations and put them in the MDC using the keys "requestID" and "closedLoopName" respectively. To further refine the filter, if a topic receives different message structures (ex: a response message structure vs an error message structure) the "|" notation allows multiple paths to a key to be defined. The feature will search through each specified path until a match is found. An example can be found below: + + .. code-block:: bash + + dmaap.source.topics.DCAE-CL.mdcFilters=requestID=$.requestID,closedLoopName=$.closedLoopControlName|$.AAI.closedLoopControlName + +Now when the filter is searching for closedLoopControlName it will check the first path "$.closedLoopControlName", if it is not present then it will try the second path "$.AAI.closedLoopControlName". If the user is unsure of the path to a field, JsonPath supports a deep scan by using the ".." notation. This will search the entire JSON document for the field without specifying the path. + + +Accessing the MDC Values in logback.xml +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Once the feature properties have been defined, logback.xml contains a "abstractNetworkPattern" property that will hold the desired message structure defined by the user. The user has the flexibility to define the message structure however they choose but for this tutorial the following pattern is used: + + .. code-block:: bash + + + +The "value" portion consists of two headers in bracket notation, the first header defines the timestamp while the second header references the keys from the MDC filters defined in the feature properties. The standard logback syntax is used and more information on the syntax can be found here. Note that some of the fields here were not defined in the feature properties file. The feature automatically puts the network infrastructure information in the keys that are prepended with "network". The current supported network infrastructure information is listed below. + + +-------------------+-------------------------------------------------+ + | Field | Values | + +===================+=================================================+ + | networkEventType | IN, OUT | + +-------------------+-------------------------------------------------+ + | networkProtocol | DMAAP, UEB, NOOP | + +-------------------+-------------------------------------------------+ + | networkTopic | The name of the topic that received the message | + +-------------------+-------------------------------------------------+ + + +To reference the keys from the feature properties the syntax "%X{KEY_DEFINED_IN_PROPERTIES}" provides access to the value. An optional addition is to append ":-", which specifies a default value to display in the log if the field was not found in the message received. For this tutorial, a default of "NULL" is displayed for any of the fields that were not found while filtering. The "|" has no special meaning and is just used as a field separator for readability; the user can decorate the log format to their desired visual appeal. + +Network Log Structure After Feature Enabled +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Once the feature and logback.xml is configured to the user's desired settings, start the PDP-D by running "policy start". Based on the configurations from the previous sections of this tutorial, the following log message is written to network log when a message is received on the DCAE-CL topic: + + .. code-block:: bash + + [2019-03-22T16:38:23.884+00:00] [IN|DMAAP|DCAE-CL|664be3d2-6c12-4f4b-a3e7-c349acced200|ControlLoop-vCPE-48f0c2c3-a172-4192-9ae3-052274181b6e] + +The message has now been filtered to display the network infrastructure information and the extracted data from the JSON message based on the feature properties. In order to view the entire message received from a topic, a complementary feature was developed to display the entire message on a per controller basis while preserving the compact network log. Refer to the `Feature Controller Logging `_ documentation for details. + + + +End of Document + diff --git a/docs/platform/index.rst b/docs/platform/index.rst index 0d097717d..6257e56ee 100644 --- a/docs/platform/index.rst +++ b/docs/platform/index.rst @@ -48,6 +48,8 @@ PDP-D Features feature_activestdbymgmt.rst feature_locking.rst feature_pooling.rst + feature_controllerlogging.rst + feature_mdcfilters.rst Policy Platform Tutorials diff --git a/docs/platform/mdc_enablefeature.png b/docs/platform/mdc_enablefeature.png new file mode 100755 index 000000000..26ae55a4e Binary files /dev/null and b/docs/platform/mdc_enablefeature.png differ diff --git a/docs/platform/mdc_properties.png b/docs/platform/mdc_properties.png new file mode 100755 index 000000000..63cea92ed Binary files /dev/null and b/docs/platform/mdc_properties.png differ diff --git a/docs/platform/offeredapis.rst b/docs/platform/offeredapis.rst index 197735100..516260941 100644 --- a/docs/platform/offeredapis.rst +++ b/docs/platform/offeredapis.rst @@ -663,16 +663,5 @@ Examples } -Additional Information -^^^^^^^^^^^^^^^^^^^^^^ - -Additional information, including examples, can be found at `PolicyApi link`_. - -.. _PolicyApi link: https://wiki.onap.org/display/DW/Policy+API - - - - - End of Document diff --git a/docs/platform/swarch_pdp.rst b/docs/platform/swarch_pdp.rst index ca9dee29d..a0b058d84 100644 --- a/docs/platform/swarch_pdp.rst +++ b/docs/platform/swarch_pdp.rst @@ -59,6 +59,8 @@ The current extensions supported are: - `Feature Active/Standby Management `_ (disabled by default) - `Feature Distributed Locking `_ (enabled in OOM installation by default) - `Feature Pooling `_ (enabled in OOM installation by default) +- `Feature Controller Logging `_ (disabled by default) +- `Feature MDC Filters `_ (disabled by default) .. seealso:: Click on the individual feature links for more information