From: Jorge Hernandez Date: Fri, 29 Mar 2019 19:36:44 +0000 (+0000) Subject: Merge "FIx Sonar Issues reported on ActionPolicyController" X-Git-Tag: 1.4.0~31 X-Git-Url: https://gerrit.onap.org/r/gitweb?p=policy%2Fengine.git;a=commitdiff_plain;h=c683a67fbf4a50e68bf8736517865b43db75ed4b;hp=36fc43ca0358087c512767287cbeb3038824650e Merge "FIx Sonar Issues reported on ActionPolicyController" --- 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/ONAP-PAP-REST/xacml.pap.properties b/ONAP-PAP-REST/xacml.pap.properties index bd0fed40c..c26e96ff9 100644 --- a/ONAP-PAP-REST/xacml.pap.properties +++ b/ONAP-PAP-REST/xacml.pap.properties @@ -158,4 +158,4 @@ CLIENT_KEY= #Micro Service Model Properties xacml.policy.msOnapName=http://org.onap -xacml.policy.msPolicyName=http://org.onap.policy +xacml.policy.msPolicyName=http://org.onap.policy \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java index e7ed57add..67a94474f 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,6 +21,15 @@ package org.onap.policy.controller; +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.gson.Gson; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; @@ -47,7 +56,6 @@ import java.util.TreeMap; import java.util.UUID; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; - import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonArrayBuilder; @@ -57,7 +65,13 @@ import javax.json.JsonReader; import javax.json.JsonValue; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; import org.apache.commons.compress.utils.IOUtils; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; @@ -86,1419 +100,1562 @@ import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; -import com.att.research.xacml.util.XACMLProperties; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectWriter; -import com.fasterxml.jackson.databind.node.JsonNodeFactory; -import com.fasterxml.jackson.databind.node.ObjectNode; -import com.google.gson.Gson; - -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; @Controller @RequestMapping("/") public class CreateDcaeMicroServiceController extends RestrictedBaseController { - private static final Logger LOGGER = FlexLogger.getLogger(CreateDcaeMicroServiceController.class); - - private static CommonClassDao commonClassDao; - - public static CommonClassDao getCommonClassDao() { - return commonClassDao; - } - - public static void setCommonClassDao(CommonClassDao commonClassDao) { - CreateDcaeMicroServiceController.commonClassDao = commonClassDao; - } - - private MicroServiceModels newModel; - private String newFile; - private String directory; - private List modelList = new ArrayList<>(); - private List dirDependencyList = new ArrayList<>(); - private LinkedHashMap classMap = new LinkedHashMap<>(); - String referenceAttributes; - String attributeString; - Set allManyTrueKeys= new HashSet <>(); - - public static final String DATATYPE = "data_types.policy.data."; - public static final String PROPERTIES=".properties."; - public static final String TYPE=".type"; - public static final String STRING="string"; - public static final String INTEGER="integer"; - public static final String LIST="list"; - public static final String DEFAULT=".default"; - public static final String REQUIRED=".required"; - public static final String MATCHABLE=".matchable"; - public static final String MANYFALSE=":MANY-false"; - - - @Autowired - private CreateDcaeMicroServiceController(CommonClassDao commonClassDao){ - CreateDcaeMicroServiceController.commonClassDao = commonClassDao; - } - - public CreateDcaeMicroServiceController(){ - // Empty Constructor - } - - protected PolicyRestAdapter policyAdapter = null; - private int priorityCount; - private Map attributesListRefMap = new HashMap<>(); - private Map> arrayTextList = new HashMap<>(); - - public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) { - - String jsonContent = null; - try{ - LOGGER.info("policyJSON :" + (root.get("policyJSON")).toString()); - - String tempJson = root.get("policyJSON").toString(); - - //---replace empty value with the value below before calling decodeContent method. - String dummyValue = "*empty-value*" + UUID.randomUUID().toString(); - LOGGER.info("dummyValue:" + dummyValue); - tempJson = StringUtils.replaceEach(tempJson, new String[]{"\"\""}, new String[]{"\""+dummyValue+"\""}); - ObjectMapper mapper = new ObjectMapper(); - JsonNode tempJsonNode = mapper.readTree(tempJson); - jsonContent = decodeContent(tempJsonNode).toString(); - constructJson(policyData, jsonContent, dummyValue); - }catch(Exception e){ - LOGGER.error("Error while decoding microservice content", e); - } - - return policyData; - } - - private GroupPolicyScopeList getPolicyObject(String policyScope) { - return (GroupPolicyScopeList) commonClassDao.getEntityItem(GroupPolicyScopeList.class, "name", policyScope); - } - - private PolicyRestAdapter constructJson(PolicyRestAdapter policyAdapter, String jsonContent, String dummyValue) { - ObjectWriter om = new ObjectMapper().writer(); - String json=""; - DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject(); - MicroServiceModels returnModel = new MicroServiceModels(); - microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS)); - if(policyAdapter.getServiceType() !=null){ - microServiceObject.setService(policyAdapter.getServiceType()); - microServiceObject.setVersion(policyAdapter.getVersion()); - returnModel = getAttributeObject(microServiceObject.getService(), microServiceObject.getVersion()); - } - if (returnModel.getAnnotation()==null || returnModel.getAnnotation().isEmpty()){ - if(policyAdapter.getUuid()!=null){ - microServiceObject.setUuid(policyAdapter.getUuid()); - } - if(policyAdapter.getLocation()!=null){ - microServiceObject.setLocation(policyAdapter.getLocation()); - } - if(policyAdapter.getConfigName()!=null){ - microServiceObject.setConfigName(policyAdapter.getConfigName()); - } - GroupPolicyScopeList policyScopeValue = getPolicyObject(policyAdapter.getPolicyScope()); - if(policyScopeValue!=null){ - microServiceObject.setPolicyScope(policyScopeValue.getGroupList()); - } - } - - if(policyAdapter.getPolicyName()!=null){ - microServiceObject.setPolicyName(policyAdapter.getPolicyName()); - } - if(policyAdapter.getPolicyDescription()!=null){ - microServiceObject.setDescription(policyAdapter.getPolicyDescription()); - } - if (policyAdapter.getPriority()!=null){ - microServiceObject.setPriority(policyAdapter.getPriority()); - }else { - microServiceObject.setPriority("9999"); - } - - if (policyAdapter.getRiskLevel()!=null){ - microServiceObject.setRiskLevel(policyAdapter.getRiskLevel()); - } - if (policyAdapter.getRiskType()!=null){ - microServiceObject.setRiskType(policyAdapter.getRiskType()); - } - if (policyAdapter.getGuard()!=null){ - microServiceObject.setGuard(policyAdapter.getGuard()); - } - microServiceObject.setContent(jsonContent); - - try { - json = om.writeValueAsString(microServiceObject); - } catch (JsonProcessingException e) { - LOGGER.error("Error writing out the object", e); - } - LOGGER.info("input json: " + json); - LOGGER.info("input jsonContent: " + jsonContent); - String cleanJson = cleanUPJson(json); - //--- reset empty value back after called cleanUPJson method and before calling removeNullAttributes - String tempJson = StringUtils.replaceEach(cleanJson, new String[]{"\""+dummyValue+"\""}, new String[]{"\"\""}); - LOGGER.info("tempJson: " + tempJson); - cleanJson = removeNullAttributes(tempJson); - policyAdapter.setJsonBody(cleanJson); - return policyAdapter; - } - - public String removeNullAttributes(String cleanJson) { - ObjectMapper mapper = new ObjectMapper(); - - try { - JsonNode rootNode = mapper.readTree(cleanJson); - JsonNode returnNode = mapper.readTree(cleanJson); - Iterator> fieldsIterator = rootNode.fields(); - boolean remove = false; - JsonObject removed = null; - boolean contentChanged = false; - while (fieldsIterator.hasNext()) { - Map.Entry field = fieldsIterator.next(); - final String key = field.getKey(); - final JsonNode value = field.getValue(); - if("content".equalsIgnoreCase(key)){ - String contentStr = value.toString(); - try(JsonReader reader = Json.createReader(new StringReader(contentStr))){ - JsonObject jsonContent = reader.readObject(); - removed = removeNull(jsonContent); - if(!jsonContent.toString().equals(removed.toString())){ - contentChanged = true; - } + private static final Logger LOGGER = FlexLogger.getLogger(CreateDcaeMicroServiceController.class); + + private static CommonClassDao commonClassDao; + + public static CommonClassDao getCommonClassDao() { + return commonClassDao; + } + + public static void setCommonClassDao(CommonClassDao commonClassDao) { + CreateDcaeMicroServiceController.commonClassDao = commonClassDao; + } + + private MicroServiceModels newModel; + private String newFile; + private String directory; + private List modelList = new ArrayList<>(); + private List dirDependencyList = new ArrayList<>(); + private LinkedHashMap classMap = new LinkedHashMap<>(); + String referenceAttributes; + String attributeString; + Set allManyTrueKeys = new HashSet<>(); + + public static final String DATATYPE = "data_types.policy.data."; + public static final String PROPERTIES = ".properties."; + public static final String TYPE = ".type"; + public static final String STRING = "string"; + public static final String INTEGER = "integer"; + public static final String LIST = "list"; + public static final String DEFAULT = ".default"; + public static final String REQUIRED = ".required"; + public static final String MATCHABLE = ".matchable"; + public static final String MANYFALSE = ":MANY-false"; + + + @Autowired + private CreateDcaeMicroServiceController(CommonClassDao commonClassDao) { + CreateDcaeMicroServiceController.commonClassDao = commonClassDao; + } + + public CreateDcaeMicroServiceController() { + // Empty Constructor + } + + protected PolicyRestAdapter policyAdapter = null; + private int priorityCount; + private Map attributesListRefMap = new HashMap<>(); + private Map> arrayTextList = new HashMap<>(); + private Map jsonStringValues = new HashMap<>(); + + public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) { + + String jsonContent = null; + try { + LOGGER.info("policyJSON :" + (root.get("policyJSON")).toString()); + + String tempJson = root.get("policyJSON").toString(); + JSONObject policyJSON = new JSONObject(root.get("policyJSON").toString()); + if (policyJSON != null) { + saveOriginalJsonObject(policyJSON, jsonStringValues); + } + // ---replace empty value with the value below before calling decodeContent method. + String dummyValue = "*empty-value*" + UUID.randomUUID().toString(); + LOGGER.info("dummyValue:" + dummyValue); + tempJson = + StringUtils.replaceEach(tempJson, new String[] {"\"\""}, new String[] {"\"" + dummyValue + "\""}); + ObjectMapper mapper = new ObjectMapper(); + JsonNode tempJsonNode = mapper.readTree(tempJson); + jsonContent = decodeContent(tempJsonNode).toString(); + constructJson(policyData, jsonContent, dummyValue); + } catch (Exception e) { + LOGGER.error("Error while decoding microservice content", e); + } + + // ----Here is the final step to reset the original value back. + if(policyData.getJsonBody() != null && jsonStringValues.size() > 0){ + String contentBody = policyData.getJsonBody(); + JSONObject contentJson= new JSONObject(contentBody); + JSONObject content = contentJson.getJSONObject("content"); + content = setOriginalJsonObject(content, jsonStringValues); + contentJson.put("content", content); + policyData.setJsonBody(contentJson.toString()); + } + + return policyData; + } + + /** + * To save the original JSON string from the root. + * + * @param jsonObj holds the value from the root. + * @param jsonStringValues value get saved. + */ + private void saveOriginalJsonObject(JSONObject jsonObj, Map jsonStringValues) { + for (Object key : jsonObj.keySet()) { + String keyStr = (String) key; + Object keyvalue = jsonObj.get(keyStr); + if (keyvalue.toString().contains("{\\\"") || keyvalue.toString().contains("\\\"")) { + jsonStringValues.put(keyStr, keyvalue.toString()); + } + + // for nested objects iteration if required + if (keyvalue instanceof JSONObject) { + saveOriginalJsonObject((JSONObject) keyvalue, jsonStringValues); + } + } + } + + /** + * To reset the original JSON string back associated to its key. + * + * @param jsonObj holds the original json. + * @param jsonStringValues value to be reset. + * @return + */ + private JSONObject setOriginalJsonObject(JSONObject jsonObj , Map jsonStringValues) { + for (Object key : jsonObj.keySet()) { + String keyStr = (String)key; + Object keyvalue = jsonObj.get(keyStr); + String originalValue = getOriginalValue(keyStr); + if (originalValue != null) { + jsonObj.put(keyStr, originalValue); + } + + //for nested objects iteration if required + if (keyvalue instanceof JSONObject) { + setOriginalJsonObject((JSONObject)keyvalue, jsonStringValues); + jsonObj.put(keyStr, originalValue); + } + + if (keyvalue instanceof JSONArray) { + for (int i = 0; i < ((JSONArray)keyvalue).length(); i++) { + JSONObject temp = ((JSONArray)keyvalue).getJSONObject(i); + setOriginalJsonObject(temp, jsonStringValues); + } + } + } + + return jsonObj; + } + + private GroupPolicyScopeList getPolicyObject(String policyScope) { + return (GroupPolicyScopeList) commonClassDao.getEntityItem(GroupPolicyScopeList.class, "name", policyScope); + } + + private PolicyRestAdapter constructJson(PolicyRestAdapter policyAdapter, String jsonContent, String dummyValue) { + ObjectWriter om = new ObjectMapper().writer(); + String json = ""; + DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject(); + MicroServiceModels returnModel = new MicroServiceModels(); + microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS)); + if (policyAdapter.getServiceType() != null) { + microServiceObject.setService(policyAdapter.getServiceType()); + microServiceObject.setVersion(policyAdapter.getVersion()); + returnModel = getAttributeObject(microServiceObject.getService(), microServiceObject.getVersion()); + } + if (returnModel.getAnnotation() == null || returnModel.getAnnotation().isEmpty()) { + if (policyAdapter.getUuid() != null) { + microServiceObject.setUuid(policyAdapter.getUuid()); + } + if (policyAdapter.getLocation() != null) { + microServiceObject.setLocation(policyAdapter.getLocation()); + } + if (policyAdapter.getConfigName() != null) { + microServiceObject.setConfigName(policyAdapter.getConfigName()); + } + GroupPolicyScopeList policyScopeValue = getPolicyObject(policyAdapter.getPolicyScope()); + if (policyScopeValue != null) { + microServiceObject.setPolicyScope(policyScopeValue.getGroupList()); + } + } + + if (policyAdapter.getPolicyName() != null) { + microServiceObject.setPolicyName(policyAdapter.getPolicyName()); + } + if (policyAdapter.getPolicyDescription() != null) { + microServiceObject.setDescription(policyAdapter.getPolicyDescription()); + } + if (policyAdapter.getPriority() != null) { + microServiceObject.setPriority(policyAdapter.getPriority()); + } else { + microServiceObject.setPriority("9999"); + } + + if (policyAdapter.getRiskLevel() != null) { + microServiceObject.setRiskLevel(policyAdapter.getRiskLevel()); + } + if (policyAdapter.getRiskType() != null) { + microServiceObject.setRiskType(policyAdapter.getRiskType()); + } + if (policyAdapter.getGuard() != null) { + microServiceObject.setGuard(policyAdapter.getGuard()); + } + microServiceObject.setContent(jsonContent); + + try { + json = om.writeValueAsString(microServiceObject); + } catch (JsonProcessingException e) { + LOGGER.error("Error writing out the object", e); + } + LOGGER.info("input json: " + json); + LOGGER.info("input jsonContent: " + jsonContent); + String cleanJson = cleanUPJson(json); + // --- reset empty value back after called cleanUPJson method and before calling removeNullAttributes + String tempJson = + StringUtils.replaceEach(cleanJson, new String[] {"\"" + dummyValue + "\""}, new String[] {"\"\""}); + LOGGER.info("tempJson: " + tempJson); + cleanJson = removeNullAttributes(tempJson); + policyAdapter.setJsonBody(cleanJson); + return policyAdapter; + } + + public String removeNullAttributes(String cleanJson) { + ObjectMapper mapper = new ObjectMapper(); + + try { + JsonNode rootNode = mapper.readTree(cleanJson); + JsonNode returnNode = mapper.readTree(cleanJson); + Iterator> fieldsIterator = rootNode.fields(); + boolean remove = false; + JsonObject removed = null; + boolean contentChanged = false; + while (fieldsIterator.hasNext()) { + Map.Entry field = fieldsIterator.next(); + final String key = field.getKey(); + final JsonNode value = field.getValue(); + if ("content".equalsIgnoreCase(key)) { + String contentStr = value.toString(); + try (JsonReader reader = Json.createReader(new StringReader(contentStr))) { + JsonObject jsonContent = reader.readObject(); + removed = removeNull(jsonContent); + if (!jsonContent.toString().equals(removed.toString())) { + contentChanged = true; + } } - if (value==null || value.isNull()){ - ((ObjectNode) returnNode).remove(key); - remove = true; - } - } - if (remove){ - cleanJson = returnNode.toString(); - } - if (value==null || value.isNull()){ - ((ObjectNode) returnNode).remove(key); - remove = true; - } - } - if (remove){ - cleanJson = returnNode.toString(); - } - - if(contentChanged){ - //set modified content to cleanJson - JSONObject jObject = new JSONObject(cleanJson); - jObject.put("content",removed.toString()); - cleanJson = cleanUPJson(jObject.toString()); - } - - } catch (IOException e) { - LOGGER.error("Error writing out the JsonNode",e); - } - return cleanJson; - } - - public static JsonArray removeNull(JsonArray array) { - JsonArrayBuilder builder = Json.createArrayBuilder(); - int i = 0; - for (Iterator it = array.iterator(); it.hasNext(); ++i) { - JsonValue value = it.next(); - switch (value.getValueType()) { - case ARRAY: - JsonArray a = removeNull(array.getJsonArray(i)); - if (!a.isEmpty()) - builder.add(a); - break; - case OBJECT: - JsonObject object = removeNull(array.getJsonObject(i)); - if (!object.isEmpty()) - builder.add(object); - break; - case STRING: - String s = array.getString(i); - if (s != null && !s.isEmpty()) - builder.add(s); - break; - case NUMBER: - builder.add(array.getJsonNumber(i)); - break; - case TRUE: - case FALSE: - builder.add(array.getBoolean(i)); - break; - case NULL: - break; - } - } - return builder.build(); - } - - public static JsonObject removeNull(JsonObject obj) { - JsonObjectBuilder builder = Json.createObjectBuilder(); - for (Iterator> it = obj.entrySet().iterator(); it.hasNext();) { - Entry e = it.next(); - String key = e.getKey(); - JsonValue value = e.getValue(); - switch (value.getValueType()) { - case ARRAY: - JsonArray array = removeNull(obj.getJsonArray(key)); - if (!array.isEmpty()) - builder.add(key, array); - break; - case OBJECT: - JsonObject object = removeNull(obj.getJsonObject(key)); - if (!object.isEmpty()) - builder.add(key, object); - break; - case STRING: - String s = obj.getString(key); - if (s != null && !s.isEmpty()) - builder.add(key, s); - break; - case NUMBER: - builder.add(key, obj.getJsonNumber(key)); - break; - case TRUE: - case FALSE: - builder.add(key, obj.getBoolean(key)); - break; - case NULL: - break; - } - } - return builder.build(); - } - - public String cleanUPJson(String json) { - String cleanJson = StringUtils.replaceEach(json, new String[]{"\\\\", "\\\\\\", "\\\\\\\\"}, new String[]{"\\", "\\", "\\"}); - cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\"}, new String[]{"\\"}); - cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\", "[[", "]]"}, new String[]{"\\", "[", "]"}); - - cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\"", "\\\"", "\"[{", "}]\""}, new String[]{"\"", "\"", "[{", "}]"}); - cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[{", "}]\""}, new String[]{"[{", "}]"}); - cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"}); - cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"{", "}\""}, new String[]{"{", "}"}); - cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\"\"", "\"\""}, new String[]{"\"", "\""}); - cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\""}, new String[]{""}); - cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\""}, new String[]{"\""}); - cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\\\\\\"}, new String[]{"\""}); - cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\\""}, new String[]{"\""}); - cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"}); - return cleanJson; - } - - public JSONObject decodeContent(JsonNode jsonNode){ - Iterator jsonElements = jsonNode.elements(); - Iterator jsonKeys = jsonNode.fieldNames(); - Map element = new TreeMap<>(); - while(jsonElements.hasNext() && jsonKeys.hasNext()){ - element.put(jsonKeys.next(), jsonElements.next().toString()); - } - JSONObject jsonResult = new JSONObject(); - JSONArray jsonArray = null; - String oldValue = null; - String nodeKey = null; - String arryKey = null; - Boolean isArray = false; - JsonNodeFactory nodeFactory = JsonNodeFactory.instance; - ObjectNode node = nodeFactory.objectNode(); - String prevKey = null; - String presKey; - for(Entry entry: element.entrySet()){ - String key = entry.getKey(); - String value = entry.getValue(); - if(key.contains(".")){ - presKey = key.substring(0,key.indexOf('.')); - }else if(key.contains("@")){ - presKey = key.substring(0,key.indexOf('@')); - }else{ - presKey = key; - } - // first check if we are different from old. - LOGGER.info(key+"\n"); - if(jsonArray!=null && jsonArray.length()>0 && key.contains("@") && !key.contains(".") && oldValue!=null){ - if(!oldValue.equals(key.substring(0,key.indexOf('@')))){ - jsonResult.put(oldValue, jsonArray); - jsonArray = new JSONArray(); - } - }else if(jsonArray!=null && jsonArray.length()>0 && !presKey.equals(prevKey) && oldValue!=null){ - jsonResult.put(oldValue, jsonArray); - isArray = false; - jsonArray = new JSONArray(); - } - - prevKey = presKey; - // - if(key.contains(".")){ - if(nodeKey==null){ - nodeKey = key.substring(0,key.indexOf('.')); - } - if(nodeKey.equals(key.substring(0,key.indexOf('.')))){ - node.put(key.substring(key.indexOf('.')+1), value); - }else{ - if(node.size()!=0){ - if(nodeKey.contains("@")){ - if(arryKey==null){ - arryKey = nodeKey.substring(0,nodeKey.indexOf('@')); - } - if(nodeKey.endsWith("@0")){ - isArray = true; - jsonArray = new JSONArray(); - } - if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf('@')))){ - jsonArray.put(decodeContent(node)); - } - if((key.contains("@") && !arryKey.equals(key.substring(0,nodeKey.indexOf('@')))) || !key.contains("@")){ - jsonResult.put(arryKey, jsonArray); - jsonArray = new JSONArray(); - } - arryKey = nodeKey.substring(0,nodeKey.indexOf('@')); - }else{ - isArray = false; - jsonResult.put(nodeKey, decodeContent(node)); - } - node = nodeFactory.objectNode(); - } - nodeKey = key.substring(0,key.indexOf('.')); - if(nodeKey.contains("@")){ - arryKey = nodeKey.substring(0,nodeKey.indexOf('@')); - } - node.put(key.substring(key.indexOf('.')+1), value); - } - }else { - if(node.size()!=0){ - if(nodeKey.contains("@")){ - if(arryKey==null){ - arryKey = nodeKey.substring(0,nodeKey.indexOf('@')); - } - if(nodeKey.endsWith("@0")){ - isArray = true; - jsonArray = new JSONArray(); - } - if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf('@')))){ - jsonArray.put(decodeContent(node)); - } - jsonResult.put(arryKey, jsonArray); - jsonArray = new JSONArray(); - arryKey = nodeKey.substring(0,nodeKey.indexOf('@')); - }else{ - isArray = false; - jsonResult.put(nodeKey, decodeContent(node)); - } - node = nodeFactory.objectNode(); - } - if(key.contains("@")){ - isArray = true; - if(key.endsWith("@0")|| jsonArray==null){ - jsonArray = new JSONArray(); - } - }else if(!key.contains("@")){ - isArray = false; - } - if(isArray){ - if(oldValue==null){ - oldValue = key.substring(0,key.indexOf('@')); - } - if(oldValue!=prevKey){ - oldValue = key.substring(0,key.indexOf('@')); - } - if(oldValue.equals(key.substring(0,key.indexOf('@')))){ - jsonArray.put(value); - }else{ - jsonResult.put(oldValue, jsonArray); - jsonArray = new JSONArray(); - } - oldValue = key.substring(0,key.indexOf('@')); - }else{ - jsonResult.put(key, value); - } - } - } - if(node.size()>0){ - if(nodeKey.contains("@")){ - if(jsonArray==null){ - jsonArray = new JSONArray(); - } - if(arryKey==null){ - arryKey = nodeKey.substring(0,nodeKey.indexOf('@')); - } - jsonArray.put(decodeContent(node)); - jsonResult.put(arryKey, jsonArray); - isArray = false; - }else{ - jsonResult.put(nodeKey, decodeContent(node)); - } - } - if(isArray && jsonArray.length() > 0){ - jsonResult.put(oldValue, jsonArray); - } - return jsonResult; - } - - @RequestMapping(value={"/policyController/getDCAEMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView getDCAEMSTemplateData(HttpServletRequest request, HttpServletResponse response) throws IOException{ - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - - String value = root.get("policyData").toString().replaceAll("^\"|\"$", ""); - String servicename = value.split("-v")[0]; - String version = null; - if (value.contains("-v")){ - version = value.split("-v")[1]; - } - MicroServiceModels returnModel = getAttributeObject(servicename, version); - - MicroserviceHeaderdeFaults returnHeaderDefauls = getHeaderDefaultsObject(value); - JSONObject jsonHdDefaultObj = null; - if(returnHeaderDefauls != null){ - jsonHdDefaultObj = new JSONObject(); - jsonHdDefaultObj.put("onapName", returnHeaderDefauls.getOnapName()); - jsonHdDefaultObj.put("guard", returnHeaderDefauls.getGuard()); - jsonHdDefaultObj.put("riskLevel", returnHeaderDefauls.getRiskLevel()); - jsonHdDefaultObj.put("riskType", returnHeaderDefauls.getRiskType()); - jsonHdDefaultObj.put("priority", returnHeaderDefauls.getPriority()); - } - String headDefautlsData = ""; - if(jsonHdDefaultObj != null){ - headDefautlsData = jsonHdDefaultObj.toString(); - }else{ - headDefautlsData = "null"; - } - - //Get all keys with "MANY-true" defined in their value from subAttribute - Set allkeys = null; - if(returnModel.getSub_attributes() != null && !returnModel.getSub_attributes().isEmpty()){ - JSONObject json = new JSONObject(returnModel.getSub_attributes()); - getAllKeys(json); - allkeys = allManyTrueKeys; - allManyTrueKeys = new HashSet <>(); - LOGGER.info("allkeys : " + allkeys); - } - - //Get element order info - String dataOrderInfo = returnModel.getDataOrderInfo(); - if(dataOrderInfo != null && !dataOrderInfo.startsWith("\"")){ + if (value == null || value.isNull()) { + ((ObjectNode) returnNode).remove(key); + remove = true; + } + } + if (remove) { + cleanJson = returnNode.toString(); + } + if (value == null || value.isNull()) { + ((ObjectNode) returnNode).remove(key); + remove = true; + } + } + if (remove) { + cleanJson = returnNode.toString(); + } + + if (contentChanged) { + // set modified content to cleanJson + JSONObject jObject = new JSONObject(cleanJson); + jObject.put("content", removed.toString()); + cleanJson = cleanUPJson(jObject.toString()); + } + + } catch (IOException e) { + LOGGER.error("Error writing out the JsonNode", e); + } + return cleanJson; + } + + /** + * To verify if it is a JSON string. If it is, then return its original value. + * + * @param key holds the values + * @return + */ + private String getOriginalValue(String key) { + for (String k : jsonStringValues.keySet()) { + if (k.contains("@")) { + String[] arrOfKeys = k.split("@"); + for (int i = 0; i < arrOfKeys.length; i++) { + if (arrOfKeys[i].contains(".")) { + arrOfKeys[i] = arrOfKeys[i].substring(arrOfKeys[i].indexOf(".") + 1); + if (arrOfKeys[i].equals(key)) { + return StringUtils.replaceEach(jsonStringValues.get(k), new String[] {"\""}, + new String[] {"\\\""}); + } + } + } + } + if (k.endsWith(key)) { + return StringUtils.replaceEach(jsonStringValues.get(k), new String[] {"\""}, new String[] {"\\\""}); + } + } + + return null; + } + + public JsonArray removeNull(JsonArray array) { + JsonArrayBuilder builder = Json.createArrayBuilder(); + int i = 0; + for (Iterator it = array.iterator(); it.hasNext(); ++i) { + JsonValue value = it.next(); + switch (value.getValueType()) { + case ARRAY: + JsonArray a = removeNull(array.getJsonArray(i)); + if (!a.isEmpty()) + builder.add(a); + break; + case OBJECT: + JsonObject object = removeNull(array.getJsonObject(i)); + if (!object.isEmpty()) + builder.add(object); + break; + case STRING: + String s = array.getString(i); + if (s != null && !s.isEmpty()) + builder.add(s); + break; + case NUMBER: + builder.add(array.getJsonNumber(i)); + break; + case TRUE: + case FALSE: + builder.add(array.getBoolean(i)); + break; + case NULL: + break; + } + } + return builder.build(); + } + + public JsonObject removeNull(JsonObject obj) { + JsonObjectBuilder builder = Json.createObjectBuilder(); + for (Iterator> it = obj.entrySet().iterator(); it.hasNext();) { + Entry e = it.next(); + String key = e.getKey(); + JsonValue value = e.getValue(); + switch (value.getValueType()) { + case ARRAY: + JsonArray array = removeNull(obj.getJsonArray(key)); + if (!array.isEmpty()) + builder.add(key, array); + break; + case OBJECT: + JsonObject object = removeNull(obj.getJsonObject(key)); + if (!object.isEmpty()) { + if (!jsonStringValues.isEmpty()) { + String originalValue = getOriginalValue(key); + if (originalValue != null) { + builder.add(key, object.toString()); + break; + } + } + builder.add(key, object); + } + break; + case STRING: + String s = obj.getString(key); + if (s != null && !s.isEmpty()) { + if (!jsonStringValues.isEmpty()) { + String originalValue = getOriginalValue(key); + if (originalValue != null) { + s = getOriginalValue(key); + } + } + builder.add(key, s); + } + break; + case NUMBER: + builder.add(key, obj.getJsonNumber(key)); + break; + case TRUE: + case FALSE: + builder.add(key, obj.getBoolean(key)); + break; + case NULL: + break; + } + } + return builder.build(); + } + + public String cleanUPJson(String json) { + String cleanJson = StringUtils.replaceEach(json, new String[] {"\\\\", "\\\\\\", "\\\\\\\\"}, + new String[] {"\\", "\\", "\\"}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\\\\"}, new String[] {"\\"}); + cleanJson = + StringUtils.replaceEach(cleanJson, new String[] {"\\\\", "[[", "]]"}, new String[] {"\\", "[", "]"}); + + cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\\\"", "\\\"", "\"[{", "}]\""}, + new String[] {"\"", "\"", "[{", "}]"}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"[{", "}]\""}, new String[] {"[{", "}]"}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"[", "]\""}, new String[] {"[", "]"}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"{", "}\""}, new String[] {"{", "}"}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"\"\"", "\"\""}, new String[] {"\"", "\""}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\""}, new String[] {""}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"\""}, new String[] {"\""}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"\\\\\\"}, new String[] {"\""}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\\\\\""}, new String[] {"\""}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"[", "]\""}, new String[] {"[", "]"}); + return cleanJson; + } + + public JSONObject decodeContent(JsonNode jsonNode) { + Iterator jsonElements = jsonNode.elements(); + Iterator jsonKeys = jsonNode.fieldNames(); + Map element = new TreeMap<>(); + while (jsonElements.hasNext() && jsonKeys.hasNext()) { + element.put(jsonKeys.next(), jsonElements.next().toString()); + } + JSONObject jsonResult = new JSONObject(); + JSONArray jsonArray = null; + String oldValue = null; + String nodeKey = null; + String arryKey = null; + Boolean isArray = false; + JsonNodeFactory nodeFactory = JsonNodeFactory.instance; + ObjectNode node = nodeFactory.objectNode(); + String prevKey = null; + String presKey; + for (Entry entry : element.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + if (key.contains(".")) { + presKey = key.substring(0, key.indexOf('.')); + } else if (key.contains("@")) { + presKey = key.substring(0, key.indexOf('@')); + } else { + presKey = key; + } + // first check if we are different from old. + LOGGER.info(key + "\n"); + if (jsonArray != null && jsonArray.length() > 0 && key.contains("@") && !key.contains(".") + && oldValue != null) { + if (!oldValue.equals(key.substring(0, key.indexOf('@')))) { + jsonResult.put(oldValue, jsonArray); + jsonArray = new JSONArray(); + } + } else if (jsonArray != null && jsonArray.length() > 0 && !presKey.equals(prevKey) && oldValue != null) { + jsonResult.put(oldValue, jsonArray); + isArray = false; + jsonArray = new JSONArray(); + } + + prevKey = presKey; + // + if (key.contains(".")) { + if (nodeKey == null) { + nodeKey = key.substring(0, key.indexOf('.')); + } + if (nodeKey.equals(key.substring(0, key.indexOf('.')))) { + node.put(key.substring(key.indexOf('.') + 1), value); + } else { + if (node.size() != 0) { + if (nodeKey.contains("@")) { + if (arryKey == null) { + arryKey = nodeKey.substring(0, nodeKey.indexOf('@')); + } + if (nodeKey.endsWith("@0")) { + isArray = true; + jsonArray = new JSONArray(); + } + if (jsonArray != null && arryKey.equals(nodeKey.substring(0, nodeKey.indexOf('@')))) { + jsonArray.put(decodeContent(node)); + } + if ((key.contains("@") && !arryKey.equals(key.substring(0, nodeKey.indexOf('@')))) + || !key.contains("@")) { + jsonResult.put(arryKey, jsonArray); + jsonArray = new JSONArray(); + } + arryKey = nodeKey.substring(0, nodeKey.indexOf('@')); + } else { + isArray = false; + jsonResult.put(nodeKey, decodeContent(node)); + } + node = nodeFactory.objectNode(); + } + nodeKey = key.substring(0, key.indexOf('.')); + if (nodeKey.contains("@")) { + arryKey = nodeKey.substring(0, nodeKey.indexOf('@')); + } + node.put(key.substring(key.indexOf('.') + 1), value); + } + } else { + if (node.size() != 0) { + if (nodeKey.contains("@")) { + if (arryKey == null) { + arryKey = nodeKey.substring(0, nodeKey.indexOf('@')); + } + if (nodeKey.endsWith("@0")) { + isArray = true; + jsonArray = new JSONArray(); + } + if (jsonArray != null && arryKey.equals(nodeKey.substring(0, nodeKey.indexOf('@')))) { + jsonArray.put(decodeContent(node)); + } + jsonResult.put(arryKey, jsonArray); + jsonArray = new JSONArray(); + arryKey = nodeKey.substring(0, nodeKey.indexOf('@')); + } else { + isArray = false; + jsonResult.put(nodeKey, decodeContent(node)); + } + node = nodeFactory.objectNode(); + } + if (key.contains("@")) { + isArray = true; + if (key.endsWith("@0") || jsonArray == null) { + jsonArray = new JSONArray(); + } + } else if (!key.contains("@")) { + isArray = false; + } + if (isArray) { + if (oldValue == null) { + oldValue = key.substring(0, key.indexOf('@')); + } + if (oldValue != prevKey) { + oldValue = key.substring(0, key.indexOf('@')); + } + if (oldValue.equals(key.substring(0, key.indexOf('@')))) { + jsonArray.put(value); + } else { + jsonResult.put(oldValue, jsonArray); + jsonArray = new JSONArray(); + } + oldValue = key.substring(0, key.indexOf('@')); + } else { + jsonResult.put(key, value); + } + } + } + if (node.size() > 0) { + if (nodeKey.contains("@")) { + if (jsonArray == null) { + jsonArray = new JSONArray(); + } + if (arryKey == null) { + arryKey = nodeKey.substring(0, nodeKey.indexOf('@')); + } + jsonArray.put(decodeContent(node)); + jsonResult.put(arryKey, jsonArray); + isArray = false; + } else { + jsonResult.put(nodeKey, decodeContent(node)); + } + } + if (isArray && jsonArray.length() > 0) { + jsonResult.put(oldValue, jsonArray); + } + return jsonResult; + } + + @RequestMapping(value = {"/policyController/getDCAEMSTemplateData.htm"}, + method = {org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView getDCAEMSTemplateData(HttpServletRequest request, HttpServletResponse response) + throws IOException { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + + String value = root.get("policyData").toString().replaceAll("^\"|\"$", ""); + String servicename = value.split("-v")[0]; + String version = null; + if (value.contains("-v")) { + version = value.split("-v")[1]; + } + MicroServiceModels returnModel = getAttributeObject(servicename, version); + + MicroserviceHeaderdeFaults returnHeaderDefauls = getHeaderDefaultsObject(value); + JSONObject jsonHdDefaultObj = null; + if (returnHeaderDefauls != null) { + jsonHdDefaultObj = new JSONObject(); + jsonHdDefaultObj.put("onapName", returnHeaderDefauls.getOnapName()); + jsonHdDefaultObj.put("guard", returnHeaderDefauls.getGuard()); + jsonHdDefaultObj.put("riskLevel", returnHeaderDefauls.getRiskLevel()); + jsonHdDefaultObj.put("riskType", returnHeaderDefauls.getRiskType()); + jsonHdDefaultObj.put("priority", returnHeaderDefauls.getPriority()); + } + String headDefautlsData = ""; + if (jsonHdDefaultObj != null) { + headDefautlsData = jsonHdDefaultObj.toString(); + } else { + headDefautlsData = "null"; + } + + // Get all keys with "MANY-true" defined in their value from subAttribute + Set allkeys = null; + if (returnModel.getSub_attributes() != null && !returnModel.getSub_attributes().isEmpty()) { + JSONObject json = new JSONObject(returnModel.getSub_attributes()); + getAllKeys(json); + allkeys = allManyTrueKeys; + allManyTrueKeys = new HashSet<>(); + LOGGER.info("allkeys : " + allkeys); + } + + // Get element order info + String dataOrderInfo = returnModel.getDataOrderInfo(); + if (dataOrderInfo != null && !dataOrderInfo.startsWith("\"")) { dataOrderInfo = "\"" + dataOrderInfo + "\""; } LOGGER.info("dataOrderInfo : " + dataOrderInfo); - - String allManyTrueKeys = ""; - if(allkeys != null){ - allManyTrueKeys = allkeys.toString(); - } - - String jsonModel = createMicroSeriveJson(returnModel, allkeys); - - JSONObject jsonObject = new JSONObject(jsonModel); - - JSONObject finalJsonObject = null; - if(allkeys != null){ - Iterator iter = allkeys.iterator(); - while(iter.hasNext()){ - //Convert to array values for MANY-true keys - finalJsonObject = convertToArrayElement(jsonObject, iter.next()); - } - } - - if(finalJsonObject != null){ - LOGGER.info(finalJsonObject.toString()); - jsonModel = finalJsonObject.toString(); - } - - //get all properties with "MANY-true" defined in Ref_attributes - Set manyTrueProperties = getManyTrueProperties(returnModel.getRef_attributes()); - if(manyTrueProperties != null){ - JSONObject jsonObj = new JSONObject(jsonModel); - for (String s : manyTrueProperties) { - LOGGER.info(s); - //convert to array element for MANY-true properties - finalJsonObject = convertToArrayElement(jsonObj, s.trim()); - } - - if(finalJsonObject != null){ - LOGGER.info(finalJsonObject.toString()); - jsonModel = finalJsonObject.toString(); - } - } - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - List list = new ArrayList<>(); - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(returnModel); - - JSONObject j = null; - - if("".equals(allManyTrueKeys)){ - j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData +"}"); - }else{ - j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",allManyTrueKeys: " + allManyTrueKeys+",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData+ "}"); - } - list.add(j); - out.write(list.toString()); - return null; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - private String createMicroSeriveJson(MicroServiceModels returnModel, Set allkeys) { - Map attributeMap = new HashMap<>(); - Map refAttributeMap = new HashMap<>(); - String attribute = returnModel.getAttributes(); - if(attribute != null){ - attribute = attribute.trim(); - } - String refAttribute = returnModel.getRef_attributes(); - if(refAttribute != null){ - refAttribute = refAttribute.trim(); - } - String enumAttribute = returnModel.getEnumValues(); - if(enumAttribute != null){ - enumAttribute = enumAttribute.trim(); - } - if (!StringUtils.isEmpty(attribute)){ - attributeMap = convert(attribute, ","); - } - if (!StringUtils.isEmpty(refAttribute)){ - refAttributeMap = convert(refAttribute, ","); - } - - Gson gson = new Gson(); - - String subAttributes = returnModel.getSub_attributes(); - if(subAttributes != null){ - subAttributes = subAttributes.trim(); - }else{ - subAttributes = ""; - } - - Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class); - - JSONObject object = new JSONObject(); - JSONArray array = new JSONArray(); - - for (Entry keySet : attributeMap.entrySet()){ - array = new JSONArray(); - String value = keySet.getValue(); - if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])){ - array.put(value); - object.put(keySet.getKey().trim(), array); - }else { - object.put(keySet.getKey().trim(), value.trim()); - } - } - - for (Entry keySet : refAttributeMap.entrySet()){ - array = new JSONArray(); - String value = keySet.getValue().split(":")[0]; - if (gsonObject.containsKey(value)){ - if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])){ - array.put(recursiveReference(value, gsonObject, enumAttribute)); - object.put(keySet.getKey().trim(), array); - }else { - object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute)); - } - }else { - if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])){ - array.put(value.trim()); - object.put(keySet.getKey().trim(), array); - }else { - object.put(keySet.getKey().trim(), value.trim()); - } - } - } - - return object.toString(); - } - - @SuppressWarnings("unchecked") - private JSONObject recursiveReference(String name, Map subAttributeMap, String enumAttribute) { - JSONObject object = new JSONObject(); - Map map; - Object returnClass = subAttributeMap.get(name); - map = (Map) returnClass; - JSONArray array; - - for( Entry m:map.entrySet()){ - String[] splitValue = m.getValue().split(":"); - array = new JSONArray(); - if (subAttributeMap.containsKey(splitValue[0])){ - if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])){ - array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute)); - object.put(m.getKey().trim(), array); - }else { - object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute)); - } - } else{ - if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])){ - array.put(splitValue[0].trim()); - object.put(m.getKey().trim(), array); - }else { - object.put(m.getKey().trim(), splitValue[0].trim()); - } - } - } - - return object; - } - - - public static JSONObject convertToArrayElement(JSONObject json, String keyValue) { - return convertToArrayElement(json, new HashSet<>(), keyValue); - } - - private static JSONObject convertToArrayElement(JSONObject json, Set keys, String keyValue) { - for (String key : json.keySet()) { - Object obj = json.get(key); - if(key.equals(keyValue.trim())){ - if(!(obj instanceof JSONArray)){ - JSONArray newJsonArray = new JSONArray(); - newJsonArray.put(obj); - json.put(key, newJsonArray); - } - LOGGER.info("key : " + key); - LOGGER.info("obj : " + obj); - LOGGER.info("json.get(key) : " + json.get(key)); - LOGGER.info("keyValue : " + keyValue); - keys.addAll(json.keySet()); - - return json; - } - - if (obj instanceof JSONObject) convertToArrayElement(json.getJSONObject(key), keyValue); - } - - return json; - } - - // call this method to get all MANY-true properties - public static Set getManyTrueProperties(String referAttributes){ - LOGGER.info("referAttributes : " + referAttributes); - Set manyTrueProperties = new HashSet<>(); - - if(referAttributes != null){ - String[] referAarray = referAttributes.split(","); - String []element= null; - for(int i=0; i 1 && element[1].contains("MANY-true")){ - manyTrueProperties.add(element[0]); - } - } - } - - return manyTrueProperties; - } - - //call this method to start the recursive - private Set getAllKeys(JSONObject json) { - return getAllKeys(json, new HashSet<>()); - } - - private Set getAllKeys(JSONArray arr) { - return getAllKeys(arr, new HashSet<>()); - } - - private Set getAllKeys(JSONArray arr, Set keys) { - for (int i = 0; i < arr.length(); i++) { - Object obj = arr.get(i); - if (obj instanceof JSONObject) keys.addAll(getAllKeys(arr.getJSONObject(i))); - if (obj instanceof JSONArray) keys.addAll(getAllKeys(arr.getJSONArray(i))); - } - - return keys; - } - + + String allManyTrueKeys = ""; + if (allkeys != null) { + allManyTrueKeys = allkeys.toString(); + } + + String jsonModel = createMicroSeriveJson(returnModel, allkeys); + + JSONObject jsonObject = new JSONObject(jsonModel); + + JSONObject finalJsonObject = null; + if (allkeys != null) { + Iterator iter = allkeys.iterator(); + while (iter.hasNext()) { + // Convert to array values for MANY-true keys + finalJsonObject = convertToArrayElement(jsonObject, iter.next()); + } + } + + if (finalJsonObject != null) { + LOGGER.info(finalJsonObject.toString()); + jsonModel = finalJsonObject.toString(); + } + + // get all properties with "MANY-true" defined in Ref_attributes + Set manyTrueProperties = getManyTrueProperties(returnModel.getRef_attributes()); + if (manyTrueProperties != null) { + JSONObject jsonObj = new JSONObject(jsonModel); + for (String s : manyTrueProperties) { + LOGGER.info(s); + // convert to array element for MANY-true properties + finalJsonObject = convertToArrayElement(jsonObj, s.trim()); + } + + if (finalJsonObject != null) { + LOGGER.info(finalJsonObject.toString()); + jsonModel = finalJsonObject.toString(); + } + } + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + List list = new ArrayList<>(); + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(returnModel); + + JSONObject j = null; + + if ("".equals(allManyTrueKeys)) { + j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",dataOrderInfo:" + + dataOrderInfo + ",headDefautlsData:" + headDefautlsData + "}"); + } else { + j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",allManyTrueKeys: " + + allManyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData + + "}"); + } + list.add(j); + out.write(list.toString()); + return null; + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private String createMicroSeriveJson(MicroServiceModels returnModel, Set allkeys) { + Map attributeMap = new HashMap<>(); + Map refAttributeMap = new HashMap<>(); + String attribute = returnModel.getAttributes(); + if (attribute != null) { + attribute = attribute.trim(); + } + String refAttribute = returnModel.getRef_attributes(); + if (refAttribute != null) { + refAttribute = refAttribute.trim(); + } + String enumAttribute = returnModel.getEnumValues(); + if (enumAttribute != null) { + enumAttribute = enumAttribute.trim(); + } + if (!StringUtils.isEmpty(attribute)) { + attributeMap = convert(attribute, ","); + } + if (!StringUtils.isEmpty(refAttribute)) { + refAttributeMap = convert(refAttribute, ","); + } + + Gson gson = new Gson(); + + String subAttributes = returnModel.getSub_attributes(); + if (subAttributes != null) { + subAttributes = subAttributes.trim(); + } else { + subAttributes = ""; + } + + Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class); + + JSONObject object = new JSONObject(); + JSONArray array = new JSONArray(); + + for (Entry keySet : attributeMap.entrySet()) { + array = new JSONArray(); + String value = keySet.getValue(); + if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) { + array.put(value); + object.put(keySet.getKey().trim(), array); + } else { + object.put(keySet.getKey().trim(), value.trim()); + } + } + + for (Entry keySet : refAttributeMap.entrySet()) { + array = new JSONArray(); + String value = keySet.getValue().split(":")[0]; + if (gsonObject.containsKey(value)) { + if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) { + array.put(recursiveReference(value, gsonObject, enumAttribute)); + object.put(keySet.getKey().trim(), array); + } else { + object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute)); + } + } else { + if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) { + array.put(value.trim()); + object.put(keySet.getKey().trim(), array); + } else { + object.put(keySet.getKey().trim(), value.trim()); + } + } + } + + return object.toString(); + } + + @SuppressWarnings("unchecked") + private JSONObject recursiveReference(String name, Map subAttributeMap, String enumAttribute) { + JSONObject object = new JSONObject(); + Map map; + Object returnClass = subAttributeMap.get(name); + map = (Map) returnClass; + JSONArray array; + + for (Entry m : map.entrySet()) { + String[] splitValue = m.getValue().split(":"); + array = new JSONArray(); + if (subAttributeMap.containsKey(splitValue[0])) { + if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])) { + array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute)); + object.put(m.getKey().trim(), array); + } else { + object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute)); + } + } else { + if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])) { + array.put(splitValue[0].trim()); + object.put(m.getKey().trim(), array); + } else { + object.put(m.getKey().trim(), splitValue[0].trim()); + } + } + } + + return object; + } + + + public static JSONObject convertToArrayElement(JSONObject json, String keyValue) { + return convertToArrayElement(json, new HashSet<>(), keyValue); + } + + private static JSONObject convertToArrayElement(JSONObject json, Set keys, String keyValue) { + for (String key : json.keySet()) { + Object obj = json.get(key); + if (key.equals(keyValue.trim())) { + if (!(obj instanceof JSONArray)) { + JSONArray newJsonArray = new JSONArray(); + newJsonArray.put(obj); + json.put(key, newJsonArray); + } + LOGGER.info("key : " + key); + LOGGER.info("obj : " + obj); + LOGGER.info("json.get(key) : " + json.get(key)); + LOGGER.info("keyValue : " + keyValue); + keys.addAll(json.keySet()); + + return json; + } + + if (obj instanceof JSONObject) + convertToArrayElement(json.getJSONObject(key), keyValue); + } + + return json; + } + + // call this method to get all MANY-true properties + public static Set getManyTrueProperties(String referAttributes) { + LOGGER.info("referAttributes : " + referAttributes); + Set manyTrueProperties = new HashSet<>(); + + if (referAttributes != null) { + String[] referAarray = referAttributes.split(","); + String[] element = null; + for (int i = 0; i < referAarray.length; i++) { + element = referAarray[i].split("="); + if (element.length > 1 && element[1].contains("MANY-true")) { + manyTrueProperties.add(element[0]); + } + } + } + + return manyTrueProperties; + } + + // call this method to start the recursive + private Set getAllKeys(JSONObject json) { + return getAllKeys(json, new HashSet<>()); + } + + private Set getAllKeys(JSONArray arr) { + return getAllKeys(arr, new HashSet<>()); + } + + private Set getAllKeys(JSONArray arr, Set keys) { + for (int i = 0; i < arr.length(); i++) { + Object obj = arr.get(i); + if (obj instanceof JSONObject) + keys.addAll(getAllKeys(arr.getJSONObject(i))); + if (obj instanceof JSONArray) + keys.addAll(getAllKeys(arr.getJSONArray(i))); + } + + return keys; + } + // this method returns a set of keys with "MANY-true" defined in their value. - private Set getAllKeys(JSONObject json, Set keys) { - for (String key : json.keySet()) { - Object obj = json.get(key); - if(obj instanceof String && ((String) obj).contains("MANY-true")){ - LOGGER.info("key : " + key); - LOGGER.info("obj : " + obj); - allManyTrueKeys.add(key); - } - if (obj instanceof JSONObject) keys.addAll(getAllKeys(json.getJSONObject(key))); - if (obj instanceof JSONArray) keys.addAll(getAllKeys(json.getJSONArray(key))); - } - - return keys; - } - - - @RequestMapping(value={"/policyController/getModelServiceVersioneData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response) throws IOException{ - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - - String value = root.get("policyData").toString().replaceAll("^\"|\"$", ""); - String servicename = value.split("-v")[0]; - Set returnList = getVersionList(servicename); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - List list = new ArrayList<>(); - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(returnList); - JSONObject j = new JSONObject("{dcaeModelVersionData: " + responseString +"}"); - list.add(j); - out.write(list.toString()); - return null; - } - - private Set getVersionList(String name) { - MicroServiceModels workingModel; - Set list = new HashSet<>(); - List microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name); - for (int i = 0; i < microServiceModelsData.size(); i++) { - workingModel = (MicroServiceModels) microServiceModelsData.get(i); - if (workingModel.getVersion()!=null){ - list.add(workingModel.getVersion()); - }else{ - list.add("Default"); - } - } - return list; - } - - private MicroServiceModels getAttributeObject(String name, String version) { - MicroServiceModels workingModel = new MicroServiceModels(); - List microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name); - for (int i = 0; i < microServiceModelsData.size(); i++) { - workingModel = (MicroServiceModels) microServiceModelsData.get(i); - if(version != null){ - if (workingModel.getVersion()!=null){ - if (workingModel.getVersion().equals(version)){ - return workingModel; - } - }else{ - return workingModel; - } - }else{ - return workingModel; - } - - } - return workingModel; - } - - private MicroserviceHeaderdeFaults getHeaderDefaultsObject(String modelName) { - return (MicroserviceHeaderdeFaults) commonClassDao.getEntityItem(MicroserviceHeaderdeFaults.class, "modelName", modelName); - } - - @RequestMapping(value={"/get_DCAEPriorityValues"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - List priorityList = new ArrayList<>(); - priorityCount = 10; - for (int i = 1; i < priorityCount; i++) { - priorityList.add(String.valueOf(i)); - } - model.put("priorityDatas", mapper.writeValueAsString(priorityList)); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(e); - } - } - - public void prePopulateDCAEMSPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - if (policyAdapter.getPolicyData() instanceof PolicyType) { - Object policyData = policyAdapter.getPolicyData(); - PolicyType policy = (PolicyType) policyData; - policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); - String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") +3); - policyAdapter.setPolicyName(policyNameValue); - String description = ""; - try{ - description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); - }catch(Exception e){ - LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue ,e); - description = policy.getDescription(); - } - policyAdapter.setPolicyDescription(description); - // Get the target data under policy. - TargetType target = policy.getTarget(); - if (target != null) { - // Under target we have AnyOFType - List anyOfList = target.getAnyOf(); - if (anyOfList != null) { - Iterator iterAnyOf = anyOfList.iterator(); - while (iterAnyOf.hasNext()) { - AnyOfType anyOf = iterAnyOf.next(); - // Under AnyOFType 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 Match - List matchList = allOf.getMatch(); - if (matchList != null) { - Iterator iterMatch = matchList.iterator(); - while (matchList.size()>1 && iterMatch.hasNext()) { - MatchType match = iterMatch.next(); - // - // Under the match we have attribute value and - // attributeDesignator. So,finally down to the actual attribute. - // - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - // First match in the target is OnapName, so set that value. - if ("ONAPName".equals(attributeId)) { - policyAdapter.setOnapName(value); - } - if ("ConfigName".equals(attributeId)){ - policyAdapter.setConfigName(value); - } - if ("uuid".equals(attributeId)){ - policyAdapter.setUuid(value); - } - if ("location".equals(attributeId)){ - policyAdapter.setLocation(value); - } - if ("RiskType".equals(attributeId)){ - policyAdapter.setRiskType(value); - } - if ("RiskLevel".equals(attributeId)){ - policyAdapter.setRiskLevel(value); - } - if ("guard".equals(attributeId)){ - policyAdapter.setGuard(value); - } - if ("TTLDate".equals(attributeId) && !value.contains("NA")){ - PolicyController controller = new PolicyController(); - String newDate = controller.convertDate(value); - policyAdapter.setTtlDate(newDate); - } - } - readFile(policyAdapter, entity); - } - } - } - } - } - } - } - } - - public static Map convert(String str, String split) { - Map map = new HashMap<>(); - for(final String entry : str.split(split)) { - String[] parts = entry.split("="); - map.put(parts[0], parts[1]); - } - return map; - } - - - @SuppressWarnings("unchecked") - private void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) { - String policyScopeName = null; - ObjectMapper mapper = new ObjectMapper(); - try { - DCAEMicroServiceObject msBody = mapper.readValue(entity.getConfigurationData().getConfigBody(), DCAEMicroServiceObject.class); - policyScopeName = getPolicyScope(msBody.getPolicyScope()); - policyAdapter.setPolicyScope(policyScopeName); - - policyAdapter.setPriority(msBody.getPriority()); - - if (msBody.getVersion()!= null){ - policyAdapter.setServiceType(msBody.getService()); - policyAdapter.setVersion(msBody.getVersion()); - }else{ - policyAdapter.setServiceType(msBody.getService()); - } - if(msBody.getContent() != null){ - LinkedHashMap data = new LinkedHashMap<>(); - LinkedHashMap map = (LinkedHashMap) msBody.getContent(); - readRecursivlyJSONContent(map, data); - policyAdapter.setRuleData(data); - } - - } catch (Exception e) { - LOGGER.error(e); - } - - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public void readRecursivlyJSONContent(LinkedHashMap map, LinkedHashMap data){ - for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) { - Object key = iterator.next(); - Object value = map.get(key); - if(value instanceof LinkedHashMap){ - LinkedHashMap secondObjec = new LinkedHashMap<>(); - readRecursivlyJSONContent((LinkedHashMap) value, secondObjec); - for( Entry entry : secondObjec.entrySet()){ - data.put(key+"." + entry.getKey(), entry.getValue()); - } - }else if(value instanceof ArrayList){ - ArrayList jsonArrayVal = (ArrayList)value; - for(int i = 0; i < jsonArrayVal.size(); i++){ - Object arrayvalue = jsonArrayVal.get(i); - if(arrayvalue instanceof LinkedHashMap){ - LinkedHashMap newData = new LinkedHashMap<>(); - readRecursivlyJSONContent((LinkedHashMap) arrayvalue, newData); - for(Entry entry: newData.entrySet()){ - data.put(key+"@"+i+"." +entry.getKey(), entry.getValue()); - } - }else if(arrayvalue instanceof ArrayList){ - ArrayList jsonArrayVal1 = (ArrayList)value; - for(int j = 0; j < jsonArrayVal1.size(); j++){ - Object arrayvalue1 = jsonArrayVal1.get(i); - data.put(key+"@"+j, arrayvalue1.toString()); - } - }else{ - data.put(key+"@"+i, arrayvalue.toString()); - } - } - }else{ - data.put(key.toString(), value.toString()); - } - } - } - - public String getPolicyScope(String value) { - List groupList= commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value); - if(groupList != null && !groupList.isEmpty()){ - GroupPolicyScopeList pScope = (GroupPolicyScopeList) groupList.get(0); - return pScope.getGroupName(); - } - return null; - } - - //Convert the map values and set into JSON body - public Map convertMap(Map attributesMap, Map attributesRefMap) { - Map attribute = new HashMap<>(); - StringBuilder temp; - String key; - String value; - for (Entry entry : attributesMap.entrySet()) { - key = entry.getKey(); - value = entry.getValue(); - attribute.put(key, value); - } - for (Entry entryRef : attributesRefMap.entrySet()) { - key = entryRef.getKey(); - value = entryRef.getValue(); - attribute.put(key, value); - } - for (Entry entryList : attributesListRefMap.entrySet()) { - key = entryList.getKey(); - value = entryList.getValue(); - attribute.put(key, value); - } - for (Entry> arrayList : arrayTextList.entrySet()){ - key = arrayList.getKey(); - temp = null; - for (Object textList : arrayList.getValue()){ - if (temp == null){ - temp = new StringBuilder(); - temp.append("[" + textList); - }else{ - temp.append("," + textList); - } - } - attribute.put(key, temp+ "]"); - } - - return attribute; - } - - @RequestMapping(value={"/ms_dictionary/set_MSModelData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public void SetMSModelData(HttpServletRequest request, HttpServletResponse response) throws IOException, FileUploadException{ - modelList = new ArrayList<>(); - dirDependencyList = new ArrayList<>(); - classMap = new LinkedHashMap<>(); - List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); - boolean zip = false; - boolean yml= false; - String errorMsg = ""; - for (FileItem item : items) { - if(item.getName().endsWith(".zip") || item.getName().endsWith(".xmi")||item.getName().endsWith(".yml")){ - this.newModel = new MicroServiceModels(); - try{ - File file = new File(item.getName()); - OutputStream outputStream = new FileOutputStream(file); - IOUtils.copy(item.getInputStream(), outputStream); - outputStream.close(); - this.newFile = file.toString(); - this.newModel.setModelName(this.newFile.split("-v")[0]); - - if (this.newFile.contains("-v")){ - if (item.getName().endsWith(".zip")){ - this.newModel.setVersion(this.newFile.split("-v")[1].replace(".zip", "")); - zip = true; - }else if(item.getName().endsWith(".yml")){ - this.newModel.setVersion(this.newFile.split("-v")[1].replace(".yml", "")); - yml = true; - } - else { - this.newModel.setVersion(this.newFile.split("-v")[1].replace(".xmi", "")); - } - } - }catch(Exception e){ - LOGGER.error("Upload error : ", e); - errorMsg = "Upload error:" + e.getMessage(); - } - } - - } - - if(!errorMsg.isEmpty()){ - - PrintWriter out = response.getWriter(); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - JSONObject j = new JSONObject(); - j.put("errorMsg", errorMsg); - out.write(j.toString()); - return; - } - - List fileList = new ArrayList<>(); - MSModelUtils msMLUtils = new MSModelUtils(); - this.directory = "model"; - if (zip){ - extractFolder(this.newFile); - fileList = listModelFiles(this.directory); - }else if (yml==true){ - - errorMsg = msMLUtils.parseTosca(this.newFile); - if(errorMsg != null){ - PrintWriter out = response.getWriter(); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - JSONObject j = new JSONObject(); - j.put("errorMsg", errorMsg); - out.write(j.toString()); - return; - } - - }else { - File file = new File(this.newFile); - fileList.add(file); - } - String modelType= ""; - if(!yml){ - modelType="xmi"; - //Process Main Model file first - classMap = new LinkedHashMap<>(); - for (File file : fileList) { - if(!file.isDirectory() && file.getName().endsWith(".xmi")){ - retreiveDependency(file.toString(), true); - } - } - - modelList = createList(); - - cleanUp(this.newFile); - cleanUp(directory); - }else{ - modelType="yml"; - modelList.add(this.newModel.getModelName()); - String className=this.newModel.getModelName(); - MSAttributeObject msAttributes= new MSAttributeObject(); - msAttributes.setClassName(className); - - LinkedHashMap returnAttributeList =new LinkedHashMap<>(); - returnAttributeList.put(className, msMLUtils.getAttributeString()); - msAttributes.setAttribute(returnAttributeList); - - msAttributes.setSubClass(msMLUtils.getRetmap()); - - msAttributes.setMatchingSet(msMLUtils.getMatchableValues()); - - LinkedHashMap returnReferenceList =new LinkedHashMap<>(); - - returnReferenceList.put(className, msMLUtils.getReferenceAttributes()); - msAttributes.setRefAttribute(returnReferenceList); - - if(msMLUtils.getListConstraints()!=""){ - LinkedHashMap enumList =new LinkedHashMap<>(); - String[] listArray=msMLUtils.getListConstraints().split("#"); - for(String str:listArray){ - String[] strArr= str.split("="); - if(strArr.length>1){ + private Set getAllKeys(JSONObject json, Set keys) { + for (String key : json.keySet()) { + Object obj = json.get(key); + if (obj instanceof String && ((String) obj).contains("MANY-true")) { + LOGGER.info("key : " + key); + LOGGER.info("obj : " + obj); + allManyTrueKeys.add(key); + } + if (obj instanceof JSONObject) + keys.addAll(getAllKeys(json.getJSONObject(key))); + if (obj instanceof JSONArray) + keys.addAll(getAllKeys(json.getJSONArray(key))); + } + + return keys; + } + + + @RequestMapping(value = {"/policyController/getModelServiceVersioneData.htm"}, + method = {org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response) + throws IOException { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + + String value = root.get("policyData").toString().replaceAll("^\"|\"$", ""); + String servicename = value.split("-v")[0]; + Set returnList = getVersionList(servicename); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + List list = new ArrayList<>(); + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(returnList); + JSONObject j = new JSONObject("{dcaeModelVersionData: " + responseString + "}"); + list.add(j); + out.write(list.toString()); + return null; + } + + private Set getVersionList(String name) { + MicroServiceModels workingModel; + Set list = new HashSet<>(); + List microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name); + for (int i = 0; i < microServiceModelsData.size(); i++) { + workingModel = (MicroServiceModels) microServiceModelsData.get(i); + if (workingModel.getVersion() != null) { + list.add(workingModel.getVersion()); + } else { + list.add("Default"); + } + } + return list; + } + + private MicroServiceModels getAttributeObject(String name, String version) { + MicroServiceModels workingModel = new MicroServiceModels(); + List microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name); + for (int i = 0; i < microServiceModelsData.size(); i++) { + workingModel = (MicroServiceModels) microServiceModelsData.get(i); + if (version != null) { + if (workingModel.getVersion() != null) { + if (workingModel.getVersion().equals(version)) { + return workingModel; + } + } else { + return workingModel; + } + } else { + return workingModel; + } + + } + return workingModel; + } + + private MicroserviceHeaderdeFaults getHeaderDefaultsObject(String modelName) { + return (MicroserviceHeaderdeFaults) commonClassDao.getEntityItem(MicroserviceHeaderdeFaults.class, "modelName", + modelName); + } + + @RequestMapping(value = {"/get_DCAEPriorityValues"}, + method = {org.springframework.web.bind.annotation.RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response) { + try { + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + List priorityList = new ArrayList<>(); + priorityCount = 10; + for (int i = 1; i < priorityCount; i++) { + priorityList.add(String.valueOf(i)); + } + model.put("priorityDatas", mapper.writeValueAsString(priorityList)); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } catch (Exception e) { + LOGGER.error(e); + } + } + + public void prePopulateDCAEMSPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + if (policyAdapter.getPolicyData() instanceof PolicyType) { + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = + policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") + 3); + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try { + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + } catch (Exception e) { + LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e); + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Get the target data under policy. + TargetType target = policy.getTarget(); + if (target != null) { + // Under target we have AnyOFType + List anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AnyOFType 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 Match + List matchList = allOf.getMatch(); + if (matchList != null) { + Iterator iterMatch = matchList.iterator(); + while (matchList.size() > 1 && iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attribute value and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + // First match in the target is OnapName, so set that value. + if ("ONAPName".equals(attributeId)) { + policyAdapter.setOnapName(value); + } + if ("ConfigName".equals(attributeId)) { + policyAdapter.setConfigName(value); + } + if ("uuid".equals(attributeId)) { + policyAdapter.setUuid(value); + } + if ("location".equals(attributeId)) { + policyAdapter.setLocation(value); + } + if ("RiskType".equals(attributeId)) { + policyAdapter.setRiskType(value); + } + if ("RiskLevel".equals(attributeId)) { + policyAdapter.setRiskLevel(value); + } + if ("guard".equals(attributeId)) { + policyAdapter.setGuard(value); + } + if ("TTLDate".equals(attributeId) && !value.contains("NA")) { + PolicyController controller = new PolicyController(); + String newDate = controller.convertDate(value); + policyAdapter.setTtlDate(newDate); + } + } + readFile(policyAdapter, entity); + } + } + } + } + } + } + } + } + + public static Map convert(String str, String split) { + Map map = new HashMap<>(); + for (final String entry : str.split(split)) { + String[] parts = entry.split("="); + map.put(parts[0], parts[1]); + } + return map; + } + + + @SuppressWarnings("unchecked") + private void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + String policyScopeName = null; + ObjectMapper mapper = new ObjectMapper(); + try { + DCAEMicroServiceObject msBody = + mapper.readValue(entity.getConfigurationData().getConfigBody(), DCAEMicroServiceObject.class); + policyScopeName = getPolicyScope(msBody.getPolicyScope()); + policyAdapter.setPolicyScope(policyScopeName); + + policyAdapter.setPriority(msBody.getPriority()); + + if (msBody.getVersion() != null) { + policyAdapter.setServiceType(msBody.getService()); + policyAdapter.setVersion(msBody.getVersion()); + } else { + policyAdapter.setServiceType(msBody.getService()); + } + if (msBody.getContent() != null) { + LinkedHashMap data = new LinkedHashMap<>(); + LinkedHashMap map = (LinkedHashMap) msBody.getContent(); + readRecursivlyJSONContent(map, data); + policyAdapter.setRuleData(data); + } + + } catch (Exception e) { + LOGGER.error(e); + } + + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + public void readRecursivlyJSONContent(LinkedHashMap map, LinkedHashMap data) { + for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) { + Object key = iterator.next(); + Object value = map.get(key); + if (value instanceof LinkedHashMap) { + LinkedHashMap secondObjec = new LinkedHashMap<>(); + readRecursivlyJSONContent((LinkedHashMap) value, secondObjec); + for (Entry entry : secondObjec.entrySet()) { + data.put(key + "." + entry.getKey(), entry.getValue()); + } + } else if (value instanceof ArrayList) { + ArrayList jsonArrayVal = (ArrayList) value; + for (int i = 0; i < jsonArrayVal.size(); i++) { + Object arrayvalue = jsonArrayVal.get(i); + if (arrayvalue instanceof LinkedHashMap) { + LinkedHashMap newData = new LinkedHashMap<>(); + readRecursivlyJSONContent((LinkedHashMap) arrayvalue, newData); + for (Entry entry : newData.entrySet()) { + data.put(key + "@" + i + "." + entry.getKey(), entry.getValue()); + } + } else if (arrayvalue instanceof ArrayList) { + ArrayList jsonArrayVal1 = (ArrayList) value; + for (int j = 0; j < jsonArrayVal1.size(); j++) { + Object arrayvalue1 = jsonArrayVal1.get(i); + data.put(key + "@" + j, arrayvalue1.toString()); + } + } else { + data.put(key + "@" + i, arrayvalue.toString()); + } + } + } else { + data.put(key.toString(), value.toString()); + } + } + } + + public String getPolicyScope(String value) { + List groupList = commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value); + if (groupList != null && !groupList.isEmpty()) { + GroupPolicyScopeList pScope = (GroupPolicyScopeList) groupList.get(0); + return pScope.getGroupName(); + } + return null; + } + + // Convert the map values and set into JSON body + public Map convertMap(Map attributesMap, Map attributesRefMap) { + Map attribute = new HashMap<>(); + StringBuilder temp; + String key; + String value; + for (Entry entry : attributesMap.entrySet()) { + key = entry.getKey(); + value = entry.getValue(); + attribute.put(key, value); + } + for (Entry entryRef : attributesRefMap.entrySet()) { + key = entryRef.getKey(); + value = entryRef.getValue(); + attribute.put(key, value); + } + for (Entry entryList : attributesListRefMap.entrySet()) { + key = entryList.getKey(); + value = entryList.getValue(); + attribute.put(key, value); + } + for (Entry> arrayList : arrayTextList.entrySet()) { + key = arrayList.getKey(); + temp = null; + for (Object textList : arrayList.getValue()) { + if (temp == null) { + temp = new StringBuilder(); + temp.append("[" + textList); + } else { + temp.append("," + textList); + } + } + attribute.put(key, temp + "]"); + } + + return attribute; + } + + @RequestMapping(value = {"/ms_dictionary/set_MSModelData"}, + method = {org.springframework.web.bind.annotation.RequestMethod.POST}) + public void SetMSModelData(HttpServletRequest request, HttpServletResponse response) + throws IOException, FileUploadException { + modelList = new ArrayList<>(); + dirDependencyList = new ArrayList<>(); + classMap = new LinkedHashMap<>(); + List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); + boolean zip = false; + boolean yml = false; + String errorMsg = ""; + for (FileItem item : items) { + if (item.getName().endsWith(".zip") || item.getName().endsWith(".xmi") || item.getName().endsWith(".yml")) { + this.newModel = new MicroServiceModels(); + try { + File file = new File(item.getName()); + OutputStream outputStream = new FileOutputStream(file); + IOUtils.copy(item.getInputStream(), outputStream); + outputStream.close(); + this.newFile = file.toString(); + this.newModel.setModelName(this.newFile.split("-v")[0]); + + if (this.newFile.contains("-v")) { + if (item.getName().endsWith(".zip")) { + this.newModel.setVersion(this.newFile.split("-v")[1].replace(".zip", "")); + zip = true; + } else if (item.getName().endsWith(".yml")) { + this.newModel.setVersion(this.newFile.split("-v")[1].replace(".yml", "")); + yml = true; + } else { + this.newModel.setVersion(this.newFile.split("-v")[1].replace(".xmi", "")); + } + } + } catch (Exception e) { + LOGGER.error("Upload error : ", e); + errorMsg = "Upload error:" + e.getMessage(); + } + } + + } + + if (!errorMsg.isEmpty()) { + + PrintWriter out = response.getWriter(); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + JSONObject j = new JSONObject(); + j.put("errorMsg", errorMsg); + out.write(j.toString()); + return; + } + + List fileList = new ArrayList<>(); + MSModelUtils msMLUtils = new MSModelUtils(); + this.directory = "model"; + if (zip) { + extractFolder(this.newFile); + fileList = listModelFiles(this.directory); + } else if (yml == true) { + + errorMsg = msMLUtils.parseTosca(this.newFile); + if (errorMsg != null) { + PrintWriter out = response.getWriter(); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + JSONObject j = new JSONObject(); + j.put("errorMsg", errorMsg); + out.write(j.toString()); + return; + } + + } else { + File file = new File(this.newFile); + fileList.add(file); + } + String modelType = ""; + if (!yml) { + modelType = "xmi"; + // Process Main Model file first + classMap = new LinkedHashMap<>(); + for (File file : fileList) { + if (!file.isDirectory() && file.getName().endsWith(".xmi")) { + retreiveDependency(file.toString(), true); + } + } + + modelList = createList(); + + cleanUp(this.newFile); + cleanUp(directory); + } else { + modelType = "yml"; + modelList.add(this.newModel.getModelName()); + String className = this.newModel.getModelName(); + MSAttributeObject msAttributes = new MSAttributeObject(); + msAttributes.setClassName(className); + + LinkedHashMap returnAttributeList = new LinkedHashMap<>(); + returnAttributeList.put(className, msMLUtils.getAttributeString()); + msAttributes.setAttribute(returnAttributeList); + + msAttributes.setSubClass(msMLUtils.getRetmap()); + + msAttributes.setMatchingSet(msMLUtils.getMatchableValues()); + + LinkedHashMap returnReferenceList = new LinkedHashMap<>(); + + returnReferenceList.put(className, msMLUtils.getReferenceAttributes()); + msAttributes.setRefAttribute(returnReferenceList); + + if (msMLUtils.getListConstraints() != "") { + LinkedHashMap enumList = new LinkedHashMap<>(); + String[] listArray = msMLUtils.getListConstraints().split("#"); + for (String str : listArray) { + String[] strArr = str.split("="); + if (strArr.length > 1) { enumList.put(strArr[0], strArr[1]); } } - msAttributes.setEnumType(enumList); - } - - classMap=new LinkedHashMap<>(); - classMap.put(className, msAttributes); - - } - - PrintWriter out = response.getWriter(); - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - ObjectMapper mapper = new ObjectMapper(); - JSONObject j = new JSONObject(); - j.put("classListDatas", modelList); - j.put("modelDatas", mapper.writeValueAsString(classMap)); - j.put("modelType", modelType); - j.put("dataOrderInfo", msMLUtils.getDataOrderInfo()); - - out.write(j.toString()); - } - - /* - * Unzip file and store in the model directory for processing - */ - @SuppressWarnings("rawtypes") - private void extractFolder(String zipFile ) { - int BUFFER = 2048; - File file = new File(zipFile); - - try (ZipFile zip = new ZipFile(file)) { - String newPath = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4); - this.directory = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4); - checkZipDirectory(this.directory); - new File(newPath).mkdir(); - Enumeration zipFileEntries = zip.entries(); - - // Process each entry - while (zipFileEntries.hasMoreElements()){ - // grab a zip file entry - ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); - String currentEntry = entry.getName(); - File destFile = new File("model" + File.separator + currentEntry); - File destinationParent = destFile.getParentFile(); - - destinationParent.mkdirs(); - - if (!entry.isDirectory()){ - BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry)); - int currentByte; - byte[] data = new byte[BUFFER]; - try (FileOutputStream fos = new FileOutputStream(destFile); - BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) { - while ((currentByte = is.read(data, 0, BUFFER)) != -1) { - dest.write(data, 0, currentByte); - } - dest.flush(); - } catch (IOException e) { - LOGGER.error("Failed to write zip contents to {}" + destFile + e); - // - // PLD should I throw e? - // - throw e; - } - } - - if (currentEntry.endsWith(".zip")){ - extractFolder(destFile.getAbsolutePath()); - } - } - } catch (IOException e) { - LOGGER.error("Failed to unzip model file " + zipFile, e); - } - } - - private void retreiveDependency(String workingFile, Boolean modelClass) { - - MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName()); - Map tempMap; - - tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI); - - classMap.putAll(tempMap); - LOGGER.info(tempMap); - - return; - - } - - private List listModelFiles(String directoryName) { - File fileDirectory = new File(directoryName); - List resultList = new ArrayList<>(); - File[] fList = fileDirectory.listFiles(); - for (File file : fList) { - if (file.isFile()) { - resultList.add(file); - } else if (file.isDirectory()) { - dirDependencyList.add(file.getName()); - resultList.addAll(listModelFiles(file.getAbsolutePath())); - } - } - return resultList; - } - + msAttributes.setEnumType(enumList); + } + + classMap = new LinkedHashMap<>(); + classMap.put(className, msAttributes); + + } + + PrintWriter out = response.getWriter(); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + ObjectMapper mapper = new ObjectMapper(); + JSONObject j = new JSONObject(); + j.put("classListDatas", modelList); + j.put("modelDatas", mapper.writeValueAsString(classMap)); + j.put("modelType", modelType); + j.put("dataOrderInfo", msMLUtils.getDataOrderInfo()); + + out.write(j.toString()); + } + + /* + * Unzip file and store in the model directory for processing + */ + @SuppressWarnings("rawtypes") + private void extractFolder(String zipFile) { + int BUFFER = 2048; + File file = new File(zipFile); + + try (ZipFile zip = new ZipFile(file)) { + String newPath = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4); + this.directory = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4); + checkZipDirectory(this.directory); + new File(newPath).mkdir(); + Enumeration zipFileEntries = zip.entries(); + + // Process each entry + while (zipFileEntries.hasMoreElements()) { + // grab a zip file entry + ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); + String currentEntry = entry.getName(); + File destFile = new File("model" + File.separator + currentEntry); + File destinationParent = destFile.getParentFile(); + + destinationParent.mkdirs(); + + if (!entry.isDirectory()) { + BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry)); + int currentByte; + byte[] data = new byte[BUFFER]; + try (FileOutputStream fos = new FileOutputStream(destFile); + BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) { + while ((currentByte = is.read(data, 0, BUFFER)) != -1) { + dest.write(data, 0, currentByte); + } + dest.flush(); + } catch (IOException e) { + LOGGER.error("Failed to write zip contents to {}" + destFile + e); + // + // PLD should I throw e? + // + throw e; + } + } + + if (currentEntry.endsWith(".zip")) { + extractFolder(destFile.getAbsolutePath()); + } + } + } catch (IOException e) { + LOGGER.error("Failed to unzip model file " + zipFile, e); + } + } + + private void retreiveDependency(String workingFile, Boolean modelClass) { + + MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName()); + Map tempMap; + + tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI); + + classMap.putAll(tempMap); + LOGGER.info(tempMap); + + return; + + } + + private List listModelFiles(String directoryName) { + File fileDirectory = new File(directoryName); + List resultList = new ArrayList<>(); + File[] fList = fileDirectory.listFiles(); + for (File file : fList) { + if (file.isFile()) { + resultList.add(file); + } else if (file.isDirectory()) { + dirDependencyList.add(file.getName()); + resultList.addAll(listModelFiles(file.getAbsolutePath())); + } + } + return resultList; + } + public void cleanUp(String path) { - if (path!=null){ + if (path != null) { try { FileUtils.forceDelete(new File(path)); } catch (IOException e) { - LOGGER.error("Failed to delete folder " + path, e); - } + LOGGER.error("Failed to delete folder " + path, e); + } } } - + public void checkZipDirectory(String zipDirectory) { Path path = Paths.get(zipDirectory); - + if (Files.exists(path)) { cleanUp(zipDirectory); } } - + private List createList() { - List list = new ArrayList<>(); - for (Entry cMap : classMap.entrySet()){ - if (cMap.getValue().isPolicyTempalate()){ + List list = new ArrayList<>(); + for (Entry cMap : classMap.entrySet()) { + if (cMap.getValue().isPolicyTempalate()) { list.add(cMap.getKey()); } - + } - - if (list.isEmpty()){ - if (classMap.containsKey(this.newModel.getModelName())){ + + if (list.isEmpty()) { + if (classMap.containsKey(this.newModel.getModelName())) { list.add(this.newModel.getModelName()); - }else { + } else { list.add("EMPTY"); } } return list; } - public Map getAttributesListRefMap() { - return attributesListRefMap; - } + public Map getAttributesListRefMap() { + return attributesListRefMap; + } - public Map> getArrayTextList() { - return arrayTextList; - } + public Map> getArrayTextList() { + return arrayTextList; + } } + class DCAEMicroServiceObject { - private String service; - private String location; - private String uuid; - private String policyName; - private String description; - private String configName; - private String templateVersion; - private String version; - private String priority; - private String policyScope; - private String riskType; - private String riskLevel; - private String guard = null; - - public String getGuard() { - return guard; - } - public void setGuard(String guard) { - this.guard = guard; - } - public String getRiskType() { - return riskType; - } - public void setRiskType(String riskType) { - this.riskType = riskType; - } - public String getRiskLevel() { - return riskLevel; - } - public void setRiskLevel(String riskLevel) { - this.riskLevel = riskLevel; - } - public String getPolicyScope() { - return policyScope; - } - public void setPolicyScope(String policyScope) { - this.policyScope = policyScope; - } - - public String getPriority() { - return priority; - } - public void setPriority(String priority) { - this.priority = priority; - } - public String getVersion() { - return version; - } - public void setVersion(String version) { - this.version = version; - } - private Object content; - - - public String getPolicyName() { - return policyName; - } - public void setPolicyName(String policyName) { - this.policyName = policyName; - } - public String getDescription() { - return description; - } - public void setDescription(String description) { - this.description = description; - } - public String getConfigName() { - return configName; - } - public void setConfigName(String configName) { - this.configName = configName; - } - public Object getContent() { - return content; - } - public void setContent(Object content) { - this.content = content; - } - - public String getService() { - return service; - } - public void setService(String service) { - this.service = service; - } - public String getLocation() { - return location; - } - public void setLocation(String location) { - this.location = location; - } - - public String getUuid() { - return uuid; - } - public void setUuid(String uuid) { - this.uuid = uuid; - } - public String getTemplateVersion() { - return templateVersion; - } - public void setTemplateVersion(String templateVersion) { - this.templateVersion = templateVersion; - } - -} \ No newline at end of file + private String service; + private String location; + private String uuid; + private String policyName; + private String description; + private String configName; + private String templateVersion; + private String version; + private String priority; + private String policyScope; + private String riskType; + private String riskLevel; + private String guard = null; + + public String getGuard() { + return guard; + } + + public void setGuard(String guard) { + this.guard = guard; + } + + public String getRiskType() { + return riskType; + } + + public void setRiskType(String riskType) { + this.riskType = riskType; + } + + public String getRiskLevel() { + return riskLevel; + } + + public void setRiskLevel(String riskLevel) { + this.riskLevel = riskLevel; + } + + public String getPolicyScope() { + return policyScope; + } + + public void setPolicyScope(String policyScope) { + this.policyScope = policyScope; + } + + public String getPriority() { + return priority; + } + + public void setPriority(String priority) { + this.priority = priority; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + private Object content; + + + public String getPolicyName() { + return policyName; + } + + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getConfigName() { + return configName; + } + + public void setConfigName(String configName) { + this.configName = configName; + } + + public Object getContent() { + return content; + } + + public void setContent(Object content) { + this.content = content; + } + + public String getService() { + return service; + } + + public void setService(String service) { + this.service = service; + } + + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getTemplateVersion() { + return templateVersion; + } + + public void setTemplateVersion(String templateVersion) { + this.templateVersion = templateVersion; + } + +} 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 637b0fc52..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 @@ -29,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; @@ -36,11 +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.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,10 +590,10 @@ 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(); @@ -591,7 +602,7 @@ public class PolicyController extends RestrictedBaseController { /** * Switch Version Policy Content. - * + * * @param pName which is used to find associated versions. * @return list of available versions based on policy name. */ @@ -608,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]); @@ -624,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); @@ -649,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; } @@ -665,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; } @@ -705,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; } @@ -931,7 +952,7 @@ public class PolicyController extends RestrictedBaseController { /** * Set File Size limit. - * + * * @param uploadSize value. */ public static void setFileSizeLimit(String uploadSize) { @@ -949,7 +970,7 @@ public class PolicyController extends RestrictedBaseController { /** * Function to convert date. - * + * * @param dateTTL input date value. * @return */