diff options
Diffstat (limited to 'ONAP-PAP-REST')
24 files changed, 3020 insertions, 2269 deletions
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=<groupId> pdpId=<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<String> adminConsoleURLStringList = new CopyOnWriteArrayList<>(); + private static final CopyOnWriteArrayList<String> 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<OnapPDPGroup> 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<Properties> pdpDataByGroup) { + private void pdpChanged(OnapPDP pdp, ONAPLoggingContext loggingContext, + List<Properties> 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/CreateNewMicroServiceModel.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java index abb425131..86455aa30 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -333,7 +333,7 @@ public class CreateNewMicroServiceModel { Map<String, String> successMap = new HashMap<>(); CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); List<Object> result = dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName+":"+version); - if(result.isEmpty()){ + if(result == null || result.isEmpty()){ MicroServiceModels model = new MicroServiceModels(); model.setModelName(modelName); model.setVersion(version); 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<String, PDPPolicy> currentPolicyMap = new HashMap<>(); HashSet<String> 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<T> 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<PolicyEntity> 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<PolicyEntity> dbPolicyIt = groupToUpdateInDb.getPolicies().iterator(); - String policyName = policyDbDaoVar.getPolicyNameAndVersionFromPolicyFileName( - policyToDelete.getPolicyName())[0]; + Iterator<PolicyEntity> 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<PolicyEntity> 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/main/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryController.java index a0044d26b..d6ebed2b8 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryController.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * 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. @@ -20,15 +20,16 @@ package org.onap.policy.pap.xacml.rest.controller; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.List; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.apache.commons.io.IOUtils; import org.onap.policy.api.PEDependency; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -50,15 +51,11 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - @Controller -public class BRMSDictionaryController{ +public class BRMSDictionaryController { - private static final Logger LOGGER = FlexLogger.getLogger(BRMSDictionaryController.class); + private static final Logger LOGGER = FlexLogger.getLogger(BRMSDictionaryController.class); private static final String VALIDATIONRESPONSE = "Validation"; @@ -67,9 +64,9 @@ public class BRMSDictionaryController{ private static String successMsg = "Success"; private static String duplicateResponseString = "Duplicate"; private static String ruleName = "ruleName"; - private static String errorMessage = "Error"; + private static String errorMessage = "Error"; private static String operation = "operation"; - private static String dictionaryFields ="dictionaryFields"; + private static String dictionaryFields = "dictionaryFields"; private static String userid = "userid"; private static String dependencyName = "dependencyName"; private static String controllerName = "controllerName"; @@ -78,7 +75,7 @@ public class BRMSDictionaryController{ private static String brmsControllerDatas = "brmsControllerDictionaryDatas"; @Autowired - public BRMSDictionaryController(CommonClassDao commonClassDao){ + public BRMSDictionaryController(CommonClassDao commonClassDao) { BRMSDictionaryController.commonClassDao = commonClassDao; } @@ -90,32 +87,36 @@ public class BRMSDictionaryController{ super(); } - private DictionaryUtils getDictionaryUtilsInstance(){ + private DictionaryUtils getDictionaryUtilsInstance() { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value={"/get_BRMSParamDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getBRMSParamDictionaryByNameEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_BRMSParamDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getBRMSParamDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, brmsParamDatas, ruleName, BRMSParamTemplate.class); } - @RequestMapping(value={"/get_BRMSParamData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getBRMSParamDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_BRMSParamData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getBRMSParamDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, brmsParamDatas, BRMSParamTemplate.class); } - @RequestMapping(value={"/brms_dictionary/set_BRMSParamData"}, method={RequestMethod.POST}) - public static void setRuleData(HttpServletRequest request) throws IOException{ + @RequestMapping(value = {"/brms_dictionary/set_BRMSParamData"}, method = {RequestMethod.POST}) + public static void setRuleData(HttpServletRequest request) throws IOException { StringWriter writer = new StringWriter(); - IOUtils.copy(request.getInputStream() , writer, StandardCharsets.UTF_8); - String cleanStreamBoundary = writer.toString().replaceFirst("------(.*)(?s).*octet-stream", ""); - rule = cleanStreamBoundary.substring(0, cleanStreamBoundary.lastIndexOf("end")+4); + IOUtils.copy(request.getInputStream(), writer, StandardCharsets.UTF_8); + String cleanStreamBoundary = + writer.toString().replaceFirst("------(.*)(?s).*octet-stream", ""); + rule = cleanStreamBoundary.substring(0, cleanStreamBoundary.lastIndexOf("end") + 4); } - @RequestMapping(value={"/brms_dictionary/save_BRMSParam"}, method={RequestMethod.POST}) - public ModelAndView saveBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/brms_dictionary/save_BRMSParam"}, method = {RequestMethod.POST}) + public ModelAndView saveBRMSParamDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -125,83 +126,96 @@ public class BRMSDictionaryController{ BRMSParamTemplate bRMSParamTemplateData; String userId = null; - if(fromAPI){ - bRMSParamTemplateData = mapper.readValue(root.get(dictionaryFields).toString(), BRMSParamTemplate.class); + if (fromAPI) { + bRMSParamTemplateData = mapper.readValue(root.get(dictionaryFields).toString(), + BRMSParamTemplate.class); userId = "API"; - }else{ - bRMSParamTemplateData = mapper.readValue(root.get("brmsParamDictionaryData").toString(), BRMSParamTemplate.class); + } else { + bRMSParamTemplateData = mapper.readValue( + root.get("brmsParamDictionaryData").toString(), BRMSParamTemplate.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(bRMSParamTemplateData.getRuleName(), ruleName, BRMSParamTemplate.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry( + bRMSParamTemplateData.getRuleName(), ruleName, BRMSParamTemplate.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { BRMSParamTemplate data = (BRMSParamTemplate) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { bRMSParamTemplateData.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != bRMSParamTemplateData.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != bRMSParamTemplateData.getId()))) { duplicateflag = true; } } String responseString = null; boolean validation = false; - if(rule != null && CreateBRMSRuleTemplate.validateRuleParams(rule)){ + if (rule != null && CreateBRMSRuleTemplate.validateRuleParams(rule)) { bRMSParamTemplateData.setRule(rule); validation = true; - if(!duplicateflag){ - if(bRMSParamTemplateData.getId() == 0){ + if (!duplicateflag) { + if (bRMSParamTemplateData.getId() == 0) { bRMSParamTemplateData.setUserCreatedBy(userInfo); commonClassDao.save(bRMSParamTemplateData); - }else{ + } else { commonClassDao.update(bRMSParamTemplateData); } - responseString = mapper.writeValueAsString(commonClassDao.getData(BRMSParamTemplate.class)); - }else{ + responseString = mapper + .writeValueAsString(commonClassDao.getData(BRMSParamTemplate.class)); + } else { responseString = duplicateResponseString; } } - if(!validation){ + if (!validation) { responseString = VALIDATIONRESPONSE; } - if(fromAPI){ - if (responseString!=null && !(duplicateResponseString).equals(responseString) && !VALIDATIONRESPONSE.equals(responseString)) { + if (fromAPI) { + if (responseString != null && !(duplicateResponseString).equals(responseString) + && !VALIDATIONRESPONSE.equals(responseString)) { responseString = successMsg; } ModelAndView result = new ModelAndView(); result.setViewName(responseString); return result; - }else{ + } else { utils.setResponseData(response, brmsParamDatas, responseString); } - }catch(Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/brms_dictionary/remove_brmsParam"}, method={RequestMethod.POST}) - public void removeBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response)throws IOException { + @RequestMapping(value = {"/brms_dictionary/remove_brmsParam"}, method = {RequestMethod.POST}) + public void removeBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, brmsParamDatas, BRMSParamTemplate.class); } - @RequestMapping(value={"/get_BRMSDependencyDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getBRMSDependencyDictionaryByNameEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_BRMSDependencyDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getBRMSDependencyDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, brmsDependencyDatas, dependencyName, BRMSDependency.class); } - - @RequestMapping(value={"/get_BRMSDependencyData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getBRMSDependencyDictionaryEntityData(HttpServletResponse response){ + + @RequestMapping(value = {"/get_BRMSDependencyData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getBRMSDependencyDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, brmsDependencyDatas, BRMSDependency.class); } - - @RequestMapping(value={"/brms_dictionary/save_BRMSDependencyData"}, method={RequestMethod.POST}) - public ModelAndView saveBRMSDependencyDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + + @RequestMapping(value = {"/brms_dictionary/save_BRMSDependencyData"}, + method = {RequestMethod.POST}) + public ModelAndView saveBRMSDependencyDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { LOGGER.debug("DictionaryController: saveBRMSDependencyDictionary() is called"); @@ -212,91 +226,109 @@ public class BRMSDictionaryController{ BRMSDependency brmsDependency; String userId = null; - if(fromAPI){ - brmsDependency = mapper.readValue(root.get(dictionaryFields).toString(), BRMSDependency.class); + if (fromAPI) { + brmsDependency = mapper.readValue(root.get(dictionaryFields).toString(), + BRMSDependency.class); userId = "API"; - }else{ - brmsDependency = mapper.readValue(root.get("brmsDependencyDictionaryData").toString(), BRMSDependency.class); + } else { + brmsDependency = mapper.readValue( + root.get("brmsDependencyDictionaryData").toString(), BRMSDependency.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(brmsDependency.getDependencyName(), dependencyName, BRMSDependency.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry( + brmsDependency.getDependencyName(), dependencyName, BRMSDependency.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { BRMSDependency data = (BRMSDependency) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { brmsDependency.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != brmsDependency.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != brmsDependency.getId()))) { duplicateflag = true; } } LOGGER.audit("the userId from the onap portal is: " + userId); String responseString = null; - if(brmsDependency.getDependency()!=null && !("").equals(brmsDependency.getDependency().trim())){ + if (brmsDependency.getDependency() != null + && !("").equals(brmsDependency.getDependency().trim())) { PEDependency dependency = null; - try{ - dependency = PolicyUtils.jsonStringToObject(brmsDependency.getDependency(), PEDependency.class); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + "wrong data given for BRMS PEDependency Dictionary : " + brmsDependency.getDependency(),e); + try { + dependency = PolicyUtils.jsonStringToObject(brmsDependency.getDependency(), + PEDependency.class); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + + "wrong data given for BRMS PEDependency Dictionary : " + + brmsDependency.getDependency(), e); } - if(dependency==null){ + if (dependency == null) { responseString = errorMessage; - }else{ - if(!duplicateflag){ + } else { + if (!duplicateflag) { brmsDependency.setUserModifiedBy(userInfo); - if(brmsDependency.getId() == 0){ + if (brmsDependency.getId() == 0) { brmsDependency.setUserCreatedBy(userInfo); commonClassDao.save(brmsDependency); - }else{ + } else { brmsDependency.setModifiedDate(new Date()); commonClassDao.update(brmsDependency); } - responseString = mapper.writeValueAsString(commonClassDao.getData(BRMSDependency.class)); - }else{ + responseString = mapper + .writeValueAsString(commonClassDao.getData(BRMSDependency.class)); + } else { responseString = duplicateResponseString; } } } - if(fromAPI){ - if(responseString!=null && !duplicateResponseString.equals(responseString) && !errorMessage.equals(responseString)){ + if (fromAPI) { + if (responseString != null && !duplicateResponseString.equals(responseString) + && !errorMessage.equals(responseString)) { responseString = successMsg; } ModelAndView result = new ModelAndView(); result.setViewName(responseString); return result; - }else{ + } else { utils.setResponseData(response, brmsDependencyDatas, responseString); } - } catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - - @RequestMapping(value={"/brms_dictionary/remove_brmsDependency"}, method={RequestMethod.POST}) - public void removeBRMSDependencyDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + + @RequestMapping(value = {"/brms_dictionary/remove_brmsDependency"}, + method = {RequestMethod.POST}) + public void removeBRMSDependencyDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, brmsDependencyDatas, BRMSDependency.class); } - - - @RequestMapping(value={"/get_BRMSControllerDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getBRMSControllerDictionaryByNameEntityData(HttpServletResponse response){ + + + @RequestMapping(value = {"/get_BRMSControllerDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getBRMSControllerDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, brmsControllerDatas, controllerName, BRMSController.class); } - - @RequestMapping(value={"/get_BRMSControllerData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getBRMSControllerDictionaryEntityData(HttpServletResponse response){ + + @RequestMapping(value = {"/get_BRMSControllerData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getBRMSControllerDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, brmsControllerDatas, BRMSController.class); } - - @RequestMapping(value={"/brms_dictionary/save_BRMSControllerData"}, method={RequestMethod.POST}) - public ModelAndView saveBRMSControllerDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + @RequestMapping(value = {"/brms_dictionary/save_BRMSControllerData"}, + method = {RequestMethod.POST}) + public ModelAndView saveBRMSControllerDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { LOGGER.debug("DictionaryController: saveBRMSControllerDictionary() is called"); @@ -306,79 +338,95 @@ public class BRMSDictionaryController{ JsonNode root = mapper.readTree(request.getReader()); BRMSController brmsController; String userId = null; - if(fromAPI){ - brmsController = mapper.readValue(root.get(dictionaryFields).toString(), BRMSController.class); + if (fromAPI) { + brmsController = mapper.readValue(root.get(dictionaryFields).toString(), + BRMSController.class); userId = "API"; - }else{ - brmsController = mapper.readValue(root.get("brmsControllerDictionaryData").toString(), BRMSController.class); + } else { + brmsController = mapper.readValue( + root.get("brmsControllerDictionaryData").toString(), BRMSController.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(brmsController.getControllerName(), controllerName, BRMSController.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry( + brmsController.getControllerName(), controllerName, BRMSController.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { BRMSController data = (BRMSController) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { brmsController.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != brmsController.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != brmsController.getId()))) { duplicateflag = true; } } String responseString = null; - if(brmsController.getController()!=null && !("").equals(brmsController.getController().trim())){ + if (brmsController.getController() != null + && !("").equals(brmsController.getController().trim())) { PEDependency dependency = null; - try{ - dependency = PolicyUtils.jsonStringToObject(brmsController.getController(), PEDependency.class); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + "wrong data given for BRMS Controller Dictionary : " + brmsController.getController(),e); + try { + dependency = PolicyUtils.jsonStringToObject(brmsController.getController(), + PEDependency.class); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + + "wrong data given for BRMS Controller Dictionary : " + + brmsController.getController(), e); } - if(dependency==null){ + if (dependency == null) { responseString = errorMessage; - }else{ - if(!duplicateflag){ + } else { + if (!duplicateflag) { brmsController.setUserModifiedBy(userInfo); - if(brmsController.getId() == 0){ + if (brmsController.getId() == 0) { brmsController.setUserCreatedBy(userInfo); commonClassDao.save(brmsController); - }else{ + } else { brmsController.setModifiedDate(new Date()); commonClassDao.update(brmsController); } - responseString = mapper.writeValueAsString(commonClassDao.getData(OnapName.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(OnapName.class)); + } else { responseString = duplicateResponseString; } } } - if(fromAPI){ - if (responseString!=null && !(duplicateResponseString).equals(responseString) && !(errorMessage).equals(responseString)) { + if (fromAPI) { + if (responseString != null && !(duplicateResponseString).equals(responseString) + && !(errorMessage).equals(responseString)) { responseString = successMsg; } ModelAndView result = new ModelAndView(); result.setViewName(responseString); return result; - }else{ + } else { utils.setResponseData(response, brmsControllerDatas, responseString); } - } catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - - @RequestMapping(value={"/brms_dictionary/remove_brmsController"}, method={RequestMethod.POST}) - public void removeBRMSControllerDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + + @RequestMapping(value = {"/brms_dictionary/remove_brmsController"}, + method = {RequestMethod.POST}) + public void removeBRMSControllerDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, brmsControllerDatas, BRMSController.class); } - - public BRMSDependency getDependencyDataByID(String dependencyName){ - return (BRMSDependency) commonClassDao.getEntityItem(BRMSDependency.class, BRMSDictionaryController.dependencyName, dependencyName); + + public BRMSDependency getDependencyDataByID(String dependencyName) { + return (BRMSDependency) commonClassDao.getEntityItem(BRMSDependency.class, + BRMSDictionaryController.dependencyName, dependencyName); + } + + public BRMSController getControllerDataByID(String controllerName) { + return (BRMSController) commonClassDao.getEntityItem(BRMSController.class, + BRMSDictionaryController.controllerName, controllerName); } - - public BRMSController getControllerDataByID(String controllerName){ - return (BRMSController) commonClassDao.getEntityItem(BRMSController.class, BRMSDictionaryController.controllerName, controllerName); - } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryController.java index 5e7113ad8..2aec0cc0d 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryController.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * 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. @@ -20,13 +20,14 @@ package org.onap.policy.pap.xacml.rest.controller; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.Date; import java.util.List; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.onap.policy.pap.xacml.rest.adapters.GridData; import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; @@ -46,12 +47,8 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - @Controller -public class ClosedLoopDictionaryController{ +public class ClosedLoopDictionaryController { private static CommonClassDao commonClassDao; private static String vsclaction = "vsclaction"; @@ -72,11 +69,11 @@ public class ClosedLoopDictionaryController{ private static String closedLoopSiteDatas = "closedLoopSiteDictionaryDatas"; @Autowired - public ClosedLoopDictionaryController(CommonClassDao commonClassDao){ + public ClosedLoopDictionaryController(CommonClassDao commonClassDao) { ClosedLoopDictionaryController.commonClassDao = commonClassDao; } - public void setCommonClassDao(CommonClassDao commonClassDao){ + public void setCommonClassDao(CommonClassDao commonClassDao) { ClosedLoopDictionaryController.commonClassDao = commonClassDao; } @@ -84,89 +81,102 @@ public class ClosedLoopDictionaryController{ commonClassDao = commonClassDaoImpl; } - public ClosedLoopDictionaryController(){ + public ClosedLoopDictionaryController() { super(); } - private DictionaryUtils getDictionaryUtilsInstance(){ + private DictionaryUtils getDictionaryUtilsInstance() { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value={"/get_VSCLActionDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getVSCLActionDictionaryByNameEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_VSCLActionDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getVSCLActionDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, vsclActionDatas, vsclaction, VSCLAction.class); } - @RequestMapping(value={"/get_VSCLActionData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getVSCLActionDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_VSCLActionData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getVSCLActionDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, vsclActionDatas, VSCLAction.class); } - @RequestMapping(value={"/get_VNFTypeDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getVNFTypeDictionaryByNameEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_VNFTypeDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getVNFTypeDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, vnfTypeDatas, vnftype, VNFType.class); } - @RequestMapping(value={"/get_VNFTypeData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getVNFTypeDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_VNFTypeData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getVNFTypeDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, vnfTypeDatas, VNFType.class); } - @RequestMapping(value={"/get_PEPOptionsDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPEPOptionsDictionaryByNameEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_PEPOptionsDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getPEPOptionsDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, pepOptionDatas, pepName, PEPOptions.class); } - @RequestMapping(value={"/get_PEPOptionsData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPEPOptionsDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_PEPOptionsData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getPEPOptionsDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, pepOptionDatas, PEPOptions.class); } - @RequestMapping(value={"/get_VarbindDictionaryDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getVarbindDictionaryByNameEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_VarbindDictionaryDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getVarbindDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, varbindDatas, varbindName, VarbindDictionary.class); } - @RequestMapping(value={"/get_VarbindDictionaryData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getVarbindDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_VarbindDictionaryData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getVarbindDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, varbindDatas, VarbindDictionary.class); } - @RequestMapping(value={"/get_ClosedLoopServicesDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getClosedLoopServiceDictionaryByNameEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_ClosedLoopServicesDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getClosedLoopServiceDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, closedLoopDatas, serviceName, ClosedLoopD2Services.class); } - @RequestMapping(value={"/get_ClosedLoopServicesData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getClosedLoopServiceDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_ClosedLoopServicesData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getClosedLoopServiceDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, closedLoopDatas, ClosedLoopD2Services.class); } - @RequestMapping(value={"/get_ClosedLoopSiteDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getClosedLoopSiteDictionaryByNameEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_ClosedLoopSiteDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getClosedLoopSiteDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, closedLoopSiteDatas, siteName, ClosedLoopSite.class); } - @RequestMapping(value={"/get_ClosedLoopSiteData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getClosedLoopSiteDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_ClosedLoopSiteData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getClosedLoopSiteDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, closedLoopSiteDatas, ClosedLoopSite.class); } - @RequestMapping(value={"/cl_dictionary/save_vsclAction"}, method={RequestMethod.POST}) - public ModelAndView saveVSCLAction(HttpServletRequest request, HttpServletResponse response)throws IOException{ + @RequestMapping(value = {"/cl_dictionary/save_vsclAction"}, method = {RequestMethod.POST}) + public ModelAndView saveVSCLAction(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -176,59 +186,68 @@ public class ClosedLoopDictionaryController{ VSCLAction vSCLAction; String userId = null; if (fromAPI) { - vSCLAction = mapper.readValue(root.get(dictionaryFields).toString(), VSCLAction.class); + vSCLAction = + mapper.readValue(root.get(dictionaryFields).toString(), VSCLAction.class); userId = "API"; } else { - vSCLAction = mapper.readValue(root.get("vsclActionDictionaryData").toString(), VSCLAction.class); + vSCLAction = mapper.readValue(root.get("vsclActionDictionaryData").toString(), + VSCLAction.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(vSCLAction.getVsclaction(), vsclaction, VSCLAction.class); + List<Object> duplicateData = commonClassDao + .checkDuplicateEntry(vSCLAction.getVsclaction(), vsclaction, VSCLAction.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { VSCLAction data = (VSCLAction) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { vSCLAction.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != vSCLAction.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != vSCLAction.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { vSCLAction.setUserModifiedBy(userInfo); - if(vSCLAction.getId() == 0){ + if (vSCLAction.getId() == 0) { vSCLAction.setUserCreatedBy(userInfo); commonClassDao.save(vSCLAction); - }else{ + } else { vSCLAction.setModifiedDate(new Date()); commonClassDao.update(vSCLAction); } - responseString = mapper.writeValueAsString(commonClassDao.getData(VSCLAction.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(VSCLAction.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, vsclActionDatas, responseString); } - }catch(Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/cl_dictionary/remove_VsclAction"}, method={RequestMethod.POST}) - public void removeVSCLAction(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/cl_dictionary/remove_VsclAction"}, method = {RequestMethod.POST}) + public void removeVSCLAction(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, vsclActionDatas, OnapName.class); } - @RequestMapping(value={"/cl_dictionary/save_vnfType"}, method={RequestMethod.POST}) - public ModelAndView saveVnfType(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/cl_dictionary/save_vnfType"}, method = {RequestMethod.POST}) + public ModelAndView saveVnfType(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -241,56 +260,63 @@ public class ClosedLoopDictionaryController{ vNFType = mapper.readValue(root.get(dictionaryFields).toString(), VNFType.class); userId = "API"; } else { - vNFType = mapper.readValue(root.get("vnfTypeDictionaryData").toString(), VNFType.class); + vNFType = mapper.readValue(root.get("vnfTypeDictionaryData").toString(), + VNFType.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(vNFType.getVnftype(), vnftype, VNFType.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(vNFType.getVnftype(), + vnftype, VNFType.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { VNFType data = (VNFType) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { vNFType.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != vNFType.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != vNFType.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { vNFType.setUserModifiedBy(userInfo); - if(vNFType.getId() == 0){ + if (vNFType.getId() == 0) { vNFType.setUserCreatedBy(userInfo); commonClassDao.save(vNFType); - }else{ + } else { vNFType.setModifiedDate(new Date()); commonClassDao.update(vNFType); } responseString = mapper.writeValueAsString(commonClassDao.getData(VNFType.class)); - }else{ + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, vnfTypeDatas, responseString); } - }catch(Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/cl_dictionary/remove_vnfType"}, method={RequestMethod.POST}) - public void removeVnfType(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/cl_dictionary/remove_vnfType"}, method = {RequestMethod.POST}) + public void removeVnfType(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, vnfTypeDatas, VNFType.class); } - @RequestMapping(value={"/cl_dictionary/save_pepOptions"}, method={RequestMethod.POST}) - public ModelAndView savePEPOptions(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/cl_dictionary/save_pepOptions"}, method = {RequestMethod.POST}) + public ModelAndView savePEPOptions(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -300,66 +326,76 @@ public class ClosedLoopDictionaryController{ PEPOptions pEPOptions; GridData gridData; String userId = null; - if(fromAPI){ - pEPOptions = mapper.readValue(root.get(dictionaryFields).toString(), PEPOptions.class); + if (fromAPI) { + pEPOptions = + mapper.readValue(root.get(dictionaryFields).toString(), PEPOptions.class); gridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); userId = "API"; - }else{ - pEPOptions = mapper.readValue(root.get("pepOptionsDictionaryData").toString(), PEPOptions.class); - gridData = mapper.readValue(root.get("pepOptionsDictionaryData").toString(), GridData.class); + } else { + pEPOptions = mapper.readValue(root.get("pepOptionsDictionaryData").toString(), + PEPOptions.class); + gridData = mapper.readValue(root.get("pepOptionsDictionaryData").toString(), + GridData.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - - if(!gridData.getAttributes().isEmpty()){ + + if (!gridData.getAttributes().isEmpty()) { pEPOptions.setActions(utils.appendKeyValue(gridData.getAttributes(), ":#@", "=#@")); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(pEPOptions.getPepName(), pepName, PEPOptions.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(pEPOptions.getPepName(), + pepName, PEPOptions.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { PEPOptions data = (PEPOptions) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { pEPOptions.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != pEPOptions.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != pEPOptions.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { pEPOptions.setUserModifiedBy(userInfo); - if(pEPOptions.getId() == 0){ + if (pEPOptions.getId() == 0) { pEPOptions.setUserCreatedBy(userInfo); commonClassDao.save(pEPOptions); - }else{ + } else { pEPOptions.setModifiedDate(new Date()); commonClassDao.update(pEPOptions); } - responseString = mapper.writeValueAsString(commonClassDao.getData(PEPOptions.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(PEPOptions.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, pepOptionDatas, responseString); } - }catch(Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/cl_dictionary/remove_pepOptions"}, method={RequestMethod.POST}) - public void removePEPOptions(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/cl_dictionary/remove_pepOptions"}, method = {RequestMethod.POST}) + public void removePEPOptions(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, pepOptionDatas, VNFType.class); } - @RequestMapping(value={"/cl_dictionary/save_service"}, method={RequestMethod.POST}) - public ModelAndView saveServiceType(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/cl_dictionary/save_service"}, method = {RequestMethod.POST}) + public ModelAndView saveServiceType(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -368,59 +404,69 @@ public class ClosedLoopDictionaryController{ JsonNode root = mapper.readTree(request.getReader()); ClosedLoopD2Services serviceData; String userId = null; - if(fromAPI){ - serviceData = mapper.readValue(root.get(dictionaryFields).toString(), ClosedLoopD2Services.class); + if (fromAPI) { + serviceData = mapper.readValue(root.get(dictionaryFields).toString(), + ClosedLoopD2Services.class); userId = "API"; } else { - serviceData = mapper.readValue(root.get("closedLoopServiceDictionaryData").toString(), ClosedLoopD2Services.class); + serviceData = + mapper.readValue(root.get("closedLoopServiceDictionaryData").toString(), + ClosedLoopD2Services.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(serviceData.getServiceName(), serviceName, ClosedLoopD2Services.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry( + serviceData.getServiceName(), serviceName, ClosedLoopD2Services.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { ClosedLoopD2Services data = (ClosedLoopD2Services) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { serviceData.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != serviceData.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != serviceData.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { serviceData.setUserModifiedBy(userInfo); - if(serviceData.getId() == 0){ + if (serviceData.getId() == 0) { serviceData.setUserCreatedBy(userInfo); commonClassDao.save(serviceData); - }else{ + } else { serviceData.setModifiedDate(new Date()); commonClassDao.update(serviceData); } - responseString = mapper.writeValueAsString(commonClassDao.getData(ClosedLoopD2Services.class)); - }else{ + responseString = mapper + .writeValueAsString(commonClassDao.getData(ClosedLoopD2Services.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, closedLoopDatas, responseString); } - }catch(Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/cl_dictionary/remove_Service"}, method={RequestMethod.POST}) - public void removeServiceType(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/cl_dictionary/remove_Service"}, method = {RequestMethod.POST}) + public void removeServiceType(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, closedLoopDatas, VNFType.class); } - @RequestMapping(value={"/cl_dictionary/save_siteName"}, method={RequestMethod.POST}) - public ModelAndView saveSiteType(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/cl_dictionary/save_siteName"}, method = {RequestMethod.POST}) + public ModelAndView saveSiteType(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -429,59 +475,68 @@ public class ClosedLoopDictionaryController{ JsonNode root = mapper.readTree(request.getReader()); ClosedLoopSite siteData; String userId = null; - if(fromAPI){ - siteData = mapper.readValue(root.get(dictionaryFields).toString(), ClosedLoopSite.class); + if (fromAPI) { + siteData = mapper.readValue(root.get(dictionaryFields).toString(), + ClosedLoopSite.class); userId = "API"; - }else{ - siteData = mapper.readValue(root.get("closedLoopSiteDictionaryData").toString(), ClosedLoopSite.class); + } else { + siteData = mapper.readValue(root.get("closedLoopSiteDictionaryData").toString(), + ClosedLoopSite.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(siteData.getSiteName(), siteName, ClosedLoopSite.class); + + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(siteData.getSiteName(), + siteName, ClosedLoopSite.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { ClosedLoopSite data = (ClosedLoopSite) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { siteData.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != siteData.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != siteData.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { siteData.setUserModifiedBy(userInfo); - if(siteData.getId() == 0){ + if (siteData.getId() == 0) { siteData.setUserCreatedBy(userInfo); commonClassDao.save(siteData); - }else{ + } else { siteData.setModifiedDate(new Date()); commonClassDao.update(siteData); } - responseString = mapper.writeValueAsString(commonClassDao.getData(ClosedLoopSite.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(ClosedLoopSite.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, closedLoopSiteDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/cl_dictionary/remove_site"}, method={RequestMethod.POST}) - public void removeSiteType(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/cl_dictionary/remove_site"}, method = {RequestMethod.POST}) + public void removeSiteType(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, closedLoopSiteDatas, VNFType.class); } - @RequestMapping(value={"/cl_dictionary/save_varbind"}, method={RequestMethod.POST}) - public ModelAndView saveVarbind(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/cl_dictionary/save_varbind"}, method = {RequestMethod.POST}) + public ModelAndView saveVarbind(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -490,55 +545,63 @@ public class ClosedLoopDictionaryController{ JsonNode root = mapper.readTree(request.getReader()); VarbindDictionary varbindDictionary; String userId = null; - if(fromAPI){ - varbindDictionary = mapper.readValue(root.get(dictionaryFields).toString(), VarbindDictionary.class); + if (fromAPI) { + varbindDictionary = mapper.readValue(root.get(dictionaryFields).toString(), + VarbindDictionary.class); userId = "API"; - }else{ - varbindDictionary = mapper.readValue(root.get("varbindDictionaryData").toString(), VarbindDictionary.class); + } else { + varbindDictionary = mapper.readValue(root.get("varbindDictionaryData").toString(), + VarbindDictionary.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(varbindDictionary.getVarbindName(), varbindName, VarbindDictionary.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry( + varbindDictionary.getVarbindName(), varbindName, VarbindDictionary.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { VarbindDictionary data = (VarbindDictionary) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { varbindDictionary.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != varbindDictionary.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != varbindDictionary.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { varbindDictionary.setUserModifiedBy(userInfo); - if(varbindDictionary.getId() == 0){ + if (varbindDictionary.getId() == 0) { varbindDictionary.setUserCreatedBy(userInfo); commonClassDao.save(varbindDictionary); - }else{ + } else { varbindDictionary.setModifiedDate(new Date()); commonClassDao.update(varbindDictionary); } - responseString = mapper.writeValueAsString(commonClassDao.getData(VarbindDictionary.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(VarbindDictionary.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, varbindDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/cl_dictionary/remove_varbindDict"}, method={RequestMethod.POST}) - public void removeVarbind(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/cl_dictionary/remove_varbindDict"}, method = {RequestMethod.POST}) + public void removeVarbind(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, varbindDatas, VNFType.class); } -}
\ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryController.java index 738a808f6..c89d21e91 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryController.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * 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. @@ -20,14 +20,15 @@ package org.onap.policy.pap.xacml.rest.controller; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.DecisionSettings; @@ -40,10 +41,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - @Controller public class DecisionPolicyDictionaryController { @@ -54,36 +51,40 @@ public class DecisionPolicyDictionaryController { private static String duplicateResponseString = "Duplicate"; private static String settingDatas = "settingsDictionaryDatas"; private static String rainDayDatas = "rainyDayDictionaryDatas"; - private static String dictionaryFields ="dictionaryFields"; + private static String dictionaryFields = "dictionaryFields"; @Autowired - public DecisionPolicyDictionaryController(CommonClassDao commonClassDao){ + public DecisionPolicyDictionaryController(CommonClassDao commonClassDao) { DecisionPolicyDictionaryController.commonClassDao = commonClassDao; } - public DecisionPolicyDictionaryController(){ + public DecisionPolicyDictionaryController() { super(); } - private DictionaryUtils getDictionaryUtilsInstance(){ + private DictionaryUtils getDictionaryUtilsInstance() { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value={"/get_SettingsDictionaryDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getSettingsDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ + @RequestMapping(value = {"/get_SettingsDictionaryDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getSettingsDictionaryByNameEntityData(HttpServletRequest request, + HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, settingDatas, xacmlId, DecisionSettings.class); } - @RequestMapping(value={"/get_SettingsDictionaryData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getSettingsDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_SettingsDictionaryData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getSettingsDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, settingDatas, DecisionSettings.class); } - @RequestMapping(value={"/decision_dictionary/save_Settings"}, method={RequestMethod.POST}) - public ModelAndView saveSettingsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/decision_dictionary/save_Settings"}, method = {RequestMethod.POST}) + public ModelAndView saveSettingsDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -93,74 +94,86 @@ public class DecisionPolicyDictionaryController { DecisionSettings decisionSettings; String userId = null; - if(fromAPI){ - decisionSettings = mapper.readValue(root.get(dictionaryFields).toString(), DecisionSettings.class); + if (fromAPI) { + decisionSettings = mapper.readValue(root.get(dictionaryFields).toString(), + DecisionSettings.class); userId = "API"; - }else{ - decisionSettings = mapper.readValue(root.get("settingsDictionaryData").toString(), DecisionSettings.class); + } else { + decisionSettings = mapper.readValue(root.get("settingsDictionaryData").toString(), + DecisionSettings.class); userId = root.get("userid").textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(decisionSettings.getXacmlId(), xacmlId, DecisionSettings.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry( + decisionSettings.getXacmlId(), xacmlId, DecisionSettings.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { DecisionSettings data = (DecisionSettings) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { decisionSettings.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != decisionSettings.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != decisionSettings.getId()))) { duplicateflag = true; } } - if(decisionSettings.getDatatypeBean().getShortName() != null){ + if (decisionSettings.getDatatypeBean().getShortName() != null) { String datatype = decisionSettings.getDatatypeBean().getShortName(); decisionSettings.setDatatypeBean(utils.getDataType(datatype)); } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { decisionSettings.setUserModifiedBy(userInfo); - if(decisionSettings.getId() == 0){ + if (decisionSettings.getId() == 0) { decisionSettings.setUserCreatedBy(userInfo); commonClassDao.save(decisionSettings); - }else{ + } else { decisionSettings.setModifiedDate(new Date()); commonClassDao.update(decisionSettings); } - responseString = mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, settingDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/settings_dictionary/remove_settings"}, method={RequestMethod.POST}) - public void removeSettingsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/settings_dictionary/remove_settings"}, method = {RequestMethod.POST}) + public void removeSettingsDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, settingDatas, DecisionSettings.class); } - @RequestMapping(value={"/get_RainyDayDictionaryDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getRainyDayDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ + @RequestMapping(value = {"/get_RainyDayDictionaryDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getRainyDayDictionaryByNameEntityData(HttpServletRequest request, + HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, rainDayDatas, bbID, RainyDayTreatments.class); } - @RequestMapping(value={"/get_RainyDayDictionaryData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getRainyDayDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_RainyDayDictionaryData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getRainyDayDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, rainDayDatas, RainyDayTreatments.class); } - @RequestMapping(value={"/decision_dictionary/save_RainyDay"}, method={RequestMethod.POST}) - public ModelAndView saveRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/decision_dictionary/save_RainyDay"}, method = {RequestMethod.POST}) + public ModelAndView saveRainyDayDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -169,57 +182,70 @@ public class DecisionPolicyDictionaryController { JsonNode root = mapper.readTree(request.getReader()); RainyDayTreatments decisionRainyDay; TreatmentValues treatmentsData = null; - if(fromAPI){ - decisionRainyDay = mapper.readValue(root.get(dictionaryFields).toString(), RainyDayTreatments.class); - treatmentsData = mapper.readValue(root.get(dictionaryFields).toString(), TreatmentValues.class); - }else{ - decisionRainyDay = mapper.readValue(root.get("rainyDayDictionaryData").toString(), RainyDayTreatments.class); - treatmentsData = mapper.readValue(root.get("rainyDayDictionaryData").toString(), TreatmentValues.class); + if (fromAPI) { + decisionRainyDay = mapper.readValue(root.get(dictionaryFields).toString(), + RainyDayTreatments.class); + treatmentsData = mapper.readValue(root.get(dictionaryFields).toString(), + TreatmentValues.class); + } else { + decisionRainyDay = mapper.readValue(root.get("rainyDayDictionaryData").toString(), + RainyDayTreatments.class); + treatmentsData = mapper.readValue(root.get("rainyDayDictionaryData").toString(), + TreatmentValues.class); } - decisionRainyDay.setTreatments(utils.appendKey(treatmentsData.getUserDataTypeValues(), "treatment", ",")); + decisionRainyDay.setTreatments( + utils.appendKey(treatmentsData.getUserDataTypeValues(), "treatment", ",")); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(decisionRainyDay.getBbid()+":"+decisionRainyDay.getWorkstep(), "bbid:workstep", RainyDayTreatments.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry( + decisionRainyDay.getBbid() + ":" + decisionRainyDay.getWorkstep(), + "bbid:workstep", RainyDayTreatments.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { RainyDayTreatments data = (RainyDayTreatments) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { decisionRainyDay.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != decisionRainyDay.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != decisionRainyDay.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(decisionRainyDay.getId() == 0){ + if (!duplicateflag) { + if (decisionRainyDay.getId() == 0) { commonClassDao.save(decisionRainyDay); - }else{ + } else { commonClassDao.update(decisionRainyDay); } - responseString = mapper.writeValueAsString(commonClassDao.getData(RainyDayTreatments.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(RainyDayTreatments.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, rainDayDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/decision_dictionary/remove_rainyDay"}, method={RequestMethod.POST}) - public void removeRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/decision_dictionary/remove_rainyDay"}, method = {RequestMethod.POST}) + public void removeRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, rainDayDatas, RainyDayTreatments.class); } } -class TreatmentValues { + +class TreatmentValues { private List<Object> userDataTypeValues = new ArrayList<>(); public List<Object> getUserDataTypeValues() { diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryController.java index a1d1bc8ff..51c8a1d91 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryController.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * 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. @@ -20,13 +20,14 @@ package org.onap.policy.pap.xacml.rest.controller; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.Date; import java.util.List; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.onap.policy.pap.xacml.rest.adapters.GridData; import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; @@ -39,10 +40,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - @Controller public class DescriptiveDictionaryController { @@ -52,36 +49,40 @@ public class DescriptiveDictionaryController { private static String descriptiveDatas = "descriptiveScopeDictionaryDatas"; @Autowired - public DescriptiveDictionaryController(CommonClassDao commonClassDao){ + public DescriptiveDictionaryController(CommonClassDao commonClassDao) { DescriptiveDictionaryController.commonClassDao = commonClassDao; } - public void setCommonClassDao(CommonClassDao commonClassDao){ + public void setCommonClassDao(CommonClassDao commonClassDao) { DescriptiveDictionaryController.commonClassDao = commonClassDao; } - public DescriptiveDictionaryController(){ + public DescriptiveDictionaryController() { super(); } - private DictionaryUtils getDictionaryUtilsInstance(){ + private DictionaryUtils getDictionaryUtilsInstance() { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value={"/get_DescriptiveScopeByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getDescriptiveDictionaryByNameEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_DescriptiveScopeByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getDescriptiveDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, descriptiveDatas, dScopeName, DescriptiveScope.class); } - @RequestMapping(value={"/get_DescriptiveScope"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getDescriptiveDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_DescriptiveScope"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getDescriptiveDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, descriptiveDatas, DescriptiveScope.class); } - @RequestMapping(value={"/descriptive_dictionary/save_descriptive"}, method={RequestMethod.POST}) - public ModelAndView saveDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response)throws IOException{ + @RequestMapping(value = {"/descriptive_dictionary/save_descriptive"}, + method = {RequestMethod.POST}) + public ModelAndView saveDescriptiveDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -91,56 +92,67 @@ public class DescriptiveDictionaryController { DescriptiveScope descriptiveScope; GridData data; String userId = null; - if(fromAPI){ - descriptiveScope = mapper.readValue(root.get("dictionaryFields").toString(), DescriptiveScope.class); + if (fromAPI) { + descriptiveScope = mapper.readValue(root.get("dictionaryFields").toString(), + DescriptiveScope.class); data = mapper.readValue(root.get("dictionaryFields").toString(), GridData.class); userId = "API"; - }else{ - descriptiveScope = mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), DescriptiveScope.class); - data = mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), GridData.class); + } else { + descriptiveScope = + mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), + DescriptiveScope.class); + data = mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), + GridData.class); userId = root.get("userid").textValue(); } descriptiveScope.setSearch(utils.appendKeyValue(data.getAttributes(), "AND", ":")); UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(descriptiveScope.getScopeName(), dScopeName, DescriptiveScope.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry( + descriptiveScope.getScopeName(), dScopeName, DescriptiveScope.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { DescriptiveScope data1 = (DescriptiveScope) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { descriptiveScope.setId(data1.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data1.getId() != descriptiveScope.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data1.getId() != descriptiveScope.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { descriptiveScope.setUserModifiedBy(userInfo); - if(descriptiveScope.getId() == 0){ + if (descriptiveScope.getId() == 0) { descriptiveScope.setUserCreatedBy(userInfo); commonClassDao.save(descriptiveScope); - }else{ + } else { descriptiveScope.setModifiedDate(new Date()); commonClassDao.update(descriptiveScope); } - responseString = mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.class)); + } else { responseString = "Duplicate"; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, descriptiveDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/descriptive_dictionary/remove_descriptiveScope"}, method={RequestMethod.POST}) - public void removeDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/descriptive_dictionary/remove_descriptiveScope"}, + method = {RequestMethod.POST}) + public void removeDescriptiveDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, descriptiveDatas, DescriptiveScope.class); } -}
\ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryController.java index 72539880c..94275e7c1 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryController.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * 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. @@ -20,13 +20,14 @@ package org.onap.policy.pap.xacml.rest.controller; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.Date; import java.util.List; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; @@ -41,52 +42,51 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - @Controller public class DictionaryController { - private static final Log LOGGER = LogFactory.getLog(DictionaryController.class); + private static final Log LOGGER = LogFactory.getLog(DictionaryController.class); private static CommonClassDao commonClassDao; private static String xacmlId = "xacmlId"; private static String operation = "operation"; - private static String dictionaryFields ="dictionaryFields"; + private static String dictionaryFields = "dictionaryFields"; private static String duplicateResponseString = "Duplicate"; private static String onapName = "onapName"; private static String attributeDatas = "attributeDictionaryDatas"; private static String onapNameDatas = "onapNameDictionaryDatas"; @Autowired - public DictionaryController(CommonClassDao commonClassDao){ + public DictionaryController(CommonClassDao commonClassDao) { DictionaryController.commonClassDao = commonClassDao; } - public DictionaryController(){ + public DictionaryController() { super(); } - private DictionaryUtils getDictionaryUtilsInstance(){ + private DictionaryUtils getDictionaryUtilsInstance() { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value={"/get_AttributeDatabyAttributeName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getAttributeDictionaryEntityDatabyAttributeName(HttpServletResponse response){ + @RequestMapping(value = {"/get_AttributeDatabyAttributeName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getAttributeDictionaryEntityDatabyAttributeName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, attributeDatas, xacmlId, Attribute.class); } - //Attribute Dictionary - @RequestMapping(value="/get_AttributeData", method= RequestMethod.GET , produces=MediaType.APPLICATION_JSON_VALUE) - public void getAttributeDictionaryEntityData(HttpServletResponse response){ + // Attribute Dictionary + @RequestMapping(value = "/get_AttributeData", method = RequestMethod.GET, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getAttributeDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, attributeDatas, Attribute.class); } - @RequestMapping(value={"/attribute_dictionary/save_attribute"}, method={RequestMethod.POST}) - public ModelAndView saveAttributeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/attribute_dictionary/save_attribute"}, method = {RequestMethod.POST}) + public ModelAndView saveAttributeDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -96,84 +96,99 @@ public class DictionaryController { Attribute attributeData = null; AttributeValues attributeValueData = null; String userId = null; - if(fromAPI){ - attributeData = mapper.readValue(root.get(dictionaryFields).toString(), Attribute.class); - attributeValueData = mapper.readValue(root.get(dictionaryFields).toString(), AttributeValues.class); + if (fromAPI) { + attributeData = + mapper.readValue(root.get(dictionaryFields).toString(), Attribute.class); + attributeValueData = mapper.readValue(root.get(dictionaryFields).toString(), + AttributeValues.class); userId = "API"; - }else{ - attributeData = mapper.readValue(root.get("attributeDictionaryData").toString(), Attribute.class); - attributeValueData = mapper.readValue(root.get("attributeDictionaryData").toString(), AttributeValues.class); + } else { + attributeData = mapper.readValue(root.get("attributeDictionaryData").toString(), + Attribute.class); + attributeValueData = mapper.readValue( + root.get("attributeDictionaryData").toString(), AttributeValues.class); userId = root.get("userid").textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(attributeData.getXacmlId(), xacmlId, Attribute.class); + List<Object> duplicateData = commonClassDao + .checkDuplicateEntry(attributeData.getXacmlId(), xacmlId, Attribute.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { Attribute data = (Attribute) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { attributeData.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != attributeData.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != attributeData.getId()))) { duplicateflag = true; } } - if(attributeValueData.getUserDataTypeValues() != null && !attributeValueData.getUserDataTypeValues().isEmpty()){ - attributeData.setAttributeValue(utils.appendKey(attributeValueData.getUserDataTypeValues(), "attributeValues", ",")); + if (attributeValueData.getUserDataTypeValues() != null + && !attributeValueData.getUserDataTypeValues().isEmpty()) { + attributeData.setAttributeValue(utils.appendKey( + attributeValueData.getUserDataTypeValues(), "attributeValues", ",")); } - if(attributeData.getDatatypeBean().getShortName() != null){ + if (attributeData.getDatatypeBean().getShortName() != null) { String datatype = attributeData.getDatatypeBean().getShortName(); attributeData.setDatatypeBean(utils.getDataType(datatype)); } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { attributeData.setUserModifiedBy(userInfo); - if(attributeData.getId() == 0){ + if (attributeData.getId() == 0) { attributeData.setCategoryBean(utils.getCategory()); attributeData.setUserCreatedBy(userInfo); commonClassDao.save(attributeData); - }else{ + } else { attributeData.setModifiedDate(new Date()); commonClassDao.update(attributeData); } responseString = mapper.writeValueAsString(commonClassDao.getData(Attribute.class)); - }else{ + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, attributeDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/attribute_dictionary/remove_attribute"}, method={RequestMethod.POST}) - public void removeAttributeDictionary(HttpServletRequest request, HttpServletResponse response)throws IOException { + @RequestMapping(value = {"/attribute_dictionary/remove_attribute"}, + method = {RequestMethod.POST}) + public void removeAttributeDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, attributeDatas, Attribute.class); } - //OnapName Dictionary - @RequestMapping(value={"/get_OnapNameDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getOnapNameDictionaryByNameEntityData(HttpServletResponse response){ + // OnapName Dictionary + @RequestMapping(value = {"/get_OnapNameDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getOnapNameDictionaryByNameEntityData(HttpServletResponse response) { LOGGER.info("get_OnapNameDataByName is called"); DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, onapNameDatas, onapName, OnapName.class); } - @RequestMapping(value={"/get_OnapNameData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getOnapNameDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_OnapNameData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getOnapNameDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, onapNameDatas, OnapName.class); } - @RequestMapping(value={"/onap_dictionary/save_onapName"}, method={RequestMethod.POST}) - public ModelAndView saveOnapDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/onap_dictionary/save_onapName"}, method = {RequestMethod.POST}) + public ModelAndView saveOnapDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -182,59 +197,66 @@ public class DictionaryController { JsonNode root = mapper.readTree(request.getReader()); OnapName onapData; String userId = null; - if(fromAPI){ + if (fromAPI) { onapData = mapper.readValue(root.get(dictionaryFields).toString(), OnapName.class); userId = "API"; - }else{ - onapData = mapper.readValue(root.get("onapNameDictionaryData").toString(), OnapName.class); + } else { + onapData = mapper.readValue(root.get("onapNameDictionaryData").toString(), + OnapName.class); userId = root.get("userid").textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getOnapName(), onapName, OnapName.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getOnapName(), + onapName, OnapName.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { OnapName data = (OnapName) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { onapData.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != onapData.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != onapData.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { onapData.setUserModifiedBy(userInfo); - if(onapData.getId() == 0){ + if (onapData.getId() == 0) { onapData.setUserCreatedBy(userInfo); commonClassDao.save(onapData); - }else{ + } else { onapData.setModifiedDate(new Date()); commonClassDao.update(onapData); } responseString = mapper.writeValueAsString(commonClassDao.getData(OnapName.class)); - }else{ + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, onapNameDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/onap_dictionary/remove_onap"}, method={RequestMethod.POST}) - public void removeOnapDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/onap_dictionary/remove_onap"}, method = {RequestMethod.POST}) + public void removeOnapDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, onapNameDatas, OnapName.class); } } -class AttributeValues{ + +class AttributeValues { private List<Object> userDataTypeValues; public List<Object> getUserDataTypeValues() { @@ -244,4 +266,4 @@ class AttributeValues{ public void setUserDataTypeValues(List<Object> userDataTypeValues) { this.userDataTypeValues = userDataTypeValues; } -}
\ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportController.java index 7093cd514..b42731d61 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportController.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * 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. @@ -20,16 +20,17 @@ package org.onap.policy.pap.xacml.rest.controller; +import au.com.bytecode.opencsv.CSVReader; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStream; import java.util.List; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.apache.commons.compress.utils.IOUtils; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; @@ -67,23 +68,18 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; - -import au.com.bytecode.opencsv.CSVReader; - @Controller public class DictionaryImportController { - private static final Logger LOGGER = FlexLogger.getLogger(DictionaryImportController.class); + private static final Logger LOGGER = FlexLogger.getLogger(DictionaryImportController.class); private static CommonClassDao commonClassDao; - private static final String DESCRIPTION= "description"; - private static final String ERROR= "Error"; - private static final String DEPENDENCY= "dependency"; + private static final String DESCRIPTION = "description"; + private static final String ERROR = "Error"; + private static final String DEPENDENCY = "dependency"; @Autowired - public DictionaryImportController(CommonClassDao commonClassDao){ + public DictionaryImportController(CommonClassDao commonClassDao) { setCommonClassDao(commonClassDao); } @@ -91,18 +87,19 @@ public class DictionaryImportController { DictionaryImportController.commonClassDao = commonClassDao; } - public DictionaryImportController(){ + public DictionaryImportController() { super(); } - @RequestMapping(value={"/dictionary/import_dictionary"}, method={RequestMethod.POST}) - public void importDictionaryData(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/dictionary/import_dictionary"}, method = {RequestMethod.POST}) + public void importDictionaryData(HttpServletRequest request, HttpServletResponse response) + throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); String userId = request.getParameter("userId"); String dictionaryName = request.getParameter("dictionaryName"); - if(dictionaryName == null || dictionaryName.isEmpty()){ + if (dictionaryName == null || dictionaryName.isEmpty()) { LOGGER.error("dictionaryName is null/empty"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().write(ERROR); @@ -110,46 +107,49 @@ public class DictionaryImportController { } // fix Fortify Path Manipulation issue - if(!isValidDictionaryName(dictionaryName)){ + if (!isValidDictionaryName(dictionaryName)) { LOGGER.error("dictionaryName is invalid"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().write(ERROR); return; } File file = new File(dictionaryName); - try(OutputStream outputStream = new FileOutputStream(file); FileReader fileReader = new FileReader(file.toString())){ + try (OutputStream outputStream = new FileOutputStream(file); + FileReader fileReader = new FileReader(file.toString())) { IOUtils.copy(request.getInputStream(), outputStream); CSVReader csvReader = new CSVReader(fileReader); List<String[]> dictSheet = csvReader.readAll(); - if(dictionaryName.startsWith("Attribute")){ - for(int i = 1; i< dictSheet.size(); i++){ + if (dictionaryName.startsWith("Attribute")) { + for (int i = 1; i < dictSheet.size(); i++) { Attribute attribute = new Attribute(""); UserInfo userinfo = new UserInfo(); userinfo.setUserLoginId(userId); attribute.setUserCreatedBy(userinfo); attribute.setUserModifiedBy(userinfo); String[] rows = dictSheet.get(i); - for (int j=0 ; j<rows.length; j++ ){ - if("xacml_id".equalsIgnoreCase(dictSheet.get(0)[j]) || "Attribute ID".equalsIgnoreCase(dictSheet.get(0)[j])){ + for (int j = 0; j < rows.length; j++) { + if ("xacml_id".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Attribute ID".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setXacmlId(rows[j]); } - if(DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])){ + if (DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDescription(rows[j]); } - if("priority".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("priority".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setPriority(rows[j]); } - if("datatype".equalsIgnoreCase(dictSheet.get(0)[j]) || "Data Type".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("datatype".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Data Type".equalsIgnoreCase(dictSheet.get(0)[j])) { Datatype dataType = new Datatype(); - if("string".equalsIgnoreCase(rows[j])){ + if ("string".equalsIgnoreCase(rows[j])) { dataType.setId(26); - }else if("integer".equalsIgnoreCase(rows[j])){ + } else if ("integer".equalsIgnoreCase(rows[j])) { dataType.setId(12); - }else if("double".equalsIgnoreCase(rows[j])){ + } else if ("double".equalsIgnoreCase(rows[j])) { dataType.setId(25); - }else if("boolean".equalsIgnoreCase(rows[j])){ + } else if ("boolean".equalsIgnoreCase(rows[j])) { dataType.setId(18); - }else if("user".equalsIgnoreCase(rows[j])){ + } else if ("user".equalsIgnoreCase(rows[j])) { dataType.setId(29); } attribute.setDatatypeBean(dataType); @@ -157,60 +157,63 @@ public class DictionaryImportController { category.setId(5); attribute.setCategoryBean(category); } - if("attribute_value".equalsIgnoreCase(dictSheet.get(0)[j]) || "Attribute Value".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("attribute_value".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Attribute Value".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setAttributeValue(rows[j]); } } commonClassDao.save(attribute); } } - if(dictionaryName.startsWith("ActionPolicyDictionary")){ - for(int i = 1; i< dictSheet.size(); i++){ + if (dictionaryName.startsWith("ActionPolicyDictionary")) { + for (int i = 1; i < dictSheet.size(); i++) { ActionPolicyDict attribute = new ActionPolicyDict(); UserInfo userinfo = new UserInfo(); userinfo.setUserLoginId(userId); attribute.setUserCreatedBy(userinfo); attribute.setUserModifiedBy(userinfo); String[] rows = dictSheet.get(i); - for (int j=0 ; j<rows.length; j++ ){ - if("attribute_name".equalsIgnoreCase(dictSheet.get(0)[j]) || "Attribute Name".equalsIgnoreCase(dictSheet.get(0)[j])){ + for (int j = 0; j < rows.length; j++) { + if ("attribute_name".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Attribute Name".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setAttributeName(rows[j]); } - if("body".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("body".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setBody(rows[j]); } - if(DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])){ + if (DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDescription(rows[j]); } - if("headers".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("headers".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setHeader(rows[j]); } - if("method".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("method".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setMethod(rows[j]); } - if("type".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("type".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setType(rows[j]); } - if("url".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("url".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setUrl(rows[j]); } } commonClassDao.save(attribute); } } - if(dictionaryName.startsWith("OnapName")){ - for(int i = 1; i< dictSheet.size(); i++){ + if (dictionaryName.startsWith("OnapName")) { + for (int i = 1; i < dictSheet.size(); i++) { OnapName attribute = new OnapName(); UserInfo userinfo = new UserInfo(); userinfo.setUserLoginId(userId); attribute.setUserCreatedBy(userinfo); attribute.setUserModifiedBy(userinfo); String[] rows = dictSheet.get(i); - for (int j=0 ; j<rows.length; j++ ){ - if("onap_name".equalsIgnoreCase(dictSheet.get(0)[j]) || "Onap Name".equalsIgnoreCase(dictSheet.get(0)[j])){ + for (int j = 0; j < rows.length; j++) { + if ("onap_name".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Onap Name".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setOnapName(rows[j]); } - if(DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])){ + if (DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDescription(rows[j]); } } @@ -218,39 +221,41 @@ public class DictionaryImportController { } } - if(dictionaryName.startsWith("MSPolicyDictionary")){ - for(int i = 1; i< dictSheet.size(); i++){ + if (dictionaryName.startsWith("MSPolicyDictionary")) { + for (int i = 1; i < dictSheet.size(); i++) { MicroServiceModels attribute = new MicroServiceModels(); UserInfo userinfo = new UserInfo(); userinfo.setUserLoginId(userId); attribute.setUserCreatedBy(userinfo); String[] rows = dictSheet.get(i); - for (int j=0 ; j<rows.length; j++ ){ - if("modelName".equalsIgnoreCase(dictSheet.get(0)[j]) || "Micro Service Model".equalsIgnoreCase(dictSheet.get(0)[j])){ + for (int j = 0; j < rows.length; j++) { + if ("modelName".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Micro Service Model".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setModelName(rows[j]); } - if("version".equalsIgnoreCase(dictSheet.get(0)[j]) || "Model Version".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("version".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Model Version".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setVersion(rows[j]); } - if(DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])){ + if (DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDescription(rows[j]); } - if(DEPENDENCY.equalsIgnoreCase(dictSheet.get(0)[j])){ + if (DEPENDENCY.equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDependency(rows[j]); } - if("attributes".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("attributes".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setAttributes(rows[j]); } - if("enumValues".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("enumValues".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setEnumValues(rows[j]); } - if("Ref Attributes".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("Ref Attributes".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setRef_attributes(rows[j]); } - if("Sub Attributes".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("Sub Attributes".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setSub_attributes(rows[j]); } - if("annotations".equalsIgnoreCase(dictSheet.get(0)[j])) { + if ("annotations".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setAnnotation(rows[j]); } } @@ -259,39 +264,42 @@ public class DictionaryImportController { } } - if(dictionaryName.startsWith("OptimizationPolicyDictionary")){ - for(int i = 1; i< dictSheet.size(); i++){ + if (dictionaryName.startsWith("OptimizationPolicyDictionary")) { + for (int i = 1; i < dictSheet.size(); i++) { MicroServiceModels attribute = new MicroServiceModels(); UserInfo userinfo = new UserInfo(); userinfo.setUserLoginId(userId); attribute.setUserCreatedBy(userinfo); String[] rows = dictSheet.get(i); - for (int j=0 ; j<rows.length; j++ ){ - if("modelName".equalsIgnoreCase(dictSheet.get(0)[j]) || "Optimization Service Model".equalsIgnoreCase(dictSheet.get(0)[j])){ + for (int j = 0; j < rows.length; j++) { + if ("modelName".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Optimization Service Model" + .equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setModelName(rows[j]); } - if("version".equalsIgnoreCase(dictSheet.get(0)[j]) || "Model Version".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("version".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Model Version".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setVersion(rows[j]); } - if(DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])){ + if (DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDescription(rows[j]); } - if(DEPENDENCY.equalsIgnoreCase(dictSheet.get(0)[j])){ + if (DEPENDENCY.equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDependency(rows[j]); } - if("attributes".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("attributes".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setAttributes(rows[j]); } - if("enumValues".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("enumValues".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setEnumValues(rows[j]); } - if("Ref Attributes".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("Ref Attributes".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setRef_attributes(rows[j]); } - if("Sub Attributes".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("Sub Attributes".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setSub_attributes(rows[j]); } - if("annotations".equalsIgnoreCase(dictSheet.get(0)[j])) { + if ("annotations".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setAnnotation(rows[j]); } } @@ -300,218 +308,231 @@ public class DictionaryImportController { } } - if(dictionaryName.startsWith("VNFType")){ - for(int i = 1; i< dictSheet.size(); i++){ + if (dictionaryName.startsWith("VNFType")) { + for (int i = 1; i < dictSheet.size(); i++) { VNFType attribute = new VNFType(); UserInfo userinfo = new UserInfo(); userinfo.setUserLoginId(userId); attribute.setUserCreatedBy(userinfo); attribute.setUserModifiedBy(userinfo); String[] rows = dictSheet.get(i); - for (int j=0 ; j<rows.length; j++ ){ - if("vnf_type".equalsIgnoreCase(dictSheet.get(0)[j]) || "VNF Type".equalsIgnoreCase(dictSheet.get(0)[j])){ + for (int j = 0; j < rows.length; j++) { + if ("vnf_type".equalsIgnoreCase(dictSheet.get(0)[j]) + || "VNF Type".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setVnftype(rows[j]); } - if(DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])){ + if (DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDescription(rows[j]); } } commonClassDao.save(attribute); } } - if(dictionaryName.startsWith("VSCLAction")){ - for(int i = 1; i< dictSheet.size(); i++){ + if (dictionaryName.startsWith("VSCLAction")) { + for (int i = 1; i < dictSheet.size(); i++) { VSCLAction attribute = new VSCLAction(); UserInfo userinfo = new UserInfo(); userinfo.setUserLoginId(userId); attribute.setUserCreatedBy(userinfo); attribute.setUserModifiedBy(userinfo); String[] rows = dictSheet.get(i); - for (int j=0 ; j<rows.length; j++ ){ - if("vscl_action".equalsIgnoreCase(dictSheet.get(0)[j]) || "VSCL Action".equalsIgnoreCase(dictSheet.get(0)[j])){ + for (int j = 0; j < rows.length; j++) { + if ("vscl_action".equalsIgnoreCase(dictSheet.get(0)[j]) + || "VSCL Action".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setVsclaction(rows[j]); } - if(DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])){ + if (DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDescription(rows[j]); } } commonClassDao.save(attribute); } } - if(dictionaryName.startsWith("ClosedLoopService")){ - for(int i = 1; i< dictSheet.size(); i++){ + if (dictionaryName.startsWith("ClosedLoopService")) { + for (int i = 1; i < dictSheet.size(); i++) { ClosedLoopD2Services attribute = new ClosedLoopD2Services(); UserInfo userinfo = new UserInfo(); userinfo.setUserLoginId(userId); attribute.setUserCreatedBy(userinfo); attribute.setUserModifiedBy(userinfo); String[] rows = dictSheet.get(i); - for (int j=0 ; j<rows.length; j++ ){ - if("serviceName".equalsIgnoreCase(dictSheet.get(0)[j]) || "Service Name".equalsIgnoreCase(dictSheet.get(0)[j])){ + for (int j = 0; j < rows.length; j++) { + if ("serviceName".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Service Name".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setServiceName(rows[j]); } - if(DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])){ + if (DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDescription(rows[j]); } } commonClassDao.save(attribute); } } - if(dictionaryName.startsWith("ClosedLoopSite")){ - for(int i = 1; i< dictSheet.size(); i++){ + if (dictionaryName.startsWith("ClosedLoopSite")) { + for (int i = 1; i < dictSheet.size(); i++) { ClosedLoopSite attribute = new ClosedLoopSite(); UserInfo userinfo = new UserInfo(); userinfo.setUserLoginId(userId); attribute.setUserCreatedBy(userinfo); attribute.setUserModifiedBy(userinfo); String[] rows = dictSheet.get(i); - for (int j=0 ; j<rows.length; j++ ){ - if("siteName".equalsIgnoreCase(dictSheet.get(0)[j]) || "Site Name".equalsIgnoreCase(dictSheet.get(0)[j])){ + for (int j = 0; j < rows.length; j++) { + if ("siteName".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Site Name".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setSiteName(rows[j]); } - if(DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])){ + if (DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDescription(rows[j]); } } commonClassDao.save(attribute); } } - if(dictionaryName.startsWith("PEPOptions")){ - for(int i = 1; i< dictSheet.size(); i++){ + if (dictionaryName.startsWith("PEPOptions")) { + for (int i = 1; i < dictSheet.size(); i++) { PEPOptions attribute = new PEPOptions(); UserInfo userinfo = new UserInfo(); userinfo.setUserLoginId(userId); attribute.setUserCreatedBy(userinfo); attribute.setUserModifiedBy(userinfo); String[] rows = dictSheet.get(i); - for (int j=0 ; j<rows.length; j++ ){ - if("PEP_NAME".equalsIgnoreCase(dictSheet.get(0)[j]) || "PEP Name".equalsIgnoreCase(dictSheet.get(0)[j])){ + for (int j = 0; j < rows.length; j++) { + if ("PEP_NAME".equalsIgnoreCase(dictSheet.get(0)[j]) + || "PEP Name".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setPepName(rows[j]); } - if(DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])){ + if (DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDescription(rows[j]); } - if("Actions".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("Actions".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setActions(rows[j]); } } commonClassDao.save(attribute); } } - if(dictionaryName.startsWith("VarbindDictionary")){ - for(int i = 1; i< dictSheet.size(); i++){ + if (dictionaryName.startsWith("VarbindDictionary")) { + for (int i = 1; i < dictSheet.size(); i++) { VarbindDictionary attribute = new VarbindDictionary(); UserInfo userinfo = new UserInfo(); userinfo.setUserLoginId(userId); attribute.setUserCreatedBy(userinfo); attribute.setUserModifiedBy(userinfo); String[] rows = dictSheet.get(i); - for (int j=0 ; j<rows.length; j++ ){ - if("varbind_Name".equalsIgnoreCase(dictSheet.get(0)[j]) || "Varbind Name".equalsIgnoreCase(dictSheet.get(0)[j])){ + for (int j = 0; j < rows.length; j++) { + if ("varbind_Name".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Varbind Name".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setVarbindName(rows[j]); } - if("varbind_Description".equalsIgnoreCase(dictSheet.get(0)[j]) || "Varbind Description".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("varbind_Description".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Varbind Description".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setVarbindDescription(rows[j]); } - if("varbind_oid".equalsIgnoreCase(dictSheet.get(0)[j]) || "Varbind OID".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("varbind_oid".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Varbind OID".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setVarbindOID(rows[j]); } } commonClassDao.save(attribute); } } - if(dictionaryName.startsWith("BRMSParamDictionary")){ - for(int i = 1; i< dictSheet.size(); i++){ + if (dictionaryName.startsWith("BRMSParamDictionary")) { + for (int i = 1; i < dictSheet.size(); i++) { BRMSParamTemplate attribute = new BRMSParamTemplate(); UserInfo userinfo = new UserInfo(); userinfo.setUserLoginId(userId); attribute.setUserCreatedBy(userinfo); String[] rows = dictSheet.get(i); - for (int j=0 ; j<rows.length; j++ ){ - if("param_template_name".equalsIgnoreCase(dictSheet.get(0)[j]) || "Rule Name".equalsIgnoreCase(dictSheet.get(0)[j])){ + for (int j = 0; j < rows.length; j++) { + if ("param_template_name".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Rule Name".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setRuleName(rows[j]); } - if(DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])){ + if (DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDescription(rows[j]); } - if("rule".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("rule".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setRule(rows[j]); } } commonClassDao.save(attribute); } } - if(dictionaryName.startsWith("BRMSControllerDictionary")){ - for(int i = 1; i< dictSheet.size(); i++){ + if (dictionaryName.startsWith("BRMSControllerDictionary")) { + for (int i = 1; i < dictSheet.size(); i++) { BRMSController attribute = new BRMSController(); UserInfo userinfo = new UserInfo(); userinfo.setUserLoginId(userId); attribute.setUserCreatedBy(userinfo); String[] rows = dictSheet.get(i); - for (int j=0 ; j<rows.length; j++ ){ - if("controllerName".equalsIgnoreCase(dictSheet.get(0)[j]) || "Controller Name".equalsIgnoreCase(dictSheet.get(0)[j])){ + for (int j = 0; j < rows.length; j++) { + if ("controllerName".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Controller Name".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setControllerName(rows[j]); } - if(DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])){ + if (DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDescription(rows[j]); } - if("controller".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("controller".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setController(rows[j]); } } commonClassDao.save(attribute); } } - if(dictionaryName.startsWith("BRMSDependencyDictionary")){ - for(int i = 1; i< dictSheet.size(); i++){ + if (dictionaryName.startsWith("BRMSDependencyDictionary")) { + for (int i = 1; i < dictSheet.size(); i++) { BRMSDependency attribute = new BRMSDependency(); UserInfo userinfo = new UserInfo(); userinfo.setUserLoginId(userId); attribute.setUserCreatedBy(userinfo); String[] rows = dictSheet.get(i); - for (int j=0 ; j<rows.length; j++ ){ - if("dependencyName".equalsIgnoreCase(dictSheet.get(0)[j]) || "Dependency Name".equalsIgnoreCase(dictSheet.get(0)[j])){ + for (int j = 0; j < rows.length; j++) { + if ("dependencyName".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Dependency Name".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDependencyName(rows[j]); } - if(DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])){ + if (DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDescription(rows[j]); } - if(DEPENDENCY.equalsIgnoreCase(dictSheet.get(0)[j])){ + if (DEPENDENCY.equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDependency(rows[j]); } } commonClassDao.save(attribute); } } - if(dictionaryName.startsWith("Settings")){ - for(int i = 1; i< dictSheet.size(); i++){ + if (dictionaryName.startsWith("Settings")) { + for (int i = 1; i < dictSheet.size(); i++) { DecisionSettings attribute = new DecisionSettings(); UserInfo userinfo = new UserInfo(); userinfo.setUserLoginId(userId); attribute.setUserCreatedBy(userinfo); attribute.setUserModifiedBy(userinfo); String[] rows = dictSheet.get(i); - for (int j=0 ; j<rows.length; j++ ){ - if("xacml_id".equalsIgnoreCase(dictSheet.get(0)[j]) || "Settings ID".equalsIgnoreCase(dictSheet.get(0)[j])){ + for (int j = 0; j < rows.length; j++) { + if ("xacml_id".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Settings ID".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setXacmlId(rows[j]); } - if(DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])){ + if (DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDescription(rows[j]); } - if("priority".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("priority".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setPriority(rows[j]); } - if("datatype".equalsIgnoreCase(dictSheet.get(0)[j]) || "Data Type".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("datatype".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Data Type".equalsIgnoreCase(dictSheet.get(0)[j])) { Datatype dataType = new Datatype(); - if("string".equalsIgnoreCase(rows[j])){ + if ("string".equalsIgnoreCase(rows[j])) { dataType.setId(26); - }else if("integer".equalsIgnoreCase(rows[j])){ + } else if ("integer".equalsIgnoreCase(rows[j])) { dataType.setId(12); - }else if("double".equalsIgnoreCase(rows[j])){ + } else if ("double".equalsIgnoreCase(rows[j])) { dataType.setId(25); - }else if("boolean".equalsIgnoreCase(rows[j])){ + } else if ("boolean".equalsIgnoreCase(rows[j])) { dataType.setId(18); - }else if("user".equalsIgnoreCase(rows[j])){ + } else if ("user".equalsIgnoreCase(rows[j])) { dataType.setId(29); } attribute.setDatatypeBean(dataType); @@ -520,200 +541,229 @@ public class DictionaryImportController { commonClassDao.save(attribute); } } - if(dictionaryName.startsWith("PrefixList")){ - for(int i = 1; i< dictSheet.size(); i++){ + if (dictionaryName.startsWith("PrefixList")) { + for (int i = 1; i < dictSheet.size(); i++) { PrefixList attribute = new PrefixList(); String[] rows = dictSheet.get(i); - for (int j=0 ; j<rows.length; j++ ){ - if("prefixListName".equalsIgnoreCase(dictSheet.get(0)[j]) || "PrefixList Name".equalsIgnoreCase(dictSheet.get(0)[j])){ + for (int j = 0; j < rows.length; j++) { + if ("prefixListName".equalsIgnoreCase(dictSheet.get(0)[j]) + || "PrefixList Name".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setPrefixListName(rows[j]); } - if(DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])){ + if (DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setPrefixListValue(rows[j]); } - if("prefixListValue".equalsIgnoreCase(dictSheet.get(0)[j]) || "PrefixList Value".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("prefixListValue".equalsIgnoreCase(dictSheet.get(0)[j]) + || "PrefixList Value".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDescription(rows[j]); } } commonClassDao.save(attribute); } } - if(dictionaryName.startsWith("SecurityZone")){ - for(int i = 1; i< dictSheet.size(); i++){ + if (dictionaryName.startsWith("SecurityZone")) { + for (int i = 1; i < dictSheet.size(); i++) { SecurityZone attribute = new SecurityZone(); String[] rows = dictSheet.get(i); - for (int j=0 ; j<rows.length; j++ ){ - if("zoneName".equalsIgnoreCase(dictSheet.get(0)[j]) || "Zone Name".equalsIgnoreCase(dictSheet.get(0)[j])){ + for (int j = 0; j < rows.length; j++) { + if ("zoneName".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Zone Name".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setZoneName(rows[j]); } - if("zoneValue".equalsIgnoreCase(dictSheet.get(0)[j]) || "Zone Value".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("zoneValue".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Zone Value".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setZoneValue(rows[j]); } } commonClassDao.save(attribute); } } - if(dictionaryName.startsWith("Zone")){ - for(int i = 1; i< dictSheet.size(); i++){ + if (dictionaryName.startsWith("Zone")) { + for (int i = 1; i < dictSheet.size(); i++) { Zone attribute = new Zone(); String[] rows = dictSheet.get(i); - for (int j=0 ; j<rows.length; j++ ){ - if("zoneName".equalsIgnoreCase(dictSheet.get(0)[j]) || "Zone Name".equalsIgnoreCase(dictSheet.get(0)[j])){ + for (int j = 0; j < rows.length; j++) { + if ("zoneName".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Zone Name".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setZoneName(rows[j]); } - if("zoneValue".equalsIgnoreCase(dictSheet.get(0)[j]) || "Zone Value".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("zoneValue".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Zone Value".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setZoneValue(rows[j]); } } commonClassDao.save(attribute); } } - if(dictionaryName.startsWith("ServiceList")){ - for(int i = 1; i< dictSheet.size(); i++){ + if (dictionaryName.startsWith("ServiceList")) { + for (int i = 1; i < dictSheet.size(); i++) { ServiceList attribute = new ServiceList(); String[] rows = dictSheet.get(i); - for (int j=0 ; j<rows.length; j++ ){ - if("serviceName".equalsIgnoreCase(dictSheet.get(0)[j]) || "Service Name".equalsIgnoreCase(dictSheet.get(0)[j])){ + for (int j = 0; j < rows.length; j++) { + if ("serviceName".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Service Name".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setServiceName(rows[j]); } - if("serviceDesc".equalsIgnoreCase(dictSheet.get(0)[j]) || DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("serviceDesc".equalsIgnoreCase(dictSheet.get(0)[j]) + || DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setServiceDescription(rows[j]); } - if("serviceType".equalsIgnoreCase(dictSheet.get(0)[j]) || "Service Type".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("serviceType".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Service Type".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setServiceType(rows[j]); } - if("serviceTrasProtocol".equalsIgnoreCase(dictSheet.get(0)[j]) || "Transport Protocol".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("serviceTrasProtocol".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Transport Protocol".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setServiceTransProtocol(rows[j]); } - if("serviceAppProtocol".equalsIgnoreCase(dictSheet.get(0)[j]) || "APP Protocol".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("serviceAppProtocol".equalsIgnoreCase(dictSheet.get(0)[j]) + || "APP Protocol".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setServiceAppProtocol(rows[j]); } - if("servicePorts".equalsIgnoreCase(dictSheet.get(0)[j]) || "Ports".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("servicePorts".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Ports".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setServicePorts(rows[j]); } } commonClassDao.save(attribute); } } - if(dictionaryName.startsWith("ServiceGroup")){ - for(int i = 1; i< dictSheet.size(); i++){ + if (dictionaryName.startsWith("ServiceGroup")) { + for (int i = 1; i < dictSheet.size(); i++) { GroupServiceList attribute = new GroupServiceList(); String[] rows = dictSheet.get(i); - for (int j=0 ; j<rows.length; j++ ){ - if("name".equalsIgnoreCase(dictSheet.get(0)[j]) || "Group Name".equalsIgnoreCase(dictSheet.get(0)[j])){ + for (int j = 0; j < rows.length; j++) { + if ("name".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Group Name".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setGroupName(rows[j]); } - if("serviceList".equalsIgnoreCase(dictSheet.get(0)[j]) || "Service List".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("serviceList".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Service List".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setServiceList(rows[j]); } } commonClassDao.save(attribute); } } - if(dictionaryName.startsWith("AddressGroup")){ - for(int i = 1; i< dictSheet.size(); i++){ + if (dictionaryName.startsWith("AddressGroup")) { + for (int i = 1; i < dictSheet.size(); i++) { AddressGroup attribute = new AddressGroup(); String[] rows = dictSheet.get(i); - for (int j=0 ; j<rows.length; j++ ){ - if("name".equalsIgnoreCase(dictSheet.get(0)[j]) || "Group Name".equalsIgnoreCase(dictSheet.get(0)[j])){ + for (int j = 0; j < rows.length; j++) { + if ("name".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Group Name".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setGroupName(rows[j]); } - if("serviceList".equalsIgnoreCase(dictSheet.get(0)[j]) || "Prefix List".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("serviceList".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Prefix List".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setServiceList(rows[j]); } - if(DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])){ + if (DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDescription(rows[j]); } } commonClassDao.save(attribute); } } - if(dictionaryName.startsWith("ProtocolList")){ - for(int i = 1; i< dictSheet.size(); i++){ + if (dictionaryName.startsWith("ProtocolList")) { + for (int i = 1; i < dictSheet.size(); i++) { ProtocolList attribute = new ProtocolList(); String[] rows = dictSheet.get(i); - for (int j=0 ; j<rows.length; j++ ){ - if("protocolName".equalsIgnoreCase(dictSheet.get(0)[j]) || "Protocol Name".equalsIgnoreCase(dictSheet.get(0)[j])){ + for (int j = 0; j < rows.length; j++) { + if ("protocolName".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Protocol Name".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setProtocolName(rows[j]); } - if(DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])){ + if (DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDescription(rows[j]); } } commonClassDao.save(attribute); } } - if(dictionaryName.startsWith("ActionList")){ - for(int i = 1; i< dictSheet.size(); i++){ + if (dictionaryName.startsWith("ActionList")) { + for (int i = 1; i < dictSheet.size(); i++) { ActionList attribute = new ActionList(); String[] rows = dictSheet.get(i); - for (int j=0 ; j<rows.length; j++ ){ - if("actionName".equalsIgnoreCase(dictSheet.get(0)[j]) || "Action Name".equalsIgnoreCase(dictSheet.get(0)[j])){ + for (int j = 0; j < rows.length; j++) { + if ("actionName".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Action Name".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setActionName(rows[j]); } - if(DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])){ + if (DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDescription(rows[j]); } } commonClassDao.save(attribute); } } - if(dictionaryName.startsWith("TermList")){ - for(int i = 1; i< dictSheet.size(); i++){ + if (dictionaryName.startsWith("TermList")) { + for (int i = 1; i < dictSheet.size(); i++) { TermList attribute = new TermList(); UserInfo userinfo = new UserInfo(); userinfo.setUserLoginId(userId); attribute.setUserCreatedBy(userinfo); attribute.setUserModifiedBy(userinfo); String[] rows = dictSheet.get(i); - for (int j=0 ; j<rows.length; j++ ){ - if("termName".equalsIgnoreCase(dictSheet.get(0)[j]) || "Term-Name".equalsIgnoreCase(dictSheet.get(0)[j])){ + for (int j = 0; j < rows.length; j++) { + if ("termName".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Term-Name".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setTermName(rows[j]); } - if("Term-Description".equalsIgnoreCase(dictSheet.get(0)[j]) || "termDescription".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("Term-Description".equalsIgnoreCase(dictSheet.get(0)[j]) + || "termDescription".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDescription(rows[j]); } - if("fromZone".equalsIgnoreCase(dictSheet.get(0)[j]) || "From Zone".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("fromZone".equalsIgnoreCase(dictSheet.get(0)[j]) + || "From Zone".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setFromZones(rows[j]); } - if("toZone".equalsIgnoreCase(dictSheet.get(0)[j]) || "To Zone".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("toZone".equalsIgnoreCase(dictSheet.get(0)[j]) + || "To Zone".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setToZones(rows[j]); } - if("srcIPList".equalsIgnoreCase(dictSheet.get(0)[j]) || "Source-IP-List".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("srcIPList".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Source-IP-List".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setSrcIPList(rows[j]); } - if("destIPList".equalsIgnoreCase(dictSheet.get(0)[j]) || "Destination-IP-List".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("destIPList".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Destination-IP-List".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDestIPList(rows[j]); } - if("srcPortList".equalsIgnoreCase(dictSheet.get(0)[j]) || "Source-Port-List".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("srcPortList".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Source-Port-List".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setSrcPortList(rows[j]); } - if("destPortList".equalsIgnoreCase(dictSheet.get(0)[j]) || "Destination-Port-List".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("destPortList".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Destination-Port-List".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDestPortList(rows[j]); } - if("action".equalsIgnoreCase(dictSheet.get(0)[j]) || "Action List".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("action".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Action List".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setAction(rows[j]); } } commonClassDao.save(attribute); } } - if(dictionaryName.startsWith("SearchCriteria")){ - for(int i = 1; i< dictSheet.size(); i++){ + if (dictionaryName.startsWith("SearchCriteria")) { + for (int i = 1; i < dictSheet.size(); i++) { DescriptiveScope attribute = new DescriptiveScope(); UserInfo userinfo = new UserInfo(); userinfo.setUserLoginId(userId); attribute.setUserCreatedBy(userinfo); attribute.setUserModifiedBy(userinfo); String[] rows = dictSheet.get(i); - for (int j=0 ; j<rows.length; j++ ){ - if("descriptiveScopeName".equalsIgnoreCase(dictSheet.get(0)[j]) || "Descriptive Scope Name".equalsIgnoreCase(dictSheet.get(0)[j])){ + for (int j = 0; j < rows.length; j++) { + if ("descriptiveScopeName".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Descriptive Scope Name".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setScopeName(rows[j]); } - if(DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])){ + if (DESCRIPTION.equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setDescription(rows[j]); } - if("search".equalsIgnoreCase(dictSheet.get(0)[j]) || "Search Criteria".equalsIgnoreCase(dictSheet.get(0)[j])){ + if ("search".equalsIgnoreCase(dictSheet.get(0)[j]) + || "Search Criteria".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setSearch(rows[j]); } } @@ -723,24 +773,24 @@ public class DictionaryImportController { csvReader.close(); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().write("Success"); - }catch(Exception e){ - LOGGER.error("Exception Occured while importing dictionary"+e); + } catch (Exception e) { + LOGGER.error("Exception Occured while importing dictionary" + e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.getWriter().write(ERROR); - }finally{ - if(file != null && file.exists()){ + } finally { + if (file != null && file.exists()) { boolean deleted = file.delete(); - LOGGER.error("Imported File has been deleted: "+deleted); + LOGGER.error("Imported File has been deleted: " + deleted); } } } - public boolean isValidDictionaryName(String dictionaryName){ + public boolean isValidDictionaryName(String dictionaryName) { String nameCheck = dictionaryName.replace(".csv", ""); - try{ + try { DictionaryNames mode = DictionaryNames.valueOf(nameCheck); - switch (mode){ + switch (mode) { case Attribute: case ActionPolicyDictionary: case OnapName: @@ -770,9 +820,9 @@ public class DictionaryImportController { default: return false; } - }catch(Exception e){ - LOGGER.error("Dictionary not exits: " +dictionaryName +e); + } catch (Exception e) { + LOGGER.error("Dictionary not exits: " + dictionaryName + e); return false; } } -}
\ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryController.java index 891787fa0..7cf12043c 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryController.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * 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. @@ -20,15 +20,16 @@ package org.onap.policy.pap.xacml.rest.controller; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.io.PrintWriter; import java.net.UnknownHostException; import java.util.Date; import java.util.List; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.jboss.netty.handler.ipfilter.CIDR; import org.json.JSONObject; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -57,29 +58,25 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - @Controller public class FirewallDictionaryController { - private static final Logger LOGGER = FlexLogger.getLogger(FirewallDictionaryController.class); + private static final Logger LOGGER = FlexLogger.getLogger(FirewallDictionaryController.class); private static CommonClassDao commonClassDao; private static String prefixListName = "prefixListName"; private static String successMessage = "success"; private static String operation = "operation"; - private static String errorMsg = "error"; - private static String dictionaryFields ="dictionaryFields"; + private static String errorMsg = "error"; + private static String dictionaryFields = "dictionaryFields"; private static String duplicateResponseString = "Duplicate"; private static String utf8 = "UTF-8"; private static String applicationJsonContentType = "application / json"; private static String protocolName = "protocolName"; private static String groupNameStart = "Group_"; private static String option = "option"; - private static String zoneName = "zoneName"; + private static String zoneName = "zoneName"; private static String serviceName = "serviceName"; private static String termName = "termName"; private static String userid = "userid"; @@ -100,36 +97,39 @@ public class FirewallDictionaryController { @Autowired - public FirewallDictionaryController(CommonClassDao commonClassDao){ + public FirewallDictionaryController(CommonClassDao commonClassDao) { FirewallDictionaryController.commonClassDao = commonClassDao; } - public static void setCommonClassDao(CommonClassDao clDao){ + public static void setCommonClassDao(CommonClassDao clDao) { commonClassDao = clDao; } - public FirewallDictionaryController(){ + public FirewallDictionaryController() { super(); } - private DictionaryUtils getDictionaryUtilsInstance(){ + private DictionaryUtils getDictionaryUtilsInstance() { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value={"/get_PrefixListDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPrefixListDictionaryEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_PrefixListDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getPrefixListDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, pfListDatas, prefixListName, PrefixList.class); } - @RequestMapping(value={"/get_PrefixListData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPrefixListDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_PrefixListData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getPrefixListDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, pfListDatas, PrefixList.class); } - @RequestMapping(value={"/fw_dictionary/save_prefixList"}, method={RequestMethod.POST}) - public ModelAndView savePrefixListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/save_prefixList"}, method = {RequestMethod.POST}) + public ModelAndView savePrefixListDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -138,62 +138,72 @@ public class FirewallDictionaryController { JsonNode root = mapper.readTree(request.getReader()); PrefixList prefixList; if (fromAPI) { - prefixList = mapper.readValue(root.get(dictionaryFields).toString(), PrefixList.class); + prefixList = + mapper.readValue(root.get(dictionaryFields).toString(), PrefixList.class); } else { - prefixList = mapper.readValue(root.get("prefixListDictionaryData").toString(), PrefixList.class); + prefixList = mapper.readValue(root.get("prefixListDictionaryData").toString(), + PrefixList.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(prefixList.getPrefixListName(), prefixListName, PrefixList.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry( + prefixList.getPrefixListName(), prefixListName, PrefixList.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { PrefixList data = (PrefixList) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { prefixList.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != prefixList.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != prefixList.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(prefixList.getId() == 0){ + if (!duplicateflag) { + if (prefixList.getId() == 0) { commonClassDao.save(prefixList); - }else{ + } else { commonClassDao.update(prefixList); } - responseString = mapper.writeValueAsString(commonClassDao.getData(PrefixList.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(PrefixList.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, pfListDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_PrefixList"}, method={RequestMethod.POST}) - public void removePrefixListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/remove_PrefixList"}, method = {RequestMethod.POST}) + public void removePrefixListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, pfListDatas, PrefixList.class); } - @RequestMapping(value={"/fw_dictionary/validate_prefixList"}, method={RequestMethod.POST}) - public void validatePrefixListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/validate_prefixList"}, method = {RequestMethod.POST}) + public void validatePrefixListDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); - PrefixList prefixList = mapper.readValue(root.get("prefixListDictionaryData").toString(), PrefixList.class); + PrefixList prefixList = mapper + .readValue(root.get("prefixListDictionaryData").toString(), PrefixList.class); String responseValidation = successMessage; - try{ + try { CIDR.newCIDR(prefixList.getPrefixListValue()); - }catch(UnknownHostException e){ + } catch (UnknownHostException e) { LOGGER.error(e); responseValidation = errorMsg; } @@ -204,20 +214,21 @@ public class FirewallDictionaryController { PrintWriter out = response.getWriter(); JSONObject j = new JSONObject("{result: " + responseValidation + "}"); out.write(j.toString()); - } - catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } } - @RequestMapping(value={"/get_PortListData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPortListDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_PortListData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getPortListDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, portListDatas, PortList.class); } - @RequestMapping(value={"/fw_dictionary/save_portName"}, method={RequestMethod.POST}) - public ModelAndView savePortListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/save_portName"}, method = {RequestMethod.POST}) + public ModelAndView savePortListDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -225,64 +236,73 @@ public class FirewallDictionaryController { mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); PortList portList; - if(fromAPI){ + if (fromAPI) { portList = mapper.readValue(root.get(dictionaryFields).toString(), PortList.class); - }else{ - portList = mapper.readValue(root.get("portListDictionaryData").toString(), PortList.class); + } else { + portList = mapper.readValue(root.get("portListDictionaryData").toString(), + PortList.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(portList.getPortName(), "portName", PortList.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(portList.getPortName(), + "portName", PortList.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { PortList data = (PortList) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { portList.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != portList.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != portList.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(portList.getId() == 0){ + if (!duplicateflag) { + if (portList.getId() == 0) { commonClassDao.save(portList); - }else{ + } else { commonClassDao.update(portList); } responseString = mapper.writeValueAsString(commonClassDao.getData(PortList.class)); - }else{ + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, portListDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_PortList"}, method={RequestMethod.POST}) - public void removePortListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/remove_PortList"}, method = {RequestMethod.POST}) + public void removePortListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, portListDatas, PortList.class); } - @RequestMapping(value={"/get_ProtocolListData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getProtocolListDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_ProtocolListData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getProtocolListDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, protocolListDatas, ProtocolList.class); } - @RequestMapping(value={"/get_ProtocolListDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getProtocolListDictionaryEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_ProtocolListDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getProtocolListDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, protocolListDatas, protocolName, ProtocolList.class); } - @RequestMapping(value={"/fw_dictionary/save_protocolList"}, method={RequestMethod.POST}) - public ModelAndView saveProtocolListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/save_protocolList"}, method = {RequestMethod.POST}) + public ModelAndView saveProtocolListDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -290,64 +310,75 @@ public class FirewallDictionaryController { mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); ProtocolList protocolList; - if(fromAPI){ - protocolList = mapper.readValue(root.get(dictionaryFields).toString(), ProtocolList.class); - }else{ - protocolList = mapper.readValue(root.get("protocolListDictionaryData").toString(), ProtocolList.class); + if (fromAPI) { + protocolList = + mapper.readValue(root.get(dictionaryFields).toString(), ProtocolList.class); + } else { + protocolList = mapper.readValue(root.get("protocolListDictionaryData").toString(), + ProtocolList.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(protocolList.getProtocolName(), protocolName, ProtocolList.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry( + protocolList.getProtocolName(), protocolName, ProtocolList.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { ProtocolList data = (ProtocolList) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { protocolList.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != protocolList.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != protocolList.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(protocolList.getId() == 0){ + if (!duplicateflag) { + if (protocolList.getId() == 0) { commonClassDao.save(protocolList); - }else{ + } else { commonClassDao.update(protocolList); } - responseString = mapper.writeValueAsString(commonClassDao.getData(ProtocolList.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(ProtocolList.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, protocolListDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_protocol"}, method={RequestMethod.POST}) - public void removeProtocolListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/remove_protocol"}, method = {RequestMethod.POST}) + public void removeProtocolListDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, protocolListDatas, ProtocolList.class); } - @RequestMapping(value={"/get_AddressGroupDictionaryDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getAddressGroupDictionaryEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_AddressGroupDictionaryDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getAddressGroupDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, addressGroupDatas, "name", AddressGroup.class); } - @RequestMapping(value={"/get_AddressGroupData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getAddressGroupDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_AddressGroupData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getAddressGroupDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, addressGroupDatas, AddressGroup.class); } - @RequestMapping(value={"/fw_dictionary/save_addressGroup"}, method={RequestMethod.POST}) - public ModelAndView saveAddressGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/save_addressGroup"}, method = {RequestMethod.POST}) + public ModelAndView saveAddressGroupDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -356,71 +387,83 @@ public class FirewallDictionaryController { JsonNode root = mapper.readTree(request.getReader()); AddressGroup addressGroup; GridData gridData; - if(fromAPI){ - addressGroup = mapper.readValue(root.get(dictionaryFields).toString(), AddressGroup.class); + if (fromAPI) { + addressGroup = + mapper.readValue(root.get(dictionaryFields).toString(), AddressGroup.class); gridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); - }else{ - addressGroup = mapper.readValue(root.get("addressGroupDictionaryData").toString(), AddressGroup.class); - gridData = mapper.readValue(root.get("addressGroupDictionaryData").toString(), GridData.class); + } else { + addressGroup = mapper.readValue(root.get("addressGroupDictionaryData").toString(), + AddressGroup.class); + gridData = mapper.readValue(root.get("addressGroupDictionaryData").toString(), + GridData.class); } - if(!addressGroup.getGroupName().startsWith(groupNameStart)){ - String groupName = groupNameStart+addressGroup.getGroupName(); + if (!addressGroup.getGroupName().startsWith(groupNameStart)) { + String groupName = groupNameStart + addressGroup.getGroupName(); addressGroup.setGroupName(groupName); } addressGroup.setServiceList(utils.appendKey(gridData.getAttributes(), option, ",")); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(addressGroup.getGroupName(), "name", AddressGroup.class); + List<Object> duplicateData = commonClassDao + .checkDuplicateEntry(addressGroup.getGroupName(), "name", AddressGroup.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { AddressGroup data = (AddressGroup) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { addressGroup.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != addressGroup.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != addressGroup.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(addressGroup.getId() == 0){ + if (!duplicateflag) { + if (addressGroup.getId() == 0) { commonClassDao.save(addressGroup); - }else{ + } else { commonClassDao.update(addressGroup); } - responseString = mapper.writeValueAsString(commonClassDao.getData(AddressGroup.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(AddressGroup.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, addressGroupDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_AddressGroup"}, method={RequestMethod.POST}) - public void removeAddressGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/remove_AddressGroup"}, method = {RequestMethod.POST}) + public void removeAddressGroupDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, addressGroupDatas, AddressGroup.class); } - @RequestMapping(value={"/get_ActionListDictionaryDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getActionListDictionaryEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_ActionListDictionaryDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getActionListDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, actionListDatas, "actionName", ActionList.class); } - @RequestMapping(value={"/get_ActionListData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getActionListDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_ActionListData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getActionListDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, actionListDatas, ActionList.class); } - @RequestMapping(value={"/fw_dictionary/save_ActionList"}, method={RequestMethod.POST}) - public ModelAndView saveActionListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/save_ActionList"}, method = {RequestMethod.POST}) + public ModelAndView saveActionListDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -429,63 +472,74 @@ public class FirewallDictionaryController { JsonNode root = mapper.readTree(request.getReader()); ActionList actionList; if (fromAPI) { - actionList = mapper.readValue(root.get(dictionaryFields).toString(), ActionList.class); + actionList = + mapper.readValue(root.get(dictionaryFields).toString(), ActionList.class); } else { - actionList = mapper.readValue(root.get("actionListDictionaryData").toString(), ActionList.class); + actionList = mapper.readValue(root.get("actionListDictionaryData").toString(), + ActionList.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(actionList.getActionName(), "actionName", ActionList.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry( + actionList.getActionName(), "actionName", ActionList.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { ActionList data = (ActionList) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { actionList.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != actionList.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != actionList.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(actionList.getId() == 0){ + if (!duplicateflag) { + if (actionList.getId() == 0) { commonClassDao.save(actionList); - }else{ + } else { commonClassDao.update(actionList); } - responseString = mapper.writeValueAsString(commonClassDao.getData(ActionList.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(ActionList.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, actionListDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_ActionList"}, method={RequestMethod.POST}) - public void removeActionListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/remove_ActionList"}, method = {RequestMethod.POST}) + public void removeActionListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, actionListDatas, ActionList.class); } - @RequestMapping(value={"/get_ServiceGroupData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getServiceGroupDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_ServiceGroupData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getServiceGroupDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, serviceGroupDatas, GroupServiceList.class); } - @RequestMapping(value={"/get_ServiceGroupDictionaryDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getServiceGroupDictionaryEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_ServiceGroupDictionaryDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getServiceGroupDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, serviceGroupDatas, "name", GroupServiceList.class); } - @RequestMapping(value={"/fw_dictionary/save_serviceGroup"}, method={RequestMethod.POST}) - public ModelAndView saveServiceGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/save_serviceGroup"}, method = {RequestMethod.POST}) + public ModelAndView saveServiceGroupDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -494,71 +548,83 @@ public class FirewallDictionaryController { JsonNode root = mapper.readTree(request.getReader()); GroupServiceList groupServiceList; GridData gridData; - if(fromAPI){ - groupServiceList = mapper.readValue(root.get(dictionaryFields).toString(), GroupServiceList.class); + if (fromAPI) { + groupServiceList = mapper.readValue(root.get(dictionaryFields).toString(), + GroupServiceList.class); gridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); - }else{ - groupServiceList = mapper.readValue(root.get("serviceGroupDictionaryData").toString(), GroupServiceList.class); - gridData = mapper.readValue(root.get("serviceGroupDictionaryData").toString(), GridData.class); + } else { + groupServiceList = mapper.readValue( + root.get("serviceGroupDictionaryData").toString(), GroupServiceList.class); + gridData = mapper.readValue(root.get("serviceGroupDictionaryData").toString(), + GridData.class); } - if(!groupServiceList.getGroupName().startsWith(groupNameStart)){ - String groupName = groupNameStart+groupServiceList.getGroupName(); + if (!groupServiceList.getGroupName().startsWith(groupNameStart)) { + String groupName = groupNameStart + groupServiceList.getGroupName(); groupServiceList.setGroupName(groupName); } groupServiceList.setServiceList(utils.appendKey(gridData.getAttributes(), option, ",")); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(groupServiceList.getGroupName(), "name", GroupServiceList.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry( + groupServiceList.getGroupName(), "name", GroupServiceList.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { GroupServiceList data = (GroupServiceList) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { groupServiceList.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != groupServiceList.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != groupServiceList.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(groupServiceList.getId() == 0){ + if (!duplicateflag) { + if (groupServiceList.getId() == 0) { commonClassDao.save(groupServiceList); - }else{ + } else { commonClassDao.update(groupServiceList); } - responseString = mapper.writeValueAsString(commonClassDao.getData(GroupServiceList.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(GroupServiceList.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, serviceGroupDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_serviceGroup"}, method={RequestMethod.POST}) - public void removeServiceGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/remove_serviceGroup"}, method = {RequestMethod.POST}) + public void removeServiceGroupDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, serviceGroupDatas, GroupServiceList.class); } - @RequestMapping(value={"/get_SecurityZoneDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getSecurityZoneDictionaryEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_SecurityZoneDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getSecurityZoneDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, securityZoneDatas, zoneName, SecurityZone.class); } - @RequestMapping(value={"/get_SecurityZoneData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getSecurityZoneDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_SecurityZoneData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getSecurityZoneDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, securityZoneDatas, SecurityZone.class); } - @RequestMapping(value={"/fw_dictionary/save_securityZone"}, method={RequestMethod.POST}) - public ModelAndView saveSecurityZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/save_securityZone"}, method = {RequestMethod.POST}) + public ModelAndView saveSecurityZoneDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -566,65 +632,76 @@ public class FirewallDictionaryController { mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); SecurityZone securityZone; - if(fromAPI){ - securityZone = mapper.readValue(root.get(dictionaryFields).toString(), SecurityZone.class); - }else{ - securityZone = mapper.readValue(root.get("securityZoneDictionaryData").toString(), SecurityZone.class); + if (fromAPI) { + securityZone = + mapper.readValue(root.get(dictionaryFields).toString(), SecurityZone.class); + } else { + securityZone = mapper.readValue(root.get("securityZoneDictionaryData").toString(), + SecurityZone.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(securityZone.getZoneName(), zoneName, SecurityZone.class); + List<Object> duplicateData = commonClassDao + .checkDuplicateEntry(securityZone.getZoneName(), zoneName, SecurityZone.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { SecurityZone data = (SecurityZone) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { securityZone.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != securityZone.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != securityZone.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(securityZone.getId() == 0){ + if (!duplicateflag) { + if (securityZone.getId() == 0) { commonClassDao.save(securityZone); - }else{ + } else { commonClassDao.update(securityZone); } - responseString = mapper.writeValueAsString(commonClassDao.getData(SecurityZone.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(SecurityZone.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, securityZoneDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_securityZone"}, method={RequestMethod.POST}) - public void removeSecurityZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/fw_dictionary/remove_securityZone"}, method = {RequestMethod.POST}) + public void removeSecurityZoneDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, securityZoneDatas, SecurityZone.class); } - @RequestMapping(value={"/get_ServiceListData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getServiceListDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_ServiceListData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getServiceListDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, serviceListDatas, ServiceList.class); } - @RequestMapping(value={"/get_ServiceListDictionaryDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getServiceListDictionaryEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_ServiceListDictionaryDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getServiceListDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, serviceListDatas, serviceName, ServiceList.class); } - @RequestMapping(value={"/fw_dictionary/save_serviceList"}, method={RequestMethod.POST}) - public ModelAndView saveServiceListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/save_serviceList"}, method = {RequestMethod.POST}) + public ModelAndView saveServiceListDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -633,69 +710,84 @@ public class FirewallDictionaryController { JsonNode root = mapper.readTree(request.getReader()); ServiceList serviceList; GridData serviceListGridData; - if(fromAPI){ - serviceList = mapper.readValue(root.get(dictionaryFields).toString(), ServiceList.class); - serviceListGridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); - }else{ - serviceList = mapper.readValue(root.get("serviceListDictionaryData").toString(), ServiceList.class); - serviceListGridData = mapper.readValue(root.get("serviceListDictionaryData").toString(), GridData.class); + if (fromAPI) { + serviceList = + mapper.readValue(root.get(dictionaryFields).toString(), ServiceList.class); + serviceListGridData = + mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); + } else { + serviceList = mapper.readValue(root.get("serviceListDictionaryData").toString(), + ServiceList.class); + serviceListGridData = mapper.readValue( + root.get("serviceListDictionaryData").toString(), GridData.class); } - serviceList.setServiceTransProtocol(utils.appendKey(serviceListGridData.getTransportProtocols(), option, ",")); - serviceList.setServiceAppProtocol(utils.appendKey(serviceListGridData.getAppProtocols(), option, ",")); + serviceList.setServiceTransProtocol( + utils.appendKey(serviceListGridData.getTransportProtocols(), option, ",")); + serviceList.setServiceAppProtocol( + utils.appendKey(serviceListGridData.getAppProtocols(), option, ",")); serviceList.setServiceType("SERVICE"); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(serviceList.getServiceName(), serviceName, ServiceList.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry( + serviceList.getServiceName(), serviceName, ServiceList.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { ServiceList data = (ServiceList) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { serviceList.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != serviceList.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != serviceList.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(serviceList.getId() == 0){ + if (!duplicateflag) { + if (serviceList.getId() == 0) { commonClassDao.save(serviceList); - }else{ + } else { commonClassDao.update(serviceList); } - responseString = mapper.writeValueAsString(commonClassDao.getData(ServiceList.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(ServiceList.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, serviceListDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_serviceList"}, method={RequestMethod.POST}) - public void removeServiceListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/fw_dictionary/remove_serviceList"}, method = {RequestMethod.POST}) + public void removeServiceListDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, serviceListDatas, ServiceList.class); } - @RequestMapping(value={"/get_ZoneData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getZoneDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_ZoneData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getZoneDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, zoneDatas, Zone.class); } - @RequestMapping(value={"/get_ZoneDictionaryDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getZoneDictionaryEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_ZoneDictionaryDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getZoneDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, zoneDatas, zoneName, Zone.class); } - @RequestMapping(value={"/fw_dictionary/save_zoneName"}, method={RequestMethod.POST}) - public ModelAndView saveZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/save_zoneName"}, method = {RequestMethod.POST}) + public ModelAndView saveZoneDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -708,59 +800,67 @@ public class FirewallDictionaryController { } else { zone = mapper.readValue(root.get("zoneDictionaryData").toString(), Zone.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(zone.getZoneName(), zoneName, Zone.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(zone.getZoneName(), zoneName, Zone.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { Zone data = (Zone) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { zone.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != zone.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != zone.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(zone.getId() == 0){ + if (!duplicateflag) { + if (zone.getId() == 0) { commonClassDao.save(zone); - }else{ + } else { commonClassDao.update(zone); } responseString = mapper.writeValueAsString(commonClassDao.getData(Zone.class)); - }else{ + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, zoneDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_zone"}, method={RequestMethod.POST}) - public void removeZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/remove_zone"}, method = {RequestMethod.POST}) + public void removeZoneDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, zoneDatas, Zone.class); } - @RequestMapping(value={"/get_TermListDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getTermListDictionaryEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_TermListDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getTermListDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, termListDictDatas, termName, TermList.class); } - @RequestMapping(value={"/get_TermListData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getTermListDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_TermListData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getTermListDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, termListDictDatas, TermList.class); } - @RequestMapping(value={"/fw_dictionary/save_termList"}, method={RequestMethod.POST}) - public ModelAndView saveTermListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/save_termList"}, method = {RequestMethod.POST}) + public ModelAndView saveTermListDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -770,82 +870,97 @@ public class FirewallDictionaryController { TermList termList; TermListData termListDatas; String userId = null; - if(fromAPI){ + if (fromAPI) { termList = mapper.readValue(root.get(dictionaryFields).toString(), TermList.class); - termListDatas = mapper.readValue(root.get(dictionaryFields).toString(), TermListData.class); + termListDatas = + mapper.readValue(root.get(dictionaryFields).toString(), TermListData.class); userId = "API"; - }else{ - termList = mapper.readValue(root.get("termListDictionaryData").toString(), TermList.class); - termListDatas = mapper.readValue(root.get("termListDictionaryData").toString(), TermListData.class); + } else { + termList = mapper.readValue(root.get("termListDictionaryData").toString(), + TermList.class); + termListDatas = mapper.readValue(root.get("termListDictionaryData").toString(), + TermListData.class); userId = root.get(userid).textValue(); } termList.setFromZones(utils.appendKey(termListDatas.getFromZoneDatas(), option, ",")); termList.setToZones(utils.appendKey(termListDatas.getToZoneDatas(), option, ",")); termList.setSrcIPList(utils.appendKey(termListDatas.getSourceListDatas(), option, ",")); - termList.setDestIPList(utils.appendKey(termListDatas.getDestinationListDatas(), option, ",")); - termList.setSrcPortList(utils.appendKey(termListDatas.getSourceServiceDatas(), option, ",")); - termList.setDestPortList(utils.appendKey(termListDatas.getDestinationServiceDatas(), option, ",")); + termList.setDestIPList( + utils.appendKey(termListDatas.getDestinationListDatas(), option, ",")); + termList.setSrcPortList( + utils.appendKey(termListDatas.getSourceServiceDatas(), option, ",")); + termList.setDestPortList( + utils.appendKey(termListDatas.getDestinationServiceDatas(), option, ",")); termList.setAction(utils.appendKey(termListDatas.getActionListDatas(), option, ",")); UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(termList.getTermName(), termName, TermList.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(termList.getTermName(), + termName, TermList.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { TermList data = (TermList) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { termList.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != termList.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != termList.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { termList.setUserModifiedBy(userInfo); - if(termList.getId() == 0){ + if (termList.getId() == 0) { termList.setUserCreatedBy(userInfo); commonClassDao.save(termList); - }else{ + } else { termList.setModifiedDate(new Date()); commonClassDao.update(termList); } responseString = mapper.writeValueAsString(commonClassDao.getData(TermList.class)); - }else{ + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, termListDictDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_termList"}, method={RequestMethod.POST}) - public void removeTermListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/remove_termList"}, method = {RequestMethod.POST}) + public void removeTermListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, termListDictDatas, TermList.class); } - //ParentList Dictionary Data - @RequestMapping(value={"/get_FWDictionaryListDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getFWDictListDictionaryEntityDataByName(HttpServletResponse response){ + // ParentList Dictionary Data + @RequestMapping(value = {"/get_FWDictionaryListDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getFWDictListDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.getDataByEntity(response, fwDictListDatas, "parentItemName", FirewallDictionaryList.class); + utils.getDataByEntity(response, fwDictListDatas, "parentItemName", + FirewallDictionaryList.class); } - @RequestMapping(value={"/get_FWDictionaryListData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getFWDictionaryListEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_FWDictionaryListData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getFWDictionaryListEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, fwDictListDatas, FirewallDictionaryList.class); } - @RequestMapping(value={"/fw_dictionary/save_FWDictionaryList"}, method={RequestMethod.POST}) - public ModelAndView saveFWDictionaryList(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/save_FWDictionaryList"}, method = {RequestMethod.POST}) + public ModelAndView saveFWDictionaryList(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -855,71 +970,83 @@ public class FirewallDictionaryController { FirewallDictionaryList fwDictList; GridData gridData; if (fromAPI) { - fwDictList = mapper.readValue(root.get(dictionaryFields).toString(), FirewallDictionaryList.class); + fwDictList = mapper.readValue(root.get(dictionaryFields).toString(), + FirewallDictionaryList.class); gridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); } else { - fwDictList = mapper.readValue(root.get("fwDictListDictionaryData").toString(), FirewallDictionaryList.class); - gridData = mapper.readValue(root.get("fwDictListDictionaryData").toString(), GridData.class); + fwDictList = mapper.readValue(root.get("fwDictListDictionaryData").toString(), + FirewallDictionaryList.class); + gridData = mapper.readValue(root.get("fwDictListDictionaryData").toString(), + GridData.class); } fwDictList.setServiceList(utils.appendKey(gridData.getAttributes(), option, ",")); fwDictList.setAddressList(utils.appendKey(gridData.getAlAttributes(), option, ",")); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(fwDictList.getParentItemName(), "parentItemName", FirewallDictionaryList.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry( + fwDictList.getParentItemName(), "parentItemName", FirewallDictionaryList.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { FirewallDictionaryList data = (FirewallDictionaryList) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { fwDictList.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != fwDictList.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != fwDictList.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(fwDictList.getId() == 0){ + if (!duplicateflag) { + if (fwDictList.getId() == 0) { commonClassDao.save(fwDictList); - }else{ + } else { commonClassDao.update(fwDictList); } - responseString = mapper.writeValueAsString(commonClassDao.getData(FirewallDictionaryList.class)); - }else{ + responseString = mapper + .writeValueAsString(commonClassDao.getData(FirewallDictionaryList.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, fwDictListDatas, responseString); } - } - catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_FWDictionaryList"}, method={RequestMethod.POST}) - public void removeFWDictionaryList(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/fw_dictionary/remove_FWDictionaryList"}, + method = {RequestMethod.POST}) + public void removeFWDictionaryList(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, fwDictListDatas, FirewallDictionaryList.class); } - @RequestMapping(value={"/get_TagPickerNameByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getTagPickerNameEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_TagPickerNameByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getTagPickerNameEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, fwTagPickerDatas, tagPickerName, FWTagPicker.class); } - @RequestMapping(value={"/get_TagPickerListData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getTagPickerDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_TagPickerListData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getTagPickerDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, fwTagPickerDatas, FWTagPicker.class); } - @RequestMapping(value={"/fw_dictionary/save_fwTagPicker"}, method={RequestMethod.POST}) - public ModelAndView saveFirewallTagPickerDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/save_fwTagPicker"}, method = {RequestMethod.POST}) + public ModelAndView saveFirewallTagPickerDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -930,76 +1057,87 @@ public class FirewallDictionaryController { TagGridValues data; String userId = ""; if (fromAPI) { - fwTagPicker = mapper.readValue(root.get(dictionaryFields).toString(), FWTagPicker.class); + fwTagPicker = + mapper.readValue(root.get(dictionaryFields).toString(), FWTagPicker.class); data = mapper.readValue(root.get(dictionaryFields).toString(), TagGridValues.class); userId = "API"; } else { - fwTagPicker = mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), FWTagPicker.class); - data = mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), TagGridValues.class); + fwTagPicker = mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), + FWTagPicker.class); + data = mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), + TagGridValues.class); userId = root.get(userid).textValue(); } fwTagPicker.setTagValues(utils.appendKeyValue(data.getTags(), "#", ":")); UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(fwTagPicker.getTagPickerName(), tagPickerName, FWTagPicker.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry( + fwTagPicker.getTagPickerName(), tagPickerName, FWTagPicker.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { FWTagPicker data1 = (FWTagPicker) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { fwTagPicker.setId(data1.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data1.getId() != fwTagPicker.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data1.getId() != fwTagPicker.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { fwTagPicker.setUserModifiedBy(userInfo); - if(fwTagPicker.getId() == 0){ + if (fwTagPicker.getId() == 0) { fwTagPicker.setUserCreatedBy(userInfo); commonClassDao.save(fwTagPicker); - }else{ + } else { fwTagPicker.setModifiedDate(new Date()); commonClassDao.update(fwTagPicker); } - responseString = mapper.writeValueAsString(commonClassDao.getData(FWTagPicker.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(FWTagPicker.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, fwTagPickerDatas, responseString); } - } - catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_tagPicker"}, method={RequestMethod.POST}) - public void removeFirewallTagPickerDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/fw_dictionary/remove_tagPicker"}, method = {RequestMethod.POST}) + public void removeFirewallTagPickerDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, fwTagPickerDatas, FWTagPicker.class); } - @RequestMapping(value={"/get_TagListData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getTagDictionaryEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_TagListData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getTagDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, fwTagDatas, FWTag.class); } - @RequestMapping(value={"/get_TagNameByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getTagNameEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_TagNameByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getTagNameEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, fwTagDatas, "fwTagName", FWTag.class); } - @RequestMapping(value={"/fw_dictionary/save_fwTag"}, method={RequestMethod.POST}) - public ModelAndView saveFirewallTagDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/save_fwTag"}, method = {RequestMethod.POST}) + public ModelAndView saveFirewallTagDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -1008,64 +1146,71 @@ public class FirewallDictionaryController { JsonNode root = mapper.readTree(request.getReader()); FWTag fwTag; TagGridValues tagGridValues; - String userId=""; - if(fromAPI){ + String userId = ""; + if (fromAPI) { fwTag = mapper.readValue(root.get(dictionaryFields).toString(), FWTag.class); - tagGridValues = mapper.readValue(root.get(dictionaryFields).toString(), TagGridValues.class); + tagGridValues = mapper.readValue(root.get(dictionaryFields).toString(), + TagGridValues.class); userId = "API"; - }else{ + } else { fwTag = mapper.readValue(root.get("fwTagDictionaryData").toString(), FWTag.class); - tagGridValues = mapper.readValue(root.get("fwTagDictionaryData").toString(), TagGridValues.class); + tagGridValues = mapper.readValue(root.get("fwTagDictionaryData").toString(), + TagGridValues.class); userId = root.get(userid).textValue(); } fwTag.setTagValues(utils.appendKey(tagGridValues.getTags(), "tags", ",")); UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(fwTag.getFwTagName(), "fwTagName", FWTag.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(fwTag.getFwTagName(), + "fwTagName", FWTag.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { FWTag data = (FWTag) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { fwTag.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != fwTag.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != fwTag.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { fwTag.setUserModifiedBy(userInfo); - if(fwTag.getId() == 0){ + if (fwTag.getId() == 0) { fwTag.setUserCreatedBy(userInfo); commonClassDao.save(fwTag); - }else{ + } else { fwTag.setModifiedDate(new Date()); commonClassDao.update(fwTag); } responseString = mapper.writeValueAsString(commonClassDao.getData(FWTag.class)); - }else{ + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, fwTagDatas, responseString); } - } - catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/fw_dictionary/remove_tagList"}, method={RequestMethod.POST}) - public void removeFirewallTagDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/fw_dictionary/remove_tagList"}, method = {RequestMethod.POST}) + public void removeFirewallTagDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, fwTagDatas, FWTag.class); } } -class TagGridValues{ + +class TagGridValues { private List<Object> tags; public List<Object> getTags() { @@ -1077,7 +1222,8 @@ class TagGridValues{ } } -class AGGridData{ + +class AGGridData { private List<Object> attributes; public List<Object> getAttributes() { @@ -1089,7 +1235,8 @@ class AGGridData{ } } -class TermListData{ + +class TermListData { private List<Object> fromZoneDatas; private List<Object> toZoneDatas; private List<Object> sourceListDatas; @@ -1097,46 +1244,60 @@ class TermListData{ private List<Object> sourceServiceDatas; private List<Object> destinationServiceDatas; private List<Object> actionListDatas; + public List<Object> getFromZoneDatas() { return fromZoneDatas; } + public void setFromZoneDatas(List<Object> fromZoneDatas) { this.fromZoneDatas = fromZoneDatas; } + public List<Object> getToZoneDatas() { return toZoneDatas; } + public void setToZoneDatas(List<Object> toZoneDatas) { this.toZoneDatas = toZoneDatas; } + public List<Object> getSourceListDatas() { return sourceListDatas; } + public void setSourceListDatas(List<Object> sourceListDatas) { this.sourceListDatas = sourceListDatas; } + public List<Object> getDestinationListDatas() { return destinationListDatas; } + public void setDestinationListDatas(List<Object> destinationListDatas) { this.destinationListDatas = destinationListDatas; } + public List<Object> getSourceServiceDatas() { return sourceServiceDatas; } + public void setSourceServiceDatas(List<Object> sourceServiceDatas) { this.sourceServiceDatas = sourceServiceDatas; } + public List<Object> getDestinationServiceDatas() { return destinationServiceDatas; } + public void setDestinationServiceDatas(List<Object> destinationServiceDatas) { this.destinationServiceDatas = destinationServiceDatas; } + public List<Object> getActionListDatas() { return actionListDatas; } + public void setActionListDatas(List<Object> actionListDatas) { this.actionListDatas = actionListDatas; } -}
\ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryController.java index 965235cce..c0e7729db 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryController.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * 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. @@ -20,13 +20,14 @@ package org.onap.policy.pap.xacml.rest.controller; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.ArrayList; import java.util.List; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.apache.commons.lang.StringUtils; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; @@ -45,19 +46,16 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - @Controller public class PolicyScopeDictionaryController { - private static final Logger LOGGER = FlexLogger.getLogger(PolicyScopeDictionaryController.class); + private static final Logger LOGGER = + FlexLogger.getLogger(PolicyScopeDictionaryController.class); private static CommonClassDao commonClassDao; private static String operation = "operation"; private static String groupPolicyScopeListData1 = "groupPolicyScopeListData1"; - private static String policyScope= "PolicyScope"; + private static String policyScope = "PolicyScope"; private static String duplicateResponseString = "Duplicate"; private static String groupPolicyScopeDatas = "groupPolicyScopeListDatas"; private static String dictionaryFields = "dictionaryFields"; @@ -66,37 +64,41 @@ public class PolicyScopeDictionaryController { private static String psTypeDatas = "psTypeDictionaryDatas"; private static String psResourceDatas = "psResourceDictionaryDatas"; - public PolicyScopeDictionaryController(){ + public PolicyScopeDictionaryController() { super(); } - private DictionaryUtils getDictionaryUtilsInstance(){ + private DictionaryUtils getDictionaryUtilsInstance() { return DictionaryUtils.getDictionaryUtils(); } @Autowired - public PolicyScopeDictionaryController(CommonClassDao commonClassDao){ + public PolicyScopeDictionaryController(CommonClassDao commonClassDao) { PolicyScopeDictionaryController.commonClassDao = commonClassDao; } - public void setCommonClassDao(CommonClassDao commonClassDao){ + public void setCommonClassDao(CommonClassDao commonClassDao) { PolicyScopeDictionaryController.commonClassDao = commonClassDao; } - @RequestMapping(value={"/get_GroupPolicyScopeDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getGroupPolicyScopeEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_GroupPolicyScopeDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getGroupPolicyScopeEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, groupPolicyScopeDatas, "name", GroupPolicyScopeList.class); } - @RequestMapping(value={"/get_GroupPolicyScopeData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getGroupPolicyScopeEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_GroupPolicyScopeData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getGroupPolicyScopeEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, groupPolicyScopeDatas, GroupPolicyScopeList.class); } - @RequestMapping(value={"/ps_dictionary/save_psGroupPolicyScope"}, method={RequestMethod.POST}) - public ModelAndView savePSGroupScopeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/ps_dictionary/save_psGroupPolicyScope"}, + method = {RequestMethod.POST}) + public ModelAndView savePSGroupScopeDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -107,31 +109,43 @@ public class PolicyScopeDictionaryController { GroupPolicyScope groupData = null; boolean duplicateGroupFlag = false; if (fromAPI) { - gpdata = mapper.readValue(root.get(dictionaryFields).toString(), GroupPolicyScopeList.class); - try{ - groupData = mapper.readValue(root.get(groupPolicyScopeListData1).toString(), GroupPolicyScope.class); - }catch(Exception e){ + gpdata = mapper.readValue(root.get(dictionaryFields).toString(), + GroupPolicyScopeList.class); + try { + groupData = mapper.readValue(root.get(groupPolicyScopeListData1).toString(), + GroupPolicyScope.class); + } catch (Exception e) { groupData = new GroupPolicyScope(); - groupData.setResource(root.get(dictionaryFields).get("resource").toString().replace("\"", "")); - groupData.setClosedloop(root.get(dictionaryFields).get("closedloop").toString().replace("\"", "")); - groupData.setService(root.get(dictionaryFields).get("service").toString().replace("\"", "")); - groupData.setType(root.get(dictionaryFields).get("type").toString().replace("\"", "")); + groupData.setResource(root.get(dictionaryFields).get("resource").toString() + .replace("\"", "")); + groupData.setClosedloop(root.get(dictionaryFields).get("closedloop").toString() + .replace("\"", "")); + groupData.setService( + root.get(dictionaryFields).get("service").toString().replace("\"", "")); + groupData.setType( + root.get(dictionaryFields).get("type").toString().replace("\"", "")); LOGGER.error(e); } } else { - gpdata = mapper.readValue(root.get("groupPolicyScopeListData").toString(), GroupPolicyScopeList.class); - try{ - groupData = mapper.readValue(root.get(groupPolicyScopeListData1).toString(), GroupPolicyScope.class); - }catch(Exception e){ + gpdata = mapper.readValue(root.get("groupPolicyScopeListData").toString(), + GroupPolicyScopeList.class); + try { + groupData = mapper.readValue(root.get(groupPolicyScopeListData1).toString(), + GroupPolicyScope.class); + } catch (Exception e) { LOGGER.error(e); groupData = new GroupPolicyScope(); - groupData.setResource(root.get(groupPolicyScopeListData1).get("resource").toString().replace("\"", "")); - groupData.setClosedloop(root.get(groupPolicyScopeListData1).get("closedloop").toString().replace("\"", "")); - groupData.setService(root.get(groupPolicyScopeListData1).get("service").toString().replace("\"", "")); - groupData.setType(root.get(groupPolicyScopeListData1).get("type").toString().replace("\"", "")); + groupData.setResource(root.get(groupPolicyScopeListData1).get("resource") + .toString().replace("\"", "")); + groupData.setClosedloop(root.get(groupPolicyScopeListData1).get("closedloop") + .toString().replace("\"", "")); + groupData.setService(root.get(groupPolicyScopeListData1).get("service") + .toString().replace("\"", "")); + groupData.setType(root.get(groupPolicyScopeListData1).get("type").toString() + .replace("\"", "")); } } - if(!gpdata.getGroupName().startsWith(policyScope)){ + if (!gpdata.getGroupName().startsWith(policyScope)) { String name = "PolicyScope_" + gpdata.getGroupName(); gpdata.setGroupName(name); } @@ -143,71 +157,83 @@ public class PolicyScopeDictionaryController { valueList.add("resource=" + resourceValue); valueList.add("service=" + serviceValue); valueList.add("type=" + typeValue); - valueList.add("closedLoopControlName=" + closedLoopValue); - String list = StringUtils.replaceEach(valueList.toString(), new String[]{"[", "]", " "}, new String[]{"", "", ""}); + valueList.add("closedLoopControlName=" + closedLoopValue); + String list = StringUtils.replaceEach(valueList.toString(), + new String[] {"[", "]", " "}, new String[] {"", "", ""}); gpdata.setGroupList(list); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(gpdata.getGroupName(), "name", GroupPolicyScopeList.class); - if(duplicateData.isEmpty()){ - duplicateData = commonClassDao.checkDuplicateEntry(gpdata.getGroupList(), "groupList", GroupPolicyScopeList.class); - if(duplicateData.isEmpty()){ + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(gpdata.getGroupName(), + "name", GroupPolicyScopeList.class); + if (duplicateData.isEmpty()) { + duplicateData = commonClassDao.checkDuplicateEntry(gpdata.getGroupList(), + "groupList", GroupPolicyScopeList.class); + if (duplicateData.isEmpty()) { duplicateGroupFlag = true; } } boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { GroupPolicyScopeList data = (GroupPolicyScopeList) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { gpdata.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != gpdata.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != gpdata.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag && !duplicateGroupFlag){ - if(gpdata.getId() == 0){ + if (!duplicateflag && !duplicateGroupFlag) { + if (gpdata.getId() == 0) { commonClassDao.save(gpdata); - }else{ + } else { commonClassDao.update(gpdata); } - responseString = mapper.writeValueAsString(commonClassDao.getData(GroupPolicyScopeList.class)); - }else if(duplicateGroupFlag){ + responseString = mapper + .writeValueAsString(commonClassDao.getData(GroupPolicyScopeList.class)); + } else if (duplicateGroupFlag) { responseString = "DuplicateGroup"; - }else{ + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, groupPolicyScopeDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/ps_dictionary/remove_GroupPolicyScope"}, method={RequestMethod.POST}) - public void removePSGroupScopeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/ps_dictionary/remove_GroupPolicyScope"}, + method = {RequestMethod.POST}) + public void removePSGroupScopeDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, groupPolicyScopeDatas, GroupPolicyScopeList.class); } - @RequestMapping(value={"/get_PSClosedLoopDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPSClosedLoopEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_PSClosedLoopDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getPSClosedLoopEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, psCLDatas, "name", OnapName.class); } - @RequestMapping(value={"/get_PSClosedLoopData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPSClosedLoopEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_PSClosedLoopData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getPSClosedLoopEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, psCLDatas, PolicyScopeClosedLoop.class); } - @RequestMapping(value={"/ps_dictionary/save_psClosedLoop"}, method={RequestMethod.POST}) - public ModelAndView savePSClosedLoopDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/ps_dictionary/save_psClosedLoop"}, method = {RequestMethod.POST}) + public ModelAndView savePSClosedLoopDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -215,65 +241,76 @@ public class PolicyScopeDictionaryController { mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); PolicyScopeClosedLoop onapData; - if(fromAPI){ - onapData = mapper.readValue(root.get(dictionaryFields).toString(), PolicyScopeClosedLoop.class); - }else{ - onapData = mapper.readValue(root.get("psClosedLoopDictionaryData").toString(), PolicyScopeClosedLoop.class); + if (fromAPI) { + onapData = mapper.readValue(root.get(dictionaryFields).toString(), + PolicyScopeClosedLoop.class); + } else { + onapData = mapper.readValue(root.get("psClosedLoopDictionaryData").toString(), + PolicyScopeClosedLoop.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeClosedLoop.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), + "name", PolicyScopeClosedLoop.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { PolicyScopeClosedLoop data = (PolicyScopeClosedLoop) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { onapData.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != onapData.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != onapData.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(onapData.getId() == 0){ + if (!duplicateflag) { + if (onapData.getId() == 0) { commonClassDao.save(onapData); - }else{ + } else { commonClassDao.update(onapData); } - responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeClosedLoop.class)); - }else{ + responseString = mapper + .writeValueAsString(commonClassDao.getData(PolicyScopeClosedLoop.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, psCLDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/ps_dictionary/remove_PSClosedLoop"}, method={RequestMethod.POST}) - public void removePSClosedLoopDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/ps_dictionary/remove_PSClosedLoop"}, method = {RequestMethod.POST}) + public void removePSClosedLoopDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, psCLDatas, PolicyScopeClosedLoop.class); } - @RequestMapping(value={"/get_PSServiceDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPSServiceEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_PSServiceDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getPSServiceEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, psServiceDatas, "name", PolicyScopeService.class); } - @RequestMapping(value={"/get_PSServiceData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPSServiceEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_PSServiceData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getPSServiceEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, psServiceDatas, PolicyScopeService.class); } - @RequestMapping(value={"/ps_dictionary/save_psService"}, method={RequestMethod.POST}) - public ModelAndView savePSServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/ps_dictionary/save_psService"}, method = {RequestMethod.POST}) + public ModelAndView savePSServiceDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -282,64 +319,75 @@ public class PolicyScopeDictionaryController { JsonNode root = mapper.readTree(request.getReader()); PolicyScopeService onapData; if (fromAPI) { - onapData = mapper.readValue(root.get(dictionaryFields).toString(), PolicyScopeService.class); + onapData = mapper.readValue(root.get(dictionaryFields).toString(), + PolicyScopeService.class); } else { - onapData = mapper.readValue(root.get("psServiceDictionaryData").toString(), PolicyScopeService.class); + onapData = mapper.readValue(root.get("psServiceDictionaryData").toString(), + PolicyScopeService.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeService.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), + "name", PolicyScopeService.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { PolicyScopeService data = (PolicyScopeService) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { onapData.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != onapData.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != onapData.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(onapData.getId() == 0){ + if (!duplicateflag) { + if (onapData.getId() == 0) { commonClassDao.save(onapData); - }else{ + } else { commonClassDao.update(onapData); } - responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeService.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(PolicyScopeService.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, psServiceDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/ps_dictionary/remove_PSService"}, method={RequestMethod.POST}) - public void removePSServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/ps_dictionary/remove_PSService"}, method = {RequestMethod.POST}) + public void removePSServiceDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, psServiceDatas, PolicyScopeService.class); } - @RequestMapping(value={"/get_PSTypeDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPSTypeEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_PSTypeDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getPSTypeEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, psTypeDatas, "name", PolicyScopeType.class); } - @RequestMapping(value={"/get_PSTypeData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPSTypeEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_PSTypeData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getPSTypeEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, psTypeDatas, PolicyScopeType.class); } - @RequestMapping(value={"/ps_dictionary/save_psType"}, method={RequestMethod.POST}) - public ModelAndView savePSTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/ps_dictionary/save_psType"}, method = {RequestMethod.POST}) + public ModelAndView savePSTypeDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -347,65 +395,76 @@ public class PolicyScopeDictionaryController { mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); PolicyScopeType onapData; - if(fromAPI){ - onapData = mapper.readValue(root.get(dictionaryFields).toString(), PolicyScopeType.class); - }else{ - onapData = mapper.readValue(root.get("psTypeDictionaryData").toString(), PolicyScopeType.class); + if (fromAPI) { + onapData = mapper.readValue(root.get(dictionaryFields).toString(), + PolicyScopeType.class); + } else { + onapData = mapper.readValue(root.get("psTypeDictionaryData").toString(), + PolicyScopeType.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeType.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), + "name", PolicyScopeType.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { PolicyScopeType data = (PolicyScopeType) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { onapData.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != onapData.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != onapData.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(onapData.getId() == 0){ + if (!duplicateflag) { + if (onapData.getId() == 0) { commonClassDao.save(onapData); - }else{ + } else { commonClassDao.update(onapData); } - responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeType.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(PolicyScopeType.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, psTypeDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/ps_dictionary/remove_PSType"}, method={RequestMethod.POST}) - public void removePSTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/ps_dictionary/remove_PSType"}, method = {RequestMethod.POST}) + public void removePSTypeDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, psTypeDatas, PolicyScopeType.class); } - @RequestMapping(value={"/get_PSResourceDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPSResourceEntityDataByName(HttpServletResponse response){ + @RequestMapping(value = {"/get_PSResourceDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getPSResourceEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, psResourceDatas, "name", PolicyScopeResource.class); } - @RequestMapping(value={"/get_PSResourceData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPSResourceEntityData(HttpServletResponse response){ + @RequestMapping(value = {"/get_PSResourceData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getPSResourceEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, psResourceDatas, PolicyScopeResource.class); } - @RequestMapping(value={"/ps_dictionary/save_psResource"}, method={RequestMethod.POST}) - public ModelAndView savePSResourceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/ps_dictionary/save_psResource"}, method = {RequestMethod.POST}) + public ModelAndView savePSResourceDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -414,77 +473,94 @@ public class PolicyScopeDictionaryController { JsonNode root = mapper.readTree(request.getReader()); PolicyScopeResource onapData; if (fromAPI) { - onapData = mapper.readValue(root.get(dictionaryFields).toString(), PolicyScopeResource.class); + onapData = mapper.readValue(root.get(dictionaryFields).toString(), + PolicyScopeResource.class); } else { - onapData = mapper.readValue(root.get("psResourceDictionaryData").toString(), PolicyScopeResource.class); + onapData = mapper.readValue(root.get("psResourceDictionaryData").toString(), + PolicyScopeResource.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeResource.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), + "name", PolicyScopeResource.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { PolicyScopeResource data = (PolicyScopeResource) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { onapData.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != onapData.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != onapData.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(onapData.getId() == 0){ + if (!duplicateflag) { + if (onapData.getId() == 0) { commonClassDao.save(onapData); - }else{ + } else { commonClassDao.update(onapData); } - responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeResource.class)); - }else{ + responseString = mapper + .writeValueAsString(commonClassDao.getData(PolicyScopeResource.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, psResourceDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/ps_dictionary/remove_PSResource"}, method={RequestMethod.POST}) - public void removePSResourceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/ps_dictionary/remove_PSResource"}, method = {RequestMethod.POST}) + public void removePSResourceDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, psResourceDatas, PolicyScopeResource.class); } } -class GroupPolicyScope{ + +class GroupPolicyScope { String resource; String type; String service; String closedloop; + public String getResource() { return resource; } + public void setResource(String resource) { this.resource = resource; } + public String getType() { return type; } + public void setType(String type) { this.type = type; } + public String getService() { return service; } + public void setService(String service) { this.service = service; } + public String getClosedloop() { return closedloop; } + public void setClosedloop(String closedloop) { this.closedloop = closedloop; } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyController.java index fe49e3478..6e794d966 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyController.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * 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. @@ -20,13 +20,14 @@ package org.onap.policy.pap.xacml.rest.controller; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.Date; import java.util.List; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.RiskType; @@ -39,10 +40,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - @Controller public class SafePolicyController { @@ -53,36 +50,39 @@ public class SafePolicyController { private static String safePolicyWarningDatas = "safePolicyWarningDatas"; @Autowired - public SafePolicyController(CommonClassDao commonClassDao){ + public SafePolicyController(CommonClassDao commonClassDao) { SafePolicyController.commonClassDao = commonClassDao; } - public void setCommonClassDao(CommonClassDao commonClassDao){ + public void setCommonClassDao(CommonClassDao commonClassDao) { SafePolicyController.commonClassDao = commonClassDao; } - public SafePolicyController(){ + public SafePolicyController() { super(); } - private DictionaryUtils getDictionaryUtilsInstance(){ + private DictionaryUtils getDictionaryUtilsInstance() { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value = { "/get_RiskTypeDataByName" }, method = {RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value = {"/get_RiskTypeDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) public void getRiskTypeDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, riskTypeDatas, "name", RiskType.class); } - @RequestMapping(value = { "/get_RiskTypeData" }, method = {RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value = {"/get_RiskTypeData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) public void getRiskTypeDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, riskTypeDatas, RiskType.class); } - @RequestMapping(value = { "/sp_dictionary/save_riskType" }, method = {RequestMethod.POST }) - public ModelAndView saveRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/sp_dictionary/save_riskType"}, method = {RequestMethod.POST}) + public ModelAndView saveRiskTypeDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -92,69 +92,80 @@ public class SafePolicyController { RiskType riskTypeData; String userId = null; if (fromAPI) { - riskTypeData = mapper.readValue(root.get("dictionaryFields").toString(), RiskType.class); + riskTypeData = + mapper.readValue(root.get("dictionaryFields").toString(), RiskType.class); userId = "API"; } else { - riskTypeData = mapper.readValue(root.get("riskTypeDictionaryData").toString(), RiskType.class); + riskTypeData = mapper.readValue(root.get("riskTypeDictionaryData").toString(), + RiskType.class); userId = root.get("userid").textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(riskTypeData.getRiskName(), "name", RiskType.class); + List<Object> duplicateData = commonClassDao + .checkDuplicateEntry(riskTypeData.getRiskName(), "name", RiskType.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { RiskType data = (RiskType) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { riskTypeData.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != riskTypeData.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != riskTypeData.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { riskTypeData.setUserModifiedBy(userInfo); - if(riskTypeData.getId() == 0){ + if (riskTypeData.getId() == 0) { riskTypeData.setUserCreatedBy(userInfo); commonClassDao.save(riskTypeData); - }else{ + } else { riskTypeData.setModifiedDate(new Date()); commonClassDao.update(riskTypeData); } responseString = mapper.writeValueAsString(commonClassDao.getData(RiskType.class)); - }else{ + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, riskTypeDatas, responseString); } - }catch (Exception e) { + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value = { "/sp_dictionary/remove_riskType" }, method = {RequestMethod.POST }) - public void removeRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/sp_dictionary/remove_riskType"}, method = {RequestMethod.POST}) + public void removeRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, riskTypeDatas, RiskType.class); } - @RequestMapping(value = { "/get_SafePolicyWarningDataByName" }, method = {RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value = {"/get_SafePolicyWarningDataByName"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) public void getSafePolicyWarningEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, safePolicyWarningDatas, "name", SafePolicyWarning.class); } - @RequestMapping(value = { "/get_SafePolicyWarningData" }, method = {RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) + @RequestMapping(value = {"/get_SafePolicyWarningData"}, method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) public void getSafePolicyWarningeEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, safePolicyWarningDatas, SafePolicyWarning.class); } - @RequestMapping(value = { "/sp_dictionary/save_safePolicyWarning" }, method = {RequestMethod.POST }) - public ModelAndView saveSafePolicyWarningDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/sp_dictionary/save_safePolicyWarning"}, + method = {RequestMethod.POST}) + public ModelAndView saveSafePolicyWarningDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -163,46 +174,55 @@ public class SafePolicyController { JsonNode root = mapper.readTree(request.getReader()); SafePolicyWarning safePolicyWarning; if (fromAPI) { - safePolicyWarning = mapper.readValue(root.get("dictionaryFields").toString(), SafePolicyWarning.class); + safePolicyWarning = mapper.readValue(root.get("dictionaryFields").toString(), + SafePolicyWarning.class); } else { - safePolicyWarning = mapper.readValue(root.get("safePolicyWarningData").toString(), SafePolicyWarning.class); + safePolicyWarning = mapper.readValue(root.get("safePolicyWarningData").toString(), + SafePolicyWarning.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(safePolicyWarning.getName(), "name", SafePolicyWarning.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry( + safePolicyWarning.getName(), "name", SafePolicyWarning.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { SafePolicyWarning data = (SafePolicyWarning) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null + && "update".equals(request.getParameter(operation))) { safePolicyWarning.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != safePolicyWarning.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null + && (data.getId() != safePolicyWarning.getId()))) { duplicateflag = true; } } String responseString = null; - if(!duplicateflag){ - if(safePolicyWarning.getId() == 0){ + if (!duplicateflag) { + if (safePolicyWarning.getId() == 0) { commonClassDao.save(safePolicyWarning); - }else{ + } else { commonClassDao.update(safePolicyWarning); } - responseString = mapper.writeValueAsString(commonClassDao.getData(SafePolicyWarning.class)); - }else{ + responseString = + mapper.writeValueAsString(commonClassDao.getData(SafePolicyWarning.class)); + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, safePolicyWarningDatas, responseString); } - }catch (Exception e) { + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value = { "/sp_dictionary/remove_SafePolicyWarning" }, method = {RequestMethod.POST }) - public void removeSafePolicyWarningDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/sp_dictionary/remove_SafePolicyWarning"}, + method = {RequestMethod.POST}) + public void removeSafePolicyWarningDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, safePolicyWarningDatas, SafePolicyWarning.class); } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java index e5b6915bd..2688d7d3c 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017,2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,9 +22,7 @@ package org.onap.policy.pap.xacml.rest.daoimpl; import java.util.List; import java.util.Map; - import javax.script.SimpleBindings; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.Criteria; @@ -49,7 +47,7 @@ import org.springframework.stereotype.Service; @Service("CommonClassDao") @Primary -public class CommonClassDaoImpl implements CommonClassDao{ +public class CommonClassDaoImpl implements CommonClassDao { private static final Log LOGGER = LogFactory.getLog(CommonClassDaoImpl.class); @@ -58,80 +56,83 @@ public class CommonClassDaoImpl implements CommonClassDao{ @Autowired - private CommonClassDaoImpl(SessionFactory sessionFactory){ + private CommonClassDaoImpl(SessionFactory sessionFactory) { CommonClassDaoImpl.sessionFactory = sessionFactory; } - public CommonClassDaoImpl(){ - //Default Constructor + public CommonClassDaoImpl() { + // Default Constructor } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Override public List<Object> getData(Class className) { Session session = sessionFactory.openSession(); List<Object> data = null; - try{ + try { Criteria cr = session.createCriteria(className); data = cr.list(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e); - }finally{ - try{ + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table" + e); + } finally { + try { session.close(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Closing Connection/Statement" + e); } } return data; } - @SuppressWarnings({ "rawtypes", "unchecked" }) + @SuppressWarnings({"rawtypes", "unchecked"}) @Override public List<Object> getDataById(Class className, String columnName, String key) { Session session = sessionFactory.openSession(); List<Object> data = null; try { Criteria cr = session.createCriteria(className); - if(columnName.contains(":") && key.contains(":")){ + if (columnName.contains(":") && key.contains(":")) { String[] columns = columnName.split(":"); String[] keys = key.split(":"); - for(int i=0; i < columns.length; i++){ + for (int i = 0; i < columns.length; i++) { cr.add(Restrictions.eq(columns[i], keys[i])); } - }else{ + } else { cr.add(Restrictions.eq(columnName, key)); } data = cr.list(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e); - }finally{ - try{ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table" + e); + } finally { + try { session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Closing Connection/Statement" + e1); } } return data; } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Override public List<String> getDataByColumn(Class className, String columnName) { Session session = sessionFactory.openSession(); List<String> data = null; - try{ + try { Criteria cr = session.createCriteria(className); cr.setProjection(Projections.property(columnName)); data = cr.list(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e); - }finally{ - try{ + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table" + e); + } finally { + try { session.close(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Closing Connection/Statement" + e); } } return data; @@ -144,13 +145,15 @@ public class CommonClassDaoImpl implements CommonClassDao{ try { session.persist(entity); tx.commit(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving data to Table"+e); - }finally{ - try{ + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Saving data to Table" + e); + } finally { + try { session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Closing Connection/Statement" + e1); } } @@ -163,13 +166,15 @@ public class CommonClassDaoImpl implements CommonClassDao{ try { session.delete(entity); tx.commit(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting data from Table"+e); - }finally{ - try{ + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Deleting data from Table" + e); + } finally { + try { session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Closing Connection/Statement" + e1); } } @@ -183,20 +188,22 @@ public class CommonClassDaoImpl implements CommonClassDao{ try { session.update(entity); tx.commit(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating data to Table"+e); - }finally{ - try{ + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Updating data to Table" + e); + } finally { + try { session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Closing Connection/Statement" + e1); } } } - @SuppressWarnings({ "unchecked", "rawtypes" }) + @SuppressWarnings({"unchecked", "rawtypes"}) @Override public List<Object> checkDuplicateEntry(String value, String columnName, Class className) { Session session = sessionFactory.openSession(); @@ -204,32 +211,34 @@ public class CommonClassDaoImpl implements CommonClassDao{ List<Object> data = null; String[] columnNames = null; - if(columnName != null && columnName.contains(":")){ + if (columnName != null && columnName.contains(":")) { columnNames = columnName.split(":"); } String[] values = null; - if(value != null && value.contains(":")){ + if (value != null && value.contains(":")) { values = value.split(":"); } try { Criteria cr = session.createCriteria(className); - if(columnNames != null && values != null && columnNames.length == values.length){ - for (int i = 0; i < columnNames.length; i++){ - cr.add(Restrictions.eq(columnNames[i],values[i])); + if (columnNames != null && values != null && columnNames.length == values.length) { + for (int i = 0; i < columnNames.length; i++) { + cr.add(Restrictions.eq(columnNames[i], values[i])); } - }else{ - cr.add(Restrictions.eq(columnName,value)); + } else { + cr.add(Restrictions.eq(columnName, value)); } data = cr.list(); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying for Duplicate Entries for Table"+e + className); - }finally{ - try{ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Querying for Duplicate Entries for Table" + e + className); + } finally { + try { session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Closing Connection/Statement" + e1); } } return data; @@ -245,23 +254,24 @@ public class CommonClassDaoImpl implements CommonClassDao{ try { Query hbquery = session.createQuery(query); for (Map.Entry<String, Object> paramPair : params.entrySet()) { - if(paramPair.getValue() instanceof java.lang.Long){ + if (paramPair.getValue() instanceof java.lang.Long) { hbquery.setLong(paramPair.getKey(), (long) paramPair.getValue()); - } - else{ + } else { hbquery.setParameter(paramPair.getKey(), paramPair.getValue()); } } data = hbquery.list(); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table"+e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Querying Database Table" + e); throw e; - }finally{ - try{ + } finally { + try { session.close(); - }catch(HibernateException e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement",e1); + } catch (HibernateException e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Closing Connection/Statement", e1); } } return data; @@ -277,12 +287,14 @@ public class CommonClassDaoImpl implements CommonClassDao{ hbquery.executeUpdate(); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating Database Table"+e); - }finally{ - try{ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Updating Database Table" + e); + } finally { + try { session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Closing Connection/Statement" + e1); } } } @@ -296,24 +308,26 @@ public class CommonClassDaoImpl implements CommonClassDao{ Object data = null; try { Criteria cr = session.createCriteria(className); - if(columnName.contains(":") && key.contains(":")){ + if (columnName.contains(":") && key.contains(":")) { String[] columns = columnName.split(":"); String[] keys = key.split(":"); - for(int i=0; i < columns.length; i++){ + for (int i = 0; i < columns.length; i++) { cr.add(Restrictions.eq(columns[i], keys[i])); } - }else{ + } else { cr.add(Restrictions.eq(columnName, key)); } data = cr.list().get(0); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table"+e); - }finally{ - try{ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Querying Database Table" + e); + } finally { + try { session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Closing Connection/Statement" + e1); } } return data; @@ -329,11 +343,11 @@ public class CommonClassDaoImpl implements CommonClassDao{ try { Criteria cr = session.createCriteria(PolicyRoles.class); Disjunction disjunction = Restrictions.disjunction(); - Conjunction conjunction1 = Restrictions.conjunction(); + Conjunction conjunction1 = Restrictions.conjunction(); conjunction1.add(Restrictions.eq("role", "admin")); - Conjunction conjunction2 = Restrictions.conjunction(); + Conjunction conjunction2 = Restrictions.conjunction(); conjunction2.add(Restrictions.eq("role", "editor")); - Conjunction conjunction3 = Restrictions.conjunction(); + Conjunction conjunction3 = Restrictions.conjunction(); conjunction3.add(Restrictions.eq("role", "guest")); disjunction.add(conjunction1); disjunction.add(conjunction2); @@ -341,12 +355,14 @@ public class CommonClassDaoImpl implements CommonClassDao{ rolesData = cr.add(disjunction).list(); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PolicyRoles Table"+e); - }finally{ - try{ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Querying PolicyRoles Table" + e); + } finally { + try { session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Closing Connection/Statement" + e1); } } return rolesData; @@ -361,15 +377,16 @@ public class CommonClassDaoImpl implements CommonClassDao{ Transaction tx = session.beginTransaction(); try { Criteria cr = session.createCriteria(ClosedLoops.class); - cr.add(Restrictions.eq("closedLoopControlName",clName)); + cr.add(Restrictions.eq("closedLoopControlName", clName)); closedloopsdata = cr.list(); ClosedLoops closedloop = closedloopsdata.get(0); closedloop.setAlarmConditions(alarms); session.update(closedloop); tx.commit(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating ClosedLoops Table"+e); - }finally{ + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Updating ClosedLoops Table" + e); + } finally { session.close(); } } @@ -383,15 +400,16 @@ public class CommonClassDaoImpl implements CommonClassDao{ Transaction tx = session.beginTransaction(); try { Criteria cr = session.createCriteria(ClosedLoops.class); - cr.add(Restrictions.eq("closedLoopControlName",clName)); + cr.add(Restrictions.eq("closedLoopControlName", clName)); closedloopsdata = cr.list(); ClosedLoops closedloop = closedloopsdata.get(0); closedloop.setYaml(yaml); session.update(closedloop); tx.commit(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating ClosedLoops Table"+e); - }finally{ + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Updating ClosedLoops Table" + e); + } finally { session.close(); } } @@ -407,9 +425,10 @@ public class CommonClassDaoImpl implements CommonClassDao{ Criteria cr = session.createCriteria(ClosedLoops.class); closedloopsdata = cr.list(); - if(closedloopsdata!=null && !closedloopsdata.isEmpty()) { - LOGGER.info("ClosedLoops exist in the database, we need to delete them in our first step to buildCache()."); - for(int i=0; i < closedloopsdata.size(); i++) { + if (closedloopsdata != null && !closedloopsdata.isEmpty()) { + LOGGER.info( + "ClosedLoops exist in the database, we need to delete them in our first step to buildCache()."); + for (int i = 0; i < closedloopsdata.size(); i++) { ClosedLoops cl = closedloopsdata.get(i); session.delete(cl); } @@ -418,33 +437,38 @@ public class CommonClassDaoImpl implements CommonClassDao{ } tx.commit(); - }catch(Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while deleting ClosedLoops from the table"+e); - }finally{ + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error while deleting ClosedLoops from the table" + e); + } finally { session.close(); } } - @SuppressWarnings({ "unchecked"}) + @SuppressWarnings({"unchecked"}) @Override - public List<Object> checkExistingGroupListforUpdate(String groupListValue, String groupNameValue) { + public List<Object> checkExistingGroupListforUpdate(String groupListValue, + String groupNameValue) { Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); List<Object> data = null; try { Criteria cr = session.createCriteria(GroupPolicyScopeList.class); - cr.add(Restrictions.eq("groupList",groupListValue)); + cr.add(Restrictions.eq("groupList", groupListValue)); Criterion expression = Restrictions.eq("name", groupNameValue); cr.add(Restrictions.not(expression)); data = cr.list(); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying for Duplicate Entries for GroupPolicyScopeList Table"+e); - }finally{ - try{ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Querying for Duplicate Entries for GroupPolicyScopeList Table" + + e); + } finally { + try { session.close(); - }catch(Exception e1){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error While Closing Connection/Statement" + e1); } } return data; @@ -452,7 +476,8 @@ public class CommonClassDaoImpl implements CommonClassDao{ @Override - public List<Object> getMultipleDataOnAddingConjunction(@SuppressWarnings("rawtypes") Class className, String columnName, List<String> data) { + public List<Object> getMultipleDataOnAddingConjunction( + @SuppressWarnings("rawtypes") Class className, String columnName, List<String> data) { return null; } @@ -460,4 +485,4 @@ public class CommonClassDaoImpl implements CommonClassDao{ sessionFactory = sessionfactory; } -}
\ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java index e895b6336..d64b71763 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,57 +17,38 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.elk.client; +import io.searchbox.client.JestResult; import java.util.Map; - import org.onap.policy.rest.adapter.PolicyRestAdapter; -import io.searchbox.client.JestResult; - public interface ElkConnector { public static final String ELK_URL = "http://localhost:9200"; public static final String ELK_INDEX_POLICY = "policy"; public enum PolicyIndexType { - config, - action, - decision, - closedloop, - all, + config, action, decision, closedloop, all, } public enum PolicyType { - Config, - Action, - Decision, - Config_Fault, - Config_PM, - Config_FW, - Config_MS, - Config_OOF, - none, + Config, Action, Decision, Config_Fault, Config_PM, Config_FW, Config_MS, Config_OOF, none, } public enum PolicyBodyType { - json, - xml, - properties, - txt, - none, + json, xml, properties, txt, none, } - public boolean delete(PolicyRestAdapter policyData) - throws IllegalStateException; + public boolean delete(PolicyRestAdapter policyData) throws IllegalStateException; public JestResult search(PolicyIndexType type, String text) - throws IllegalStateException, IllegalArgumentException; + throws IllegalStateException, IllegalArgumentException; - public JestResult search(PolicyIndexType type, String text, - Map<String, String> searchKeyValue) - throws IllegalStateException, IllegalArgumentException; + public JestResult search(PolicyIndexType type, String text, Map<String, String> searchKeyValue) + throws IllegalStateException, IllegalArgumentException; public boolean update(PolicyRestAdapter policyData) throws IllegalStateException; @@ -88,16 +69,15 @@ public interface ElkConnector { return PolicyIndexType.config; } else if (policyName.startsWith("Config_OOF")) { return PolicyIndexType.config; - }else if (policyName.startsWith("Action")) { + } else if (policyName.startsWith("Action")) { return PolicyIndexType.action; } else if (policyName.startsWith("Decision")) { return PolicyIndexType.decision; } else if (policyName.startsWith("Config")) { return PolicyIndexType.config; } else { - throw new IllegalArgumentException - ("Unsupported policy name conversion to index: " + - policyName); + throw new IllegalArgumentException( + "Unsupported policy name conversion to index: " + policyName); } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java index 19a7ed294..6bbe033a3 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * 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. @@ -17,20 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.policy.pap.xacml.rest.elk.client; - -import java.io.IOException; -import java.util.Map; -import java.util.Map.Entry; -import org.elasticsearch.index.query.QueryBuilders; -import org.elasticsearch.index.query.QueryStringQueryBuilder; -import org.elasticsearch.search.builder.SearchSourceBuilder; -import org.json.JSONObject; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.rest.adapter.PolicyRestAdapter; -import org.onap.policy.xacml.api.XACMLErrorConstants; +package org.onap.policy.pap.xacml.rest.elk.client; import io.searchbox.action.Action; import io.searchbox.client.JestClient; @@ -44,8 +32,19 @@ import io.searchbox.core.Search.Builder; import io.searchbox.indices.IndicesExists; import io.searchbox.indices.type.TypeExist; import io.searchbox.params.Parameters; +import java.io.IOException; +import java.util.Map; +import java.util.Map.Entry; +import org.elasticsearch.index.query.QueryBuilders; +import org.elasticsearch.index.query.QueryStringQueryBuilder; +import org.elasticsearch.search.builder.SearchSourceBuilder; +import org.json.JSONObject; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.xacml.api.XACMLErrorConstants; -public class ElkConnectorImpl implements ElkConnector{ +public class ElkConnectorImpl implements ElkConnector { private static final Logger LOGGER = FlexLogger.getLogger(ElkConnector.class); @@ -54,21 +53,23 @@ public class ElkConnectorImpl implements ElkConnector{ protected static int QUERY_MAXRECORDS = 1000; public ElkConnectorImpl() { - if (LOGGER.isDebugEnabled()){ + if (LOGGER.isDebugEnabled()) { LOGGER.debug("ENTER: -"); } - HttpClientConfig jestClientConfig = new HttpClientConfig.Builder(ELK_URL).multiThreaded(true).build(); + HttpClientConfig jestClientConfig = + new HttpClientConfig.Builder(ELK_URL).multiThreaded(true).build(); jestFactory.setHttpClientConfig(jestClientConfig); jestClient = jestFactory.getObject(); } protected boolean isType(PolicyIndexType type) throws IOException { - if (LOGGER.isDebugEnabled()){ + if (LOGGER.isDebugEnabled()) { LOGGER.debug("ENTER: -"); } try { - Action<JestResult> typeQuery = new TypeExist.Builder(ELK_INDEX_POLICY).addType(type.toString()).build(); + Action<JestResult> typeQuery = + new TypeExist.Builder(ELK_INDEX_POLICY).addType(type.toString()).build(); JestResult result = jestClient.execute(typeQuery); if (LOGGER.isInfoEnabled()) { @@ -79,7 +80,9 @@ public class ElkConnectorImpl implements ElkConnector{ } return result.isSucceeded(); } catch (IOException e) { - LOGGER.warn("Error checking type existance of " + type.toString() + ": " + e.getMessage(), e); + LOGGER.warn( + "Error checking type existance of " + type.toString() + ": " + e.getMessage(), + e); throw e; } } @@ -97,17 +100,21 @@ public class ElkConnectorImpl implements ElkConnector{ } return result.isSucceeded(); } catch (IOException e) { - LOGGER.warn("Error checking index existance of " + ELK_INDEX_POLICY + ": " + e.getMessage(), e); + LOGGER.warn( + "Error checking index existance of " + ELK_INDEX_POLICY + ": " + e.getMessage(), + e); throw e; } } - private boolean isAlphaNumeric(String query){ + + private boolean isAlphaNumeric(String query) { return query.matches("[a-zA-Z_0-9]+"); } @Override - public JestResult search(PolicyIndexType type, String text) throws IllegalStateException, IllegalArgumentException { - if (LOGGER.isTraceEnabled()){ + public JestResult search(PolicyIndexType type, String text) + throws IllegalStateException, IllegalArgumentException { + if (LOGGER.isTraceEnabled()) { LOGGER.trace("ENTER: " + text); } @@ -115,20 +122,19 @@ public class ElkConnectorImpl implements ElkConnector{ throw new IllegalArgumentException("No search string provided"); } - if(!isAlphaNumeric(text)){ + if (!isAlphaNumeric(text)) { throw new IllegalArgumentException("Search must be alpha numeric"); } - QueryStringQueryBuilder mQ = QueryBuilders.queryStringQuery("*"+text+"*"); - SearchSourceBuilder searchSourceBuilder = - new SearchSourceBuilder().query(mQ); + QueryStringQueryBuilder mQ = QueryBuilders.queryStringQuery("*" + text + "*"); + SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(mQ); - Builder searchBuilder = new Search.Builder(searchSourceBuilder.toString()). - addIndex(ELK_INDEX_POLICY). - setParameter(Parameters.SIZE, ElkConnectorImpl.QUERY_MAXRECORDS); + Builder searchBuilder = + new Search.Builder(searchSourceBuilder.toString()).addIndex(ELK_INDEX_POLICY) + .setParameter(Parameters.SIZE, ElkConnectorImpl.QUERY_MAXRECORDS); if (type == null || type == PolicyIndexType.all) { - for (PolicyIndexType pT: PolicyIndexType.values()) { + for (PolicyIndexType pT : PolicyIndexType.values()) { if (pT != PolicyIndexType.all) { searchBuilder.addType(pT.toString()); } @@ -142,26 +148,24 @@ public class ElkConnectorImpl implements ElkConnector{ try { result = jestClient.execute(search); } catch (IOException ioe) { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + - search + ": " + ioe.getMessage(), ioe); + LOGGER.warn( + XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + search + ": " + ioe.getMessage(), + ioe); throw new IllegalStateException(ioe); } if (result.isSucceeded()) { - if (LOGGER.isInfoEnabled()){ - LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " + - result.getPathToResult() + ":" + System.lineSeparator() + - result.getJsonString()); + if (LOGGER.isInfoEnabled()) { + LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " + + result.getPathToResult() + ":" + System.lineSeparator() + + result.getJsonString()); } } else { /* Unsuccessful search */ - if (LOGGER.isWarnEnabled()){ - LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + - result.getResponseCode() + ": " + - search.getURI() + ":" + - result.getPathToResult() + ":" + - result.getJsonString() + ":" + - result.getErrorMessage()); + if (LOGGER.isWarnEnabled()) { + LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + result.getResponseCode() + + ": " + search.getURI() + ":" + result.getPathToResult() + ":" + + result.getJsonString() + ":" + result.getErrorMessage()); } String errorMessage = result.getErrorMessage(); @@ -169,19 +173,24 @@ public class ElkConnectorImpl implements ElkConnector{ String xMessage; if (errorMessage.contains("TokenMgrError")) { int indexError = errorMessage.lastIndexOf("TokenMgrError"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + + errorMessage.substring(indexError); } else if (errorMessage.contains("QueryParsingException")) { int indexError = errorMessage.lastIndexOf("QueryParsingException"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + + errorMessage.substring(indexError); } else if (errorMessage.contains("JsonParseException")) { int indexError = errorMessage.lastIndexOf("JsonParseException"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + + errorMessage.substring(indexError); } else if (errorMessage.contains("Parse Failure")) { int indexError = errorMessage.lastIndexOf("Parse Failure"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + + errorMessage.substring(indexError); } else if (errorMessage.contains("SearchParseException")) { int indexError = errorMessage.lastIndexOf("SearchParseException"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + + errorMessage.substring(indexError); } else { xMessage = result.getErrorMessage(); } @@ -194,10 +203,9 @@ public class ElkConnectorImpl implements ElkConnector{ @Override - public JestResult search(PolicyIndexType type, String text, - Map<String, String> filter_s) - throws IllegalStateException, IllegalArgumentException { - if (LOGGER.isTraceEnabled()){ + public JestResult search(PolicyIndexType type, String text, Map<String, String> filter_s) + throws IllegalStateException, IllegalArgumentException { + if (LOGGER.isTraceEnabled()) { LOGGER.trace("ENTER: " + text); } @@ -205,52 +213,50 @@ public class ElkConnectorImpl implements ElkConnector{ return search(type, text); } - if(!isAlphaNumeric(text)){ + if (!isAlphaNumeric(text)) { throw new IllegalArgumentException("Search must be alpha numeric"); } String matches_s = ""; - matches_s = "{\n" + - " \"size\" : "+ ElkConnectorImpl.QUERY_MAXRECORDS + ",\n" + - " \"query\": {\n" + - " \"bool\" : {\n" + - " \"must\" : ["; + matches_s = "{\n" + " \"size\" : " + ElkConnectorImpl.QUERY_MAXRECORDS + ",\n" + + " \"query\": {\n" + " \"bool\" : {\n" + " \"must\" : ["; String match_params = ""; boolean first = true; - for(Entry<String, String> entry : filter_s.entrySet()){ + for (Entry<String, String> entry : filter_s.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); - if(first){ - match_params = "\"match\" : {\""+key+"\" : \""+value+"\" }},"; + if (first) { + match_params = "\"match\" : {\"" + key + "\" : \"" + value + "\" }},"; first = false; - }else{ - match_params = match_params + "{\"match\" : { \""+key+"\" : \""+value+"\" } },"; + } else { + match_params = + match_params + "{\"match\" : { \"" + key + "\" : \"" + value + "\" } },"; } } - if(match_params.endsWith(",")){ - match_params = match_params.substring(0, match_params.length()-2); + if (match_params.endsWith(",")) { + match_params = match_params.substring(0, match_params.length() - 2); } - matches_s = matches_s + "{\n" + match_params + "\n}" ; + matches_s = matches_s + "{\n" + match_params + "\n}"; boolean query = false; String query_String = ""; - if(text != null){ + if (text != null) { query = true; - query_String = "{\n \"query_string\" : {\n \"query\" : \"*"+text+"*\"\n} \n}"; + query_String = "{\n \"query_string\" : {\n \"query\" : \"*" + text + "*\"\n} \n}"; } - if(query){ - matches_s = matches_s + "," + query_String + "]\n}\n}\n}"; - }else{ + if (query) { + matches_s = matches_s + "," + query_String + "]\n}\n}\n}"; + } else { matches_s = matches_s + "]\n}\n}\n}"; } Builder searchBuilder = new Search.Builder(matches_s).addIndex(ELK_INDEX_POLICY); if (type == null || type == PolicyIndexType.all) { - for (PolicyIndexType pT: PolicyIndexType.values()) { + for (PolicyIndexType pT : PolicyIndexType.values()) { if (pT != PolicyIndexType.all) { searchBuilder.addType(pT.toString()); } @@ -265,26 +271,24 @@ public class ElkConnectorImpl implements ElkConnector{ try { result = jestClient.execute(search); } catch (IOException ioe) { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + - search + ": " + ioe.getMessage(), ioe); + LOGGER.warn( + XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + search + ": " + ioe.getMessage(), + ioe); throw new IllegalStateException(ioe); } if (result.isSucceeded()) { - if (LOGGER.isInfoEnabled()){ - LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " + - result.getPathToResult() + ":" + System.lineSeparator() + - result.getJsonString()); + if (LOGGER.isInfoEnabled()) { + LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " + + result.getPathToResult() + ":" + System.lineSeparator() + + result.getJsonString()); } } else { /* Unsuccessful search */ - if (LOGGER.isWarnEnabled()){ - LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + - result.getResponseCode() + ": " + - search.getURI() + ":" + - result.getPathToResult() + ":" + - result.getJsonString() + ":" + - result.getErrorMessage()); + if (LOGGER.isWarnEnabled()) { + LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + result.getResponseCode() + + ": " + search.getURI() + ":" + result.getPathToResult() + ":" + + result.getJsonString() + ":" + result.getErrorMessage()); } String errorMessage = result.getErrorMessage(); @@ -292,19 +296,24 @@ public class ElkConnectorImpl implements ElkConnector{ String xMessage = errorMessage; if (errorMessage.contains("TokenMgrError")) { int indexError = errorMessage.lastIndexOf("TokenMgrError"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + + errorMessage.substring(indexError); } else if (errorMessage.contains("QueryParsingException")) { int indexError = errorMessage.lastIndexOf("QueryParsingException"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + + errorMessage.substring(indexError); } else if (errorMessage.contains("JsonParseException")) { int indexError = errorMessage.lastIndexOf("JsonParseException"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + + errorMessage.substring(indexError); } else if (errorMessage.contains("Parse Failure")) { int indexError = errorMessage.lastIndexOf("Parse Failure"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + + errorMessage.substring(indexError); } else if (errorMessage.contains("SearchParseException")) { int indexError = errorMessage.lastIndexOf("SearchParseException"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + + errorMessage.substring(indexError); } else { xMessage = result.getErrorMessage(); } @@ -315,18 +324,18 @@ public class ElkConnectorImpl implements ElkConnector{ return result; } - public boolean put(PolicyRestAdapter policyData) - throws IOException, IllegalStateException { - if (LOGGER.isTraceEnabled()) LOGGER.trace("ENTER"); + public boolean put(PolicyRestAdapter policyData) throws IOException, IllegalStateException { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("ENTER"); PolicyIndexType indexType; try { String policyName = policyData.getNewFileName(); - if(policyName.contains("Config_")){ + if (policyName.contains("Config_")) { policyName = policyName.replace(".Config_", ":Config_"); - }else if(policyName.contains("Action_")){ + } else if (policyName.contains("Action_")) { policyName = policyName.replace(".Action_", ":Action_"); - }else if(policyName.contains("Decision_")){ + } else if (policyName.contains("Decision_")) { policyName = policyName.replace(".Decision_", ":Decision_"); } @@ -338,27 +347,23 @@ public class ElkConnectorImpl implements ElkConnector{ } PolicyElasticData elasticData = new PolicyElasticData(policyData); JSONObject jsonObj = new JSONObject(elasticData); - Index elkPut = new Index.Builder(jsonObj.toString()). - index(ELK_INDEX_POLICY). - type(indexType.name()). - id(elasticData.getPolicyName()). - refresh(true). - build(); + Index elkPut = new Index.Builder(jsonObj.toString()).index(ELK_INDEX_POLICY) + .type(indexType.name()).id(elasticData.getPolicyName()).refresh(true).build(); JestResult result = jestClient.execute(elkPut); if (result.isSucceeded()) { if (LOGGER.isInfoEnabled()) - LOGGER.info("ElkConnector: OK: PUT operation of " + "->" + ": " + - "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + - result.getPathToResult() + "]" + System.lineSeparator() + - result.getJsonString()); + LOGGER.info("ElkConnector: OK: PUT operation of " + "->" + ": " + "success=" + + result.isSucceeded() + "[" + result.getResponseCode() + ":" + + result.getPathToResult() + "]" + System.lineSeparator() + + result.getJsonString()); } else { if (LOGGER.isWarnEnabled()) - LOGGER.warn("ElkConnector: FAILURE: PUT operation of "+ "->" + ": " + - "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + - result.getPathToResult() + "]" + System.lineSeparator() + - result.getJsonString()); + LOGGER.warn("ElkConnector: FAILURE: PUT operation of " + "->" + ": " + "success=" + + result.isSucceeded() + "[" + result.getResponseCode() + ":" + + result.getPathToResult() + "]" + System.lineSeparator() + + result.getJsonString()); } @@ -366,57 +371,55 @@ public class ElkConnectorImpl implements ElkConnector{ } @Override - public boolean delete(PolicyRestAdapter policyData) throws IllegalStateException { + public boolean delete(PolicyRestAdapter policyData) throws IllegalStateException { PolicyIndexType indexType = null; JestResult result; try { String policyName = policyData.getNewFileName(); - if(policyName.contains("Config_")){ + if (policyName.contains("Config_")) { policyName = policyName.replace(".Config_", ":Config_"); - }else if(policyName.contains("Action_")){ + } else if (policyName.contains("Action_")) { policyName = policyName.replace(".Action_", ":Action_"); - }else if(policyName.contains("Decision_")){ + } else if (policyName.contains("Decision_")) { policyName = policyName.replace(".Decision_", ":Decision_"); } String[] splitPolicyName = policyName.split(":"); indexType = ElkConnector.toPolicyIndexType(splitPolicyName[1]); if (!isType(indexType)) { - throw new IllegalStateException("ELK: Index: " + ELK_INDEX_POLICY + - " Type: " + indexType + - " is not configured"); + throw new IllegalStateException("ELK: Index: " + ELK_INDEX_POLICY + " Type: " + + indexType + " is not configured"); } PolicyElasticData elasticData = new PolicyElasticData(policyData); - Delete deleteRequest = new Delete.Builder(elasticData.getPolicyName()).index(ELK_INDEX_POLICY). - type(indexType.name()).build(); + Delete deleteRequest = new Delete.Builder(elasticData.getPolicyName()) + .index(ELK_INDEX_POLICY).type(indexType.name()).build(); result = jestClient.execute(deleteRequest); } catch (IllegalArgumentException | IOException e) { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ": delete:" + - indexType + ": null" + ":" + policyData.getNewFileName() + ": " + - e.getMessage(), e); + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ": delete:" + indexType + ": null" + + ":" + policyData.getNewFileName() + ": " + e.getMessage(), e); throw new IllegalStateException(e); } if (result.isSucceeded()) { if (LOGGER.isInfoEnabled()) - LOGGER.info("OK: DELETE operation of " + indexType + ":" + policyData.getNewFileName() + ": " + - "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + - result.getPathToResult() + "]" + System.lineSeparator() + - result.getJsonString()); + LOGGER.info("OK: DELETE operation of " + indexType + ":" + + policyData.getNewFileName() + ": " + "success=" + result.isSucceeded() + + "[" + result.getResponseCode() + ":" + result.getPathToResult() + "]" + + System.lineSeparator() + result.getJsonString()); } else { if (LOGGER.isWarnEnabled()) - LOGGER.warn("FAILURE: DELETE operation of " + indexType + ":" + policyData.getNewFileName() + ": " + - "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + - result.getPathToResult() + "]" + System.lineSeparator() + - result.getJsonString()); + LOGGER.warn("FAILURE: DELETE operation of " + indexType + ":" + + policyData.getNewFileName() + ": " + "success=" + result.isSucceeded() + + "[" + result.getResponseCode() + ":" + result.getPathToResult() + "]" + + System.lineSeparator() + result.getJsonString()); } return result.isSucceeded(); } @Override - public boolean update(PolicyRestAdapter policyData) throws IllegalStateException { - if (LOGGER.isDebugEnabled()){ + public boolean update(PolicyRestAdapter policyData) throws IllegalStateException { + if (LOGGER.isDebugEnabled()) { LOGGER.debug("ENTER"); } try { diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java index e965356be..dd24aafc9 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * 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. @@ -17,13 +17,12 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.service; import java.io.IOException; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.onap.policy.pap.xacml.rest.controller.ActionPolicyDictionaryController; import org.onap.policy.pap.xacml.rest.controller.BRMSDictionaryController; import org.onap.policy.pap.xacml.rest.controller.ClosedLoopDictionaryController; @@ -45,250 +44,284 @@ public class DictionaryService { /* * Methods that call the controller method directly to Save and Update dictionary data */ - public String saveOnapDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + public String saveOnapDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryController dictionary = new DictionaryController(); - ModelAndView result = dictionary.saveOnapDictionary(request, response); + ModelAndView result = dictionary.saveOnapDictionary(request, response); return result.getViewName(); } - public String saveAttributeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveAttributeDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryController dictionary = new DictionaryController(); - ModelAndView result = dictionary.saveAttributeDictionary(request, response); + ModelAndView result = dictionary.saveAttributeDictionary(request, response); return result.getViewName(); - } + } - public String saveActionPolicyDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + public String saveActionPolicyDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { ActionPolicyDictionaryController action = new ActionPolicyDictionaryController(); - ModelAndView result = action.saveActionPolicyDictionary(request, response); + ModelAndView result = action.saveActionPolicyDictionary(request, response); return result.getViewName(); } - public String saveBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + public String saveBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { BRMSDictionaryController dictionary = new BRMSDictionaryController(); - ModelAndView result = dictionary.saveBRMSParamDictionary(request, response); + ModelAndView result = dictionary.saveBRMSParamDictionary(request, response); return result.getViewName(); } - public String saveVSCLAction(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveVSCLAction(HttpServletRequest request, HttpServletResponse response) + throws IOException { ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - ModelAndView result = dictionary.saveVSCLAction(request, response); + ModelAndView result = dictionary.saveVSCLAction(request, response); return result.getViewName(); } - public String saveVnfType(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveVnfType(HttpServletRequest request, HttpServletResponse response) + throws IOException { ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - ModelAndView result = dictionary.saveVnfType(request, response); + ModelAndView result = dictionary.saveVnfType(request, response); return result.getViewName(); } - public String savePEPOptions(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String savePEPOptions(HttpServletRequest request, HttpServletResponse response) + throws IOException { ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - ModelAndView result = dictionary.savePEPOptions(request, response); + ModelAndView result = dictionary.savePEPOptions(request, response); return result.getViewName(); } - public String saveVarbind(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveVarbind(HttpServletRequest request, HttpServletResponse response) + throws IOException { ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - ModelAndView result = dictionary.saveVarbind(request, response); + ModelAndView result = dictionary.saveVarbind(request, response); return result.getViewName(); } - public String saveServiceType(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveServiceType(HttpServletRequest request, HttpServletResponse response) + throws IOException { ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - ModelAndView result = dictionary.saveServiceType(request, response); + ModelAndView result = dictionary.saveServiceType(request, response); return result.getViewName(); } - public String saveSiteType(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveSiteType(HttpServletRequest request, HttpServletResponse response) + throws IOException { ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - ModelAndView result = dictionary.saveSiteType(request, response); + ModelAndView result = dictionary.saveSiteType(request, response); return result.getViewName(); } - public String saveSettingsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveSettingsDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController(); - ModelAndView result = dictionary.saveSettingsDictionary(request, response); + ModelAndView result = dictionary.saveSettingsDictionary(request, response); return result.getViewName(); } - public String saveRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController(); - ModelAndView result = dictionary.saveRainyDayDictionary(request, response); + ModelAndView result = dictionary.saveRainyDayDictionary(request, response); return result.getViewName(); } - public String saveDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveDescriptiveDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { DescriptiveDictionaryController dictionary = new DescriptiveDictionaryController(); - ModelAndView result = dictionary.saveDescriptiveDictionary(request, response); + ModelAndView result = dictionary.saveDescriptiveDictionary(request, response); return result.getViewName(); } - public String saveActionListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveActionListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - ModelAndView result = dictionary.saveActionListDictionary(request, response); + ModelAndView result = dictionary.saveActionListDictionary(request, response); return result.getViewName(); } - public String saveProtocolListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveProtocolListDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - ModelAndView result = dictionary.saveProtocolListDictionary(request, response); + ModelAndView result = dictionary.saveProtocolListDictionary(request, response); return result.getViewName(); } - public String saveZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveZoneDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - ModelAndView result = dictionary.saveZoneDictionary(request, response); + ModelAndView result = dictionary.saveZoneDictionary(request, response); return result.getViewName(); } - public String saveSecurityZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveSecurityZoneDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - ModelAndView result = dictionary.saveSecurityZoneDictionary(request, response); + ModelAndView result = dictionary.saveSecurityZoneDictionary(request, response); return result.getViewName(); } - public String savePrefixListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String savePrefixListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - ModelAndView result = dictionary.savePrefixListDictionary(request, response); + ModelAndView result = dictionary.savePrefixListDictionary(request, response); return result.getViewName(); } - public String saveAddressGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveAddressGroupDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - ModelAndView result = dictionary.saveAddressGroupDictionary(request, response); + ModelAndView result = dictionary.saveAddressGroupDictionary(request, response); return result.getViewName(); } - public String saveServiceGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveServiceGroupDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - ModelAndView result = dictionary.saveServiceGroupDictionary(request, response); + ModelAndView result = dictionary.saveServiceGroupDictionary(request, response); return result.getViewName(); } - public String saveServiceListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveServiceListDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - ModelAndView result = dictionary.saveServiceListDictionary(request, response); + ModelAndView result = dictionary.saveServiceListDictionary(request, response); return result.getViewName(); } - public String saveTermListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveTermListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - ModelAndView result = dictionary.saveTermListDictionary(request, response); + ModelAndView result = dictionary.saveTermListDictionary(request, response); return result.getViewName(); } - - public String saveMicroServiceLocationDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveMicroServiceLocationDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - ModelAndView result = dictionary.saveMicroServiceLocationDictionary(request, response); + ModelAndView result = dictionary.saveMicroServiceLocationDictionary(request, response); return result.getViewName(); } - public String saveMicroServiceConfigNameDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveMicroServiceConfigNameDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - ModelAndView result = dictionary.saveMicroServiceConfigNameDictionary(request, response); + ModelAndView result = dictionary.saveMicroServiceConfigNameDictionary(request, response); return result.getViewName(); } - public String saveDCAEUUIDDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveDCAEUUIDDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - ModelAndView result = dictionary.saveDCAEUUIDDictionary(request, response); + ModelAndView result = dictionary.saveDCAEUUIDDictionary(request, response); return result.getViewName(); } - public String saveMicroServiceModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveMicroServiceModelsDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - ModelAndView result = dictionary.saveMicroServiceModelsDictionary(request, response); + ModelAndView result = dictionary.saveMicroServiceModelsDictionary(request, response); return result.getViewName(); } - public String saveMicroServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveMicroServiceDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - ModelAndView result = dictionary.saveMicroServiceAttributeDictionary(request, response); + ModelAndView result = dictionary.saveMicroServiceAttributeDictionary(request, response); return result.getViewName(); } - public String saveOptimizationModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveOptimizationModelsDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { OptimizationDictionaryController dictionary = new OptimizationDictionaryController(); - ModelAndView result = dictionary.saveOptimizationModelsDictionary(request, response); + ModelAndView result = dictionary.saveOptimizationModelsDictionary(request, response); return result.getViewName(); } - public String savePSServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String savePSServiceDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - ModelAndView result = dictionary.savePSServiceDictionary(request, response); + ModelAndView result = dictionary.savePSServiceDictionary(request, response); return result.getViewName(); } - public String savePSResourceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String savePSResourceDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - ModelAndView result = dictionary.savePSResourceDictionary(request, response); + ModelAndView result = dictionary.savePSResourceDictionary(request, response); return result.getViewName(); } - public String savePSTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String savePSTypeDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - ModelAndView result = dictionary.savePSTypeDictionary(request, response); + ModelAndView result = dictionary.savePSTypeDictionary(request, response); return result.getViewName(); } - public String savePSClosedLoopDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String savePSClosedLoopDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - ModelAndView result = dictionary.savePSClosedLoopDictionary(request, response); + ModelAndView result = dictionary.savePSClosedLoopDictionary(request, response); return result.getViewName(); } - public String savePSGroupScopeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String savePSGroupScopeDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - ModelAndView result = dictionary.savePSGroupScopeDictionary(request, response); + ModelAndView result = dictionary.savePSGroupScopeDictionary(request, response); return result.getViewName(); } - public String saveRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { SafePolicyController dictionary = new SafePolicyController(); - ModelAndView result = dictionary.saveRiskTypeDictionary(request, response); + ModelAndView result = dictionary.saveRiskTypeDictionary(request, response); return result.getViewName(); } - public String saveSafePolicyWarningDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + public String saveSafePolicyWarningDictionary(HttpServletRequest request, + HttpServletResponse response) throws IOException { SafePolicyController dictionary = new SafePolicyController(); - ModelAndView result = dictionary.saveSafePolicyWarningDictionary(request, response); + ModelAndView result = dictionary.saveSafePolicyWarningDictionary(request, response); return result.getViewName(); } @@ -296,179 +329,179 @@ public class DictionaryService { /* * Methods that call the controller get methods directly to get dictionary data */ - public void getOnapDictionary(HttpServletResponse response){ + public void getOnapDictionary(HttpServletResponse response) { DictionaryController dictionary = new DictionaryController(); - dictionary.getOnapNameDictionaryEntityData(response); + dictionary.getOnapNameDictionaryEntityData(response); } - public void getAttributeDictionary(HttpServletResponse response){ + public void getAttributeDictionary(HttpServletResponse response) { DictionaryController dictionary = new DictionaryController(); - dictionary.getAttributeDictionaryEntityData(response); + dictionary.getAttributeDictionaryEntityData(response); } - public void getActionPolicyDictionary(HttpServletResponse response){ + public void getActionPolicyDictionary(HttpServletResponse response) { ActionPolicyDictionaryController action = new ActionPolicyDictionaryController(); - action.getActionPolicyDictionaryEntityData(response); + action.getActionPolicyDictionaryEntityData(response); } - public void getBRMSParamDictionary(HttpServletResponse response){ + public void getBRMSParamDictionary(HttpServletResponse response) { BRMSDictionaryController dictionary = new BRMSDictionaryController(); - dictionary.getBRMSParamDictionaryEntityData(response); + dictionary.getBRMSParamDictionaryEntityData(response); } - public void getVSCLAction(HttpServletResponse response){ + public void getVSCLAction(HttpServletResponse response) { ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - dictionary.getVSCLActionDictionaryEntityData(response); + dictionary.getVSCLActionDictionaryEntityData(response); } - public void getVnfType(HttpServletResponse response){ + public void getVnfType(HttpServletResponse response) { ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - dictionary.getVNFTypeDictionaryEntityData(response); + dictionary.getVNFTypeDictionaryEntityData(response); } - public void getPEPOptions(HttpServletResponse response){ + public void getPEPOptions(HttpServletResponse response) { ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - dictionary.getPEPOptionsDictionaryEntityData(response); + dictionary.getPEPOptionsDictionaryEntityData(response); } - public void getVarbind(HttpServletResponse response){ + public void getVarbind(HttpServletResponse response) { ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - dictionary.getVarbindDictionaryEntityData(response); + dictionary.getVarbindDictionaryEntityData(response); } - public void getServiceType(HttpServletResponse response){ + public void getServiceType(HttpServletResponse response) { ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - dictionary.getClosedLoopServiceDictionaryEntityData(response); + dictionary.getClosedLoopServiceDictionaryEntityData(response); } - public void getSiteType(HttpServletResponse response){ + public void getSiteType(HttpServletResponse response) { ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - dictionary.getClosedLoopSiteDictionaryEntityData(response); + dictionary.getClosedLoopSiteDictionaryEntityData(response); } - public void getSettingsDictionary(HttpServletResponse response){ + public void getSettingsDictionary(HttpServletResponse response) { DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController(); - dictionary.getSettingsDictionaryEntityData(response); + dictionary.getSettingsDictionaryEntityData(response); } - public void getRainyDayDictionary(HttpServletResponse response){ + public void getRainyDayDictionary(HttpServletResponse response) { DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController(); - dictionary.getRainyDayDictionaryEntityData(response); + dictionary.getRainyDayDictionaryEntityData(response); } - public void getDescriptiveDictionary(HttpServletResponse response){ + public void getDescriptiveDictionary(HttpServletResponse response) { DescriptiveDictionaryController dictionary = new DescriptiveDictionaryController(); - dictionary.getDescriptiveDictionaryEntityData(response); + dictionary.getDescriptiveDictionaryEntityData(response); } - public void getActionListDictionary(HttpServletResponse response){ + public void getActionListDictionary(HttpServletResponse response) { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - dictionary.getActionListDictionaryEntityData(response); + dictionary.getActionListDictionaryEntityData(response); } - public void getProtocolListDictionary(HttpServletResponse response){ + public void getProtocolListDictionary(HttpServletResponse response) { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - dictionary.getProtocolListDictionaryEntityData(response); + dictionary.getProtocolListDictionaryEntityData(response); } - public void getZoneDictionary(HttpServletResponse response){ + public void getZoneDictionary(HttpServletResponse response) { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - dictionary.getZoneDictionaryEntityData(response); + dictionary.getZoneDictionaryEntityData(response); } - public void getSecurityZoneDictionary(HttpServletResponse response){ + public void getSecurityZoneDictionary(HttpServletResponse response) { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - dictionary.getSecurityZoneDictionaryEntityData(response); + dictionary.getSecurityZoneDictionaryEntityData(response); } - public void getPrefixListDictionary(HttpServletResponse response){ + public void getPrefixListDictionary(HttpServletResponse response) { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - dictionary.getPrefixListDictionaryEntityData(response); + dictionary.getPrefixListDictionaryEntityData(response); } - public void getAddressGroupDictionary(HttpServletResponse response){ + public void getAddressGroupDictionary(HttpServletResponse response) { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - dictionary.getAddressGroupDictionaryEntityData(response); + dictionary.getAddressGroupDictionaryEntityData(response); } - public void getServiceGroupDictionary(HttpServletResponse response){ + public void getServiceGroupDictionary(HttpServletResponse response) { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - dictionary.getServiceGroupDictionaryEntityData(response); + dictionary.getServiceGroupDictionaryEntityData(response); } - public void getServiceListDictionary(HttpServletResponse response){ + public void getServiceListDictionary(HttpServletResponse response) { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - dictionary.getServiceListDictionaryEntityData(response); + dictionary.getServiceListDictionaryEntityData(response); } - public void getTermListDictionary(HttpServletResponse response){ + public void getTermListDictionary(HttpServletResponse response) { FirewallDictionaryController dictionary = new FirewallDictionaryController(); - dictionary.getTermListDictionaryEntityData(response); + dictionary.getTermListDictionaryEntityData(response); } - public void getMicroServiceLocationDictionary(HttpServletResponse response){ + public void getMicroServiceLocationDictionary(HttpServletResponse response) { MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - dictionary.getMicroServiceLocationDictionaryEntityData(response); + dictionary.getMicroServiceLocationDictionaryEntityData(response); } - public void getMicroServiceConfigNameDictionary(HttpServletResponse response){ + public void getMicroServiceConfigNameDictionary(HttpServletResponse response) { MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - dictionary.getMicroServiceConfigNameDictionaryEntityData(response); + dictionary.getMicroServiceConfigNameDictionaryEntityData(response); } - public void getDCAEUUIDDictionary(HttpServletResponse response){ + public void getDCAEUUIDDictionary(HttpServletResponse response) { MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - dictionary.getDCAEUUIDDictionaryEntityData(response); + dictionary.getDCAEUUIDDictionaryEntityData(response); } - public void getMicroServiceModelsDictionary(HttpServletResponse response){ + public void getMicroServiceModelsDictionary(HttpServletResponse response) { MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - dictionary.getMicroServiceModelsDictionaryEntityData(response); + dictionary.getMicroServiceModelsDictionaryEntityData(response); } - public void getMicroServiceDictionary(HttpServletResponse response){ + public void getMicroServiceDictionary(HttpServletResponse response) { MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - dictionary.getMicroServiceModelsDictionaryEntityData(response); + dictionary.getMicroServiceModelsDictionaryEntityData(response); } - public void getOptimizationModelsDictionary(HttpServletResponse response){ + public void getOptimizationModelsDictionary(HttpServletResponse response) { OptimizationDictionaryController dictionary = new OptimizationDictionaryController(); - dictionary.getOptimizationModelsDictionaryEntityData(response); + dictionary.getOptimizationModelsDictionaryEntityData(response); } - public void getPSServiceDictionary(HttpServletResponse response){ + public void getPSServiceDictionary(HttpServletResponse response) { PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - dictionary.getPSServiceEntityData(response); + dictionary.getPSServiceEntityData(response); } - public void getPSResourceDictionary(HttpServletResponse response){ + public void getPSResourceDictionary(HttpServletResponse response) { PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - dictionary.getPSResourceEntityData(response); + dictionary.getPSResourceEntityData(response); } - public void getPSTypeDictionary(HttpServletResponse response){ + public void getPSTypeDictionary(HttpServletResponse response) { PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - dictionary.getPSTypeEntityData(response); + dictionary.getPSTypeEntityData(response); } - public void getPSClosedLoopDictionary(HttpServletResponse response){ + public void getPSClosedLoopDictionary(HttpServletResponse response) { PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - dictionary.getPSClosedLoopEntityData(response); + dictionary.getPSClosedLoopEntityData(response); } - public void getPSGroupScopeDictionary(HttpServletResponse response){ + public void getPSGroupScopeDictionary(HttpServletResponse response) { PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - dictionary.getGroupPolicyScopeEntityData(response); + dictionary.getGroupPolicyScopeEntityData(response); } - public void getRiskTypeDictionary(HttpServletResponse response){ + public void getRiskTypeDictionary(HttpServletResponse response) { SafePolicyController dictionary = new SafePolicyController(); - dictionary.getRiskTypeDictionaryEntityData(response); + dictionary.getRiskTypeDictionaryEntityData(response); } public void getSafePolicyWarningDictionary(HttpServletResponse response) { SafePolicyController dictionary = new SafePolicyController(); - dictionary.getSafePolicyWarningeEntityData(response); + dictionary.getSafePolicyWarningeEntityData(response); } -}
\ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java index 5e4b4ee7d..01fbff7ce 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.service; import java.io.BufferedWriter; @@ -29,10 +30,8 @@ import java.io.Writer; import java.util.HashMap; import java.util.Map; import java.util.UUID; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; @@ -43,7 +42,7 @@ import org.onap.policy.pap.xacml.rest.components.CreateNewOptimizationModel; public class ImportService { private static final Logger logger = FlexLogger.getLogger(ImportService.class); private static String errorMessage = "Error in reading in file from API call"; - private static String errorMsg = "error"; + private static String errorMsg = "error"; private static String operation = "operation"; private static String importHeader = "import"; private static String service = "service"; @@ -59,7 +58,7 @@ public class ImportService { String version = request.getParameter("version"); String serviceName = request.getParameter("serviceName"); - if(serviceName == null || serviceName.isEmpty() || !serviceName.matches(REGEX)){ + if (serviceName == null || serviceName.isEmpty() || !serviceName.matches(REGEX)) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.addHeader(errorMsg, MISSING); response.addHeader(operation, importHeader); @@ -69,12 +68,12 @@ public class ImportService { String description = request.getParameter("description"); Map<String, String> successMap = new HashMap<>(); - if(("BRMSPARAM").equals(importServiceCreation)){ + if (("BRMSPARAM").equals(importServiceCreation)) { StringBuilder builder = new StringBuilder(); int ch; try { - while((ch = request.getInputStream().read()) != -1){ - builder.append((char)ch); + while ((ch = request.getInputStream().read()) != -1) { + builder.append((char) ch); } } catch (IOException e) { logger.error(e); @@ -85,19 +84,19 @@ public class ImportService { response.addHeader(service, serviceName); } CreateBRMSRuleTemplate brmsRuleTemplate = new CreateBRMSRuleTemplate(); - successMap = brmsRuleTemplate.addRule(builder.toString(), serviceName, description, "API"); - } - else if(("MICROSERVICE").equals(importServiceCreation)){ + successMap = + brmsRuleTemplate.addRule(builder.toString(), serviceName, description, "API"); + } else if (("MICROSERVICE").equals(importServiceCreation)) { CreateNewMicroServiceModel newMS = null; String randomID = UUID.randomUUID().toString(); String type = ".xmi"; - if ( fileName != null) { + if (fileName != null) { File extracDir = new File(extractDir); - if (!extracDir.exists()){ + if (!extracDir.exists()) { extracDir.mkdirs(); } - if (fileName.contains(".xmi") || fileName.contains(".yml")){ - if(fileName.contains(".yml")){ + if (fileName.contains(".xmi") || fileName.contains(".yml")) { + if (fileName.contains(".yml")) { type = ".yml"; } // get the request content into a String @@ -106,7 +105,7 @@ public class ImportService { try { scanner = new java.util.Scanner(request.getInputStream()); scanner.useDelimiter("\\A"); - xmi = scanner.hasNext() ? scanner.next() : ""; + xmi = scanner.hasNext() ? scanner.next() : ""; scanner.close(); } catch (IOException e1) { logger.error(e1); @@ -115,37 +114,41 @@ public class ImportService { } PolicyLogger.info("Request from API to import new Service"); try (Writer writer = new BufferedWriter(new OutputStreamWriter( - new FileOutputStream(extractDir + File.separator + randomID+type), "utf-8"))) { + new FileOutputStream(extractDir + File.separator + randomID + type), + "utf-8"))) { writer.write(xmi); } catch (IOException e) { logger.error(e); PolicyLogger.error(errorMessage); return; } - }else{ + } else { InputStream inputStream = null; - try(FileOutputStream outputStream = new FileOutputStream(extractDir + File.separator + randomID+".zip")) { + try (FileOutputStream outputStream = + new FileOutputStream(extractDir + File.separator + randomID + ".zip")) { inputStream = request.getInputStream(); byte[] buffer = new byte[4096]; - int bytesRead = -1 ; + int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { - outputStream.write(buffer, 0, bytesRead) ; + outputStream.write(buffer, 0, bytesRead); } } catch (IOException e) { - PolicyLogger.error("Error in reading in Zip File from API call"+e); + PolicyLogger.error("Error in reading in Zip File from API call" + e); return; - }finally{ + } finally { try { - if(inputStream != null){ + if (inputStream != null) { inputStream.close(); } } catch (IOException e) { - PolicyLogger.error("Exception Occured while closing the input/output stream"+e); + PolicyLogger.error( + "Exception Occured while closing the input/output stream" + e); } } } - newMS = new CreateNewMicroServiceModel(fileName, serviceName, "API", version, randomID); + newMS = new CreateNewMicroServiceModel(fileName, serviceName, "API", version, + randomID); successMap = newMS.addValuesToNewModel(type); @@ -154,12 +157,12 @@ public class ImportService { successMap = newMS.saveImportService(); } } - } else if(("OPTIMIZATION").equals(importServiceCreation)){ + } else if (("OPTIMIZATION").equals(importServiceCreation)) { CreateNewOptimizationModel newOOF = null; String randomID = UUID.randomUUID().toString(); - if ( fileName != null) { + if (fileName != null) { File extracDir = new File(extractDir); - if (!extracDir.exists()){ + if (!extracDir.exists()) { extracDir.mkdirs(); } @@ -167,9 +170,9 @@ public class ImportService { // get the request content into a String String yml = null; - try (java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());){ + try (java.util.Scanner scanner = new java.util.Scanner(request.getInputStream());) { scanner.useDelimiter("\\A"); - yml = scanner.hasNext() ? scanner.next() : ""; + yml = scanner.hasNext() ? scanner.next() : ""; } catch (IOException e1) { logger.error(e1); PolicyLogger.error(errorMessage); @@ -177,7 +180,8 @@ public class ImportService { } PolicyLogger.info("Request from API to import new Optimization Service Model"); try (Writer writer = new BufferedWriter(new OutputStreamWriter( - new FileOutputStream(extractDir + File.separator + randomID+type), "utf-8"))) { + new FileOutputStream(extractDir + File.separator + randomID + type), + "utf-8"))) { writer.write(yml); } catch (IOException e) { logger.error(e); @@ -185,7 +189,8 @@ public class ImportService { return; } - newOOF = new CreateNewOptimizationModel(fileName, serviceName, "API Import Service", version, randomID); + newOOF = new CreateNewOptimizationModel(fileName, serviceName, "API Import Service", + version, randomID); successMap = newOOF.addValuesToNewModel(); if (successMap.containsKey(successMessage)) { successMap.clear(); @@ -201,22 +206,22 @@ public class ImportService { response.addHeader(operation, importHeader); response.addHeader(service, serviceName); } else if (successMap.containsKey("DBError")) { - if (successMap.get("DBError").contains("EXISTS")){ + if (successMap.get("DBError").contains("EXISTS")) { response.setStatus(HttpServletResponse.SC_CONFLICT); response.addHeader(service, serviceName); response.addHeader(errorMsg, "modelExistsDB"); - }else{ + } else { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.addHeader(errorMsg, "importDB"); } response.addHeader(operation, importHeader); response.addHeader(service, serviceName); - }else if (successMap.get(errorMsg).contains("MISSING")){ + } else if (successMap.get(errorMsg).contains("MISSING")) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.addHeader(errorMsg, MISSING); response.addHeader(operation, importHeader); response.addHeader(service, serviceName); - }else if (successMap.get(errorMsg).contains("VALIDATION")){ + } else if (successMap.get(errorMsg).contains("VALIDATION")) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.addHeader(errorMsg, "validation"); response.addHeader(operation, importHeader); @@ -224,4 +229,4 @@ public class ImportService { } } -}
\ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/DictionaryUtils.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/DictionaryUtils.java index f85255785..e88efa931 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/DictionaryUtils.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/DictionaryUtils.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,18 +17,20 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.util; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONObject; @@ -41,14 +43,10 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - @Service public class DictionaryUtils { - private static final Log LOGGER = LogFactory.getLog(DictionaryUtils.class); + private static final Log LOGGER = LogFactory.getLog(DictionaryUtils.class); private static String apiflag = "apiflag"; private static String operation = "operation"; @@ -69,78 +67,80 @@ public class DictionaryUtils { } @Autowired - public DictionaryUtils(CommonClassDao commonClassDao){ + public DictionaryUtils(CommonClassDao commonClassDao) { DictionaryUtils.commonClassDao = commonClassDao; } - public DictionaryUtils(){ + public DictionaryUtils() { super(); } - public UserInfo getUserInfo(String loginId){ + public UserInfo getUserInfo(String loginId) { return (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); } - public boolean isRequestFromAPI(HttpServletRequest request){ - return request.getParameter(apiflag)!=null && "api".equalsIgnoreCase(request.getParameter(apiflag)); + public boolean isRequestFromAPI(HttpServletRequest request) { + return request.getParameter(apiflag) != null + && "api".equalsIgnoreCase(request.getParameter(apiflag)); } - public String appendKey(List<Object> objects, String key1, String appendValue){ + public String appendKey(List<Object> objects, String key1, String appendValue) { StringBuilder userValue = new StringBuilder(); int counter = 0; - for(Object attribute : objects){ - if(attribute instanceof LinkedHashMap<?, ?>){ + for (Object attribute : objects) { + if (attribute instanceof LinkedHashMap<?, ?>) { String key = ((LinkedHashMap<?, ?>) attribute).get(key1).toString(); - if(counter>0){ + if (counter > 0) { userValue.append(appendValue); } userValue.append(key); - counter ++; + counter++; } } return userValue.toString(); } - public String appendKeyValue(List<Object> objects, String append1, String append2){ + public String appendKeyValue(List<Object> objects, String append1, String append2) { StringBuilder header = new StringBuilder(); int counter = 0; - for(Object attribute : objects){ - if(attribute instanceof LinkedHashMap<?, ?>){ + for (Object attribute : objects) { + if (attribute instanceof LinkedHashMap<?, ?>) { String key = ((LinkedHashMap<?, ?>) attribute).get("option").toString(); String value = ((LinkedHashMap<?, ?>) attribute).get("number").toString(); - if(counter>0){ + if (counter > 0) { header.append(append1); } header.append(key).append(append2).append(value); - counter ++; + counter++; } } return header.toString(); } - public Datatype getDataType(String datatype){ + public Datatype getDataType(String datatype) { Datatype a = new Datatype(); - if("string".equalsIgnoreCase(datatype)){ + if ("string".equalsIgnoreCase(datatype)) { a.setId(26); - }else if("integer".equalsIgnoreCase(datatype)){ + } else if ("integer".equalsIgnoreCase(datatype)) { a.setId(12); - }else if("boolean".equalsIgnoreCase(datatype)){ + } else if ("boolean".equalsIgnoreCase(datatype)) { a.setId(18); - }else if("double".equalsIgnoreCase(datatype)){ + } else if ("double".equalsIgnoreCase(datatype)) { a.setId(25); - }else if("user".equalsIgnoreCase(datatype)){ + } else if ("user".equalsIgnoreCase(datatype)) { a.setId(29); } return a; } - public Category getCategory(){ - return (Category) commonClassDao.getDataById(Category.class, "shortName", "resource").get(0); + public Category getCategory() { + return (Category) commonClassDao.getDataById(Category.class, "shortName", "resource") + .get(0); } - public ModelAndView getResultForApi(String inResponseString){ + public ModelAndView getResultForApi(String inResponseString) { String responseString = inResponseString; - if(responseString!=null && !duplicateResponseString.equals(responseString)){ + if (responseString != null && !duplicateResponseString.equals(responseString)) { responseString = "Success"; } ModelAndView result = new ModelAndView(); @@ -148,16 +148,17 @@ public class DictionaryUtils { return result; } - public void setResponseData(HttpServletResponse response, String key, String responseString) throws IOException{ + public void setResponseData(HttpServletResponse response, String key, String responseString) + throws IOException { response.setCharacterEncoding(utf8); response.setContentType(applicationJsonContentType); PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{"+key+":" + responseString + "}"); + JSONObject j = new JSONObject("{" + key + ":" + responseString + "}"); out.write(j.toString()); } - public void setErrorResponseData(HttpServletResponse response, Exception e) throws IOException{ + public void setErrorResponseData(HttpServletResponse response, Exception e) throws IOException { LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); response.setCharacterEncoding(utf8); PrintWriter out = response.getWriter(); @@ -165,47 +166,51 @@ public class DictionaryUtils { } @SuppressWarnings("rawtypes") - public void getDataByEntity(HttpServletResponse response, String key, String value, Class className){ - try{ + public void getDataByEntity(HttpServletResponse response, String key, String value, + Class className) { + try { Map<String, Object> model = new HashMap<>(); ObjectMapper mapper = new ObjectMapper(); - model.put(key, mapper.writeValueAsString(commonClassDao.getDataByColumn(className, value))); + model.put(key, + mapper.writeValueAsString(commonClassDao.getDataByColumn(className, value))); JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); JSONObject j = new JSONObject(msg); response.getWriter().write(j.toString()); - }catch(Exception e){ + } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); } } @SuppressWarnings("rawtypes") - public void getData(HttpServletResponse response, String key, Class className){ - try{ + public void getData(HttpServletResponse response, String key, Class className) { + try { Map<String, Object> model = new HashMap<>(); ObjectMapper mapper = new ObjectMapper(); model.put(key, mapper.writeValueAsString(commonClassDao.getData(className))); JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); + response.addHeader("successMapKey", "success"); response.addHeader(operation, "getDictionary"); response.getWriter().write(j.toString()); - }catch(Exception e){ + } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.addHeader("error", "dictionaryDBQuery"); } } @SuppressWarnings("unchecked") - public void removeData(HttpServletRequest request, HttpServletResponse response, String key, @SuppressWarnings("rawtypes") Class className) throws IOException{ - try{ + public void removeData(HttpServletRequest request, HttpServletResponse response, String key, + @SuppressWarnings("rawtypes") Class className) throws IOException { + try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); - commonClassDao.delete((Object)mapper.readValue(root.get("data").toString(), className)); + commonClassDao + .delete(mapper.readValue(root.get("data").toString(), className)); String responseString = mapper.writeValueAsString(commonClassDao.getData(className)); setResponseData(response, key, responseString); - }catch(Exception e){ + } catch (Exception e) { setErrorResponseData(response, e); } } 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 |