summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiService.java14
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DataToNotifyPdp.java2
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java442
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java4
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java178
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransactionInstance.java559
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryController.java306
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryController.java387
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryController.java162
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryController.java92
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryController.java162
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportController.java470
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryController.java873
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryController.java388
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyController.java128
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java261
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java50
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java275
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java327
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java85
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/DictionaryUtils.java107
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTest.java7
-rw-r--r--ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/MetricServiceTest.java8
-rw-r--r--ONAP-PAP-REST/xacml.pap.properties2
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java9
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PolicyEngineImportService.java22
-rw-r--r--ONAP-PDP-REST/xacml.pdp.properties5
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java72
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java64
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java1035
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java23
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java81
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java42
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java123
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java6
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java263
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java157
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java650
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java2915
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java255
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java287
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/utils/UserUtils.java134
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Edit_Roles_Window.html110
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/PolicyAddScopeRoleController.js57
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/PolicyRolesController.js81
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policyManager.js254
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/entities/item.js23
-rw-r--r--packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties4
48 files changed, 6627 insertions, 5334 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
diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java
index fcf319c8e..c227d9d2a 100644
--- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java
+++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PDP-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.
@@ -276,6 +276,13 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to create IntegrityMonitor" + e);
throw new ServletException(e);
}
+
+ try {
+ System.setProperty("msToscaModel.home", properties.getProperty("msToscaModel.home"));
+ } catch (Exception e) {
+ logger.error("ERROR: Unable to set msToscaModel.home- Please check the configuration");
+ }
+
startThreads(baseLoggingContext, new Thread(this));
}
diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PolicyEngineImportService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PolicyEngineImportService.java
index f7c1cc578..f8cba5123 100644
--- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PolicyEngineImportService.java
+++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PolicyEngineImportService.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PDP-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.
@@ -20,6 +20,7 @@
package org.onap.policy.pdp.rest.api.services;
import java.io.BufferedInputStream;
+import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
@@ -77,6 +78,25 @@ public class PolicyEngineImportService {
importResponse = XACMLErrorConstants.ERROR_DATA_ISSUE + e;
status = HttpStatus.BAD_REQUEST;
}
+
+ // Save the imported file
+ if (!file.isEmpty() && status.equals(HttpStatus.OK) ) {
+ String filePath = null;
+ try {
+ String uploadsDir = System.getProperty("msToscaModel.home");
+ if(uploadsDir != null) {
+ if(! new File(uploadsDir).exists()){
+ new File(uploadsDir).mkdir();
+ }
+ String orgName = file.getOriginalFilename();
+ filePath = uploadsDir + orgName;
+ File dest = new File(filePath);
+ file.transferTo(dest);
+ }
+ }catch(Exception e){
+ LOGGER.error("Operation: policyEngineImport : " + e.getMessage() + ". " + filePath + " is not a valid file path.");
+ }
+ }
}
private void specialCheck() {
diff --git a/ONAP-PDP-REST/xacml.pdp.properties b/ONAP-PDP-REST/xacml.pdp.properties
index b6050ff58..90e0f5c3c 100644
--- a/ONAP-PDP-REST/xacml.pdp.properties
+++ b/ONAP-PDP-REST/xacml.pdp.properties
@@ -2,7 +2,7 @@
# ============LICENSE_START=======================================================
# ONAP-PDP-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.
@@ -192,6 +192,9 @@ aaf_oauth2_token_url=https://aaf-onap-test.osaaf.org:8095/AAF_NS.token:2.1/token
fs_url=https://aaf-onap-test.osaaf.org:8095/AAF_NS.fs.2.1
gui_url=https://aaf-onap-test.osaaf.org:8095/AAF_NS.gui.2.1
+#TOSCA MS model yaml file directory which can be changed based on systems.
+#msToscaModel.home=C://home//msyamlFiles//
+msToscaModel.home=/home/users/PolicyEngine/webapps/ConfigPAP/
# Decision Response settings.
# can be either PERMIT or DENY.
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java
index 8349fab82..f91815992 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java
@@ -4,13 +4,14 @@
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
+ * Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -46,24 +47,23 @@ import org.onap.policy.xacml.api.XACMLErrorConstants;
import com.att.research.xacml.util.XACMLProperties;
/**
- * What is not good about this class is that once a value has been set for pdpProperties path
- * you cannot change it. That may be ok for a highly controlled production environment in which
- * nothing changes, but not a very good implementation.
- *
- * The reset() method has been added to assist with the above problem in order to
- * acquire >80% JUnit code coverage.
- *
- * This static class doesn't really check a PDP, it simply loads a properties file and tried
- * to ensure that a valid URL exists for a PDP along with user/password.
+ * What is not good about this class is that once a value has been set for pdpProperties path you cannot change it. That
+ * may be ok for a highly controlled production environment in which nothing changes, but not a very good
+ * implementation.
*
+ * The reset() method has been added to assist with the above problem in order to acquire >80% JUnit code coverage.
+ *
+ * This static class doesn't really check a PDP, it simply loads a properties file and tried to ensure that a valid URL
+ * exists for a PDP along with user/password.
*/
public class CheckPDP {
+
private static Path pdpPath = null;
private static Long oldModified = null;
private static HashMap<String, String> pdpMap = null;
private static final Logger LOGGER = FlexLogger.getLogger(CheckPDP.class);
- private CheckPDP(){
+ private CheckPDP() {
//default constructor
}
@@ -92,28 +92,27 @@ public class CheckPDP {
return pdpMap.containsKey(id);
}
- private static void readFile(){
- String pdpFile = null;
- try{
+ private static void readFile() {
+ String pdpFile;
+ try {
pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE);
- }catch (Exception e){
+ } catch (Exception e) {
LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot read the PDP ID File" + e);
return;
}
if (pdpFile == null) {
LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PDP File name not Valid : " + pdpFile);
- }
- if (pdpPath == null) {
+ } else if (pdpPath == null) {
pdpPath = Paths.get(pdpFile);
if (!pdpPath.toString().endsWith(".properties") || !pdpPath.toFile().exists()) {
- LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path : " + pdpPath.toString());
+ LOGGER.error(
+ XACMLErrorConstants.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path : " + pdpPath
+ .toString());
CheckPDP.reset();
return;
}
readProps();
- }
- // Check if File is updated recently
- else {
+ } else { // Check if File is updated recently
Long newModified = pdpPath.toFile().lastModified();
if (!newModified.equals(oldModified)) {
// File has been updated.
@@ -122,11 +121,11 @@ public class CheckPDP {
}
}
- @SuppressWarnings({ "unchecked", "rawtypes" })
+ @SuppressWarnings({"unchecked", "rawtypes"})
private static void readProps() {
Properties pdpProp;
pdpProp = new Properties();
- try(InputStream in = new FileInputStream(pdpPath.toFile())) {
+ try (InputStream in = new FileInputStream(pdpPath.toFile())) {
oldModified = pdpPath.toFile().lastModified();
pdpProp.load(in);
// Read the Properties and Load the PDPs and encoding.
@@ -147,7 +146,7 @@ public class CheckPDP {
}
}
- private static void loadPDPProperties(String propKey, Properties pdpProp){
+ private static void loadPDPProperties(String propKey, Properties pdpProp) {
if (propKey.startsWith("PDP_URL")) {
String checkVal = pdpProp.getProperty(propKey);
if (checkVal == null) {
@@ -165,39 +164,40 @@ public class CheckPDP {
}
}
- private static void readPDPParam(String pdpVal){
- if(pdpVal.contains(",")){
+ private static void readPDPParam(String pdpVal) {
+ if (pdpVal.contains(",")) {
List<String> pdpValues = new ArrayList<>(Arrays.asList(pdpVal.split("\\s*,\\s*")));
- if(pdpValues.size()==3){
+ if (pdpValues.size() == 3) {
// 1:2 will be UserID:Password
String userID = pdpValues.get(1);
String pass = pdpValues.get(2);
Base64.Encoder encoder = Base64.getEncoder();
// 0 - PDPURL
- pdpMap.put(pdpValues.get(0), encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8)));
- }else{
+ pdpMap.put(pdpValues.get(0),
+ encoder.encodeToString((userID + ":" + pass).getBytes(StandardCharsets.UTF_8)));
+ } else {
LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpValues);
}
- }else{
+ } else {
LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpVal);
}
}
- public static String getEncoding(String pdpID){
+ public static String getEncoding(String pdpID) {
try {
readFile();
} catch (Exception e) {
LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
}
String encoding = null;
- if(pdpMap!=null && (!pdpMap.isEmpty())){
- try{
+ if (pdpMap != null && (!pdpMap.isEmpty())) {
+ try {
encoding = pdpMap.get(pdpID);
- } catch(Exception e){
+ } catch (Exception e) {
LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
}
return encoding;
- }else{
+ } else {
return null;
}
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java
index be660c803..6aa40dacf 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java
@@ -4,6 +4,7 @@
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
+ * Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -40,7 +41,7 @@ import com.att.research.xacml.util.XACMLProperties;
public class PolicyAdapter {
- private static final Logger LOGGER = FlexLogger.getLogger(PolicyAdapter.class);
+ private static final Logger LOGGER = FlexLogger.getLogger(PolicyAdapter.class);
public void configure(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
String policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf('_'));
@@ -50,77 +51,70 @@ public class PolicyAdapter {
if (configPolicyName != null) {
policyAdapter.setConfigPolicyType(configPolicyName);
}
-
- if("Action".equalsIgnoreCase(policyAdapter.getPolicyType())){
- new ActionPolicyController().prePopulateActionPolicyData(policyAdapter, entity);
+ if ("Action".equalsIgnoreCase(policyAdapter.getPolicyType())) {
+ new ActionPolicyController().prePopulateActionPolicyData(policyAdapter);
}
- if("Decision".equalsIgnoreCase(policyAdapter.getPolicyType())){
+ if ("Decision".equalsIgnoreCase(policyAdapter.getPolicyType())) {
new DecisionPolicyController().prePopulateDecisionPolicyData(policyAdapter, entity);
}
- if("Config".equalsIgnoreCase(policyAdapter.getPolicyType())){
+ if ("Config".equalsIgnoreCase(policyAdapter.getPolicyType())) {
prePopulatePolicyData(policyAdapter, entity);
}
}
private String getConfigPolicyName(PolicyRestAdapter policyAdapter) {
- String configPolicyName = null ;
- if(policyAdapter.getPolicyName().startsWith("Config_PM")){
+ String configPolicyName = null;
+ if (policyAdapter.getPolicyName().startsWith("Config_PM")) {
configPolicyName = "ClosedLoop_PM";
- }else if(policyAdapter.getPolicyName().startsWith("Config_Fault")){
+ } else if (policyAdapter.getPolicyName().startsWith("Config_Fault")) {
configPolicyName = "ClosedLoop_Fault";
- }else if(policyAdapter.getPolicyName().startsWith("Config_FW")){
+ } else if (policyAdapter.getPolicyName().startsWith("Config_FW")) {
configPolicyName = "Firewall Config";
- }else if(policyAdapter.getPolicyName().startsWith("Config_BRMS_Raw")){
+ } else if (policyAdapter.getPolicyName().startsWith("Config_BRMS_Raw")) {
configPolicyName = "BRMS_Raw";
- }else if(policyAdapter.getPolicyName().startsWith("Config_BRMS_Param")){
+ } else if (policyAdapter.getPolicyName().startsWith("Config_BRMS_Param")) {
configPolicyName = "BRMS_Param";
- }else if(policyAdapter.getPolicyName().startsWith("Config_MS")){
+ } else if (policyAdapter.getPolicyName().startsWith("Config_MS")) {
configPolicyName = "Micro Service";
- }else if(policyAdapter.getPolicyName().startsWith("Config_OOF")){
+ } else if (policyAdapter.getPolicyName().startsWith("Config_OOF")) {
configPolicyName = "Optimization";
- }else if(policyAdapter.getPolicyName().startsWith("Action") || policyAdapter.getPolicyName().startsWith("Decision") ){
+ } else if (policyAdapter.getPolicyName().startsWith("Action") || policyAdapter.getPolicyName()
+ .startsWith("Decision")) {
// No configPolicyName is applicable
- }else{
+ } else {
configPolicyName = "Base";
}
return configPolicyName;
}
private void prePopulatePolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
- if("Base".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){
+ if ("Base".equalsIgnoreCase(policyAdapter.getConfigPolicyType())) {
new CreatePolicyController().prePopulateBaseConfigPolicyData(policyAdapter, entity);
- }
- else if("BRMS_Raw".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){
+ } else if ("BRMS_Raw".equalsIgnoreCase(policyAdapter.getConfigPolicyType())) {
new CreateBRMSRawController().prePopulateBRMSRawPolicyData(policyAdapter, entity);
- }
- else if("BRMS_Param".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){
+ } else if ("BRMS_Param".equalsIgnoreCase(policyAdapter.getConfigPolicyType())) {
new CreateBRMSParamController().prePopulateBRMSParamPolicyData(policyAdapter, entity);
- }
- else if("ClosedLoop_Fault".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){
+ } else if ("ClosedLoop_Fault".equalsIgnoreCase(policyAdapter.getConfigPolicyType())) {
new CreateClosedLoopFaultController().prePopulateClosedLoopFaultPolicyData(policyAdapter, entity);
- }
- else if("ClosedLoop_PM".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){
+ } else if ("ClosedLoop_PM".equalsIgnoreCase(policyAdapter.getConfigPolicyType())) {
new CreateClosedLoopPMController().prePopulateClosedLoopPMPolicyData(policyAdapter, entity);
- }
- else if("Micro Service".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){
+ } else if ("Micro Service".equalsIgnoreCase(policyAdapter.getConfigPolicyType())) {
new CreateDcaeMicroServiceController().prePopulateDCAEMSPolicyData(policyAdapter, entity);
- }
- else if("Optimization".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){
+ } else if ("Optimization".equalsIgnoreCase(policyAdapter.getConfigPolicyType())) {
new CreateOptimizationController().prePopulatePolicyData(policyAdapter, entity);
- }
- else if("Firewall Config".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){
+ } else if ("Firewall Config".equalsIgnoreCase(policyAdapter.getConfigPolicyType())) {
new CreateFirewallController().prePopulateFWPolicyData(policyAdapter, entity);
}
}
public static PolicyAdapter getInstance() {
try {
- Class<?> policyAdapter = Class.forName(XACMLProperties.getProperty("policyAdapter.impl.className", PolicyAdapter.class.getName()));
+ Class<?> policyAdapter = Class
+ .forName(XACMLProperties.getProperty("policyAdapter.impl.className", PolicyAdapter.class.getName()));
return (PolicyAdapter) policyAdapter.newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException e) {
- LOGGER.error("Exception Occured"+e);
+ LOGGER.error("Exception Occurred" + e);
}
return null;
}
-
-} \ No newline at end of file
+}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java
index fa9e759b7..d289feaaf 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java
@@ -2,8 +2,9 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
+ * Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -55,6 +56,7 @@ import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.http.HttpStatus;
+import org.elasticsearch.common.Strings;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
@@ -82,16 +84,17 @@ import com.att.research.xacml.util.XACMLProperties;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
-
-@WebServlet(value ="/fm/*", loadOnStartup = 1, initParams = { @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.admin.properties", description = "The location of the properties file holding configuration information.") })
+@WebServlet(value = "/fm/*", loadOnStartup = 1, initParams = {
+ @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.admin.properties", description = "The location of the properties file holding configuration information.") })
public class PolicyManagerServlet extends HttpServlet {
- private static final Logger LOGGER = FlexLogger.getLogger(PolicyManagerServlet.class);
+ private static final Logger LOGGER = FlexLogger.getLogger(PolicyManagerServlet.class);
private static final long serialVersionUID = -8453502699403909016L;
private static final String VERSION = "version";
private static final String NAME = "name";
private static final String DATE = "date";
private static final String SIZE = "size";
private static final String TYPE = "type";
+ private static final String ROLETYPE = "roleType";
private static final String CREATED_BY = "createdBy";
private static final String MODIFIED_BY = "modifiedBy";
private static final String CONTENTTYPE = "application/json";
@@ -125,16 +128,19 @@ public class PolicyManagerServlet extends HttpServlet {
private static final String SCOPE_NAME = "scopeName";
private static final String SUCCESS = "success";
private static final String SUB_SCOPENAME = "subScopename";
+ private static final String ALLSCOPES = "@All@";
private static final String PERCENT_AND_ID_GT_0 = "%' and id >0";
private static List<String> serviceTypeNamesList = new ArrayList<>();
private static JsonArray policyNames;
private static String testUserId = null;
private enum Mode {
- LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT, SEARCHLIST
+ LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION,
+ EXPORT, SEARCHLIST
}
private static PolicyController policyController;
+
private synchronized PolicyController getPolicyController() {
return policyController;
}
@@ -163,21 +169,20 @@ public class PolicyManagerServlet extends HttpServlet {
//
XACMLRest.xacmlInit(servletConfig);
//
- //Initialize ClosedLoop JSON
+ // Initialize ClosedLoop JSON
//
PolicyManagerServlet.initializeJSONLoad();
}
private static void initializeJSONLoad() {
- Path closedLoopJsonLocation = Paths.get(XACMLProperties
- .getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP));
+ Path closedLoopJsonLocation = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP));
String location = closedLoopJsonLocation.toString();
- if (! location.endsWith("json")) {
+ if (!location.endsWith("json")) {
LOGGER.warn("JSONConfig file does not end with extension .json");
return;
}
try (FileInputStream inputStream = new FileInputStream(location);
- JsonReader jsonReader = Json.createReader(inputStream)) {
+ JsonReader jsonReader = Json.createReader(inputStream)) {
policyNames = jsonReader.readArray();
serviceTypeNamesList = new ArrayList<>();
for (int i = 0; i < policyNames.size(); i++) {
@@ -186,7 +191,7 @@ public class PolicyManagerServlet extends HttpServlet {
serviceTypeNamesList.add(name);
}
} catch (IOException e) {
- LOGGER.error("Exception Occured while initializing the JSONConfig file"+e);
+ LOGGER.error("Exception Occured while initializing the JSONConfig file" + e);
}
}
@@ -205,13 +210,13 @@ public class PolicyManagerServlet extends HttpServlet {
} catch (Exception e) {
try {
setError(e, response);
- }catch(Exception e1){
- LOGGER.error(EXCEPTION_OCCURED +e1);
+ } catch (Exception e1) {
+ LOGGER.error(EXCEPTION_OCCURED + e1);
}
}
}
- //Set Error Message for Exception
+ // Set Error Message for Exception
private void setError(Exception t, HttpServletResponse response) throws IOException {
try {
JSONObject responseJsonObject = error(t.getMessage());
@@ -220,12 +225,12 @@ public class PolicyManagerServlet extends HttpServlet {
out.print(responseJsonObject);
out.flush();
} catch (Exception x) {
- LOGGER.error(EXCEPTION_OCCURED +x);
+ LOGGER.error(EXCEPTION_OCCURED + x);
response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage());
}
}
- //Policy Import Functionality
+ // Policy Import Functionality
private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException {
try {
Map<String, InputStream> files = new HashMap<>();
@@ -253,27 +258,24 @@ public class PolicyManagerServlet extends HttpServlet {
private void processFormFile(HttpServletRequest request, FileItem item) {
String newFile;
- if(item.getName().endsWith(".xls") && item.getSize() <= PolicyController.getFileSizeLimit()){
+ if (item.getName().endsWith(".xls") && item.getSize() <= PolicyController.getFileSizeLimit()) {
File file = new File(item.getName());
- try (OutputStream outputStream = new FileOutputStream(file))
- {
+ try (OutputStream outputStream = new FileOutputStream(file)) {
IOUtils.copy(item.getInputStream(), outputStream);
newFile = file.toString();
PolicyExportAndImportController importController = new PolicyExportAndImportController();
importController.importRepositoryFile(newFile, request);
- }catch(Exception e){
+ } catch (Exception e) {
LOGGER.error("Upload error : " + e);
}
- }
- else if (!item.getName().endsWith(".xls")) {
+ } else if (!item.getName().endsWith(".xls")) {
LOGGER.error("Non .xls filetype uploaded: " + item.getName());
- }
- else { //uploaded file size is greater than allowed
+ } else { // uploaded file size is greater than allowed
LOGGER.error("Upload file size limit exceeded! File size (Bytes) is: " + item.getSize());
}
}
- //File Operation Functionality
+ // File Operation Functionality
private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException {
JSONObject responseJsonObject;
StringBuilder sb = new StringBuilder();
@@ -294,9 +296,12 @@ public class PolicyManagerServlet extends HttpServlet {
Mode mode = Mode.valueOf(params.getString("mode"));
String userId = UserUtils.getUserSession(request).getOrgUserId();
- LOGGER.info("****************************************Logging UserID while doing actions on Editor tab*******************************************");
- LOGGER.info("UserId: " + userId + "Action Mode: "+ mode.toString() + "Action Params: "+params.toString());
- LOGGER.info("***********************************************************************************************************************************");
+ LOGGER.info(
+ "****************************************Logging UserID while doing actions on Editor tab*******************************************");
+ LOGGER.info(
+ "UserId: " + userId + "Action Mode: " + mode.toString() + "Action Params: " + params.toString());
+ LOGGER.info(
+ "***********************************************************************************************************************************");
responseJsonObject = operateBasedOnMode(mode, params, request);
} catch (Exception e) {
LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Processing Json" + e);
@@ -315,8 +320,8 @@ public class PolicyManagerServlet extends HttpServlet {
}
}
-
- private JSONObject operateBasedOnMode(Mode mode, JSONObject params, HttpServletRequest request) throws ServletException{
+ private JSONObject operateBasedOnMode(Mode mode, JSONObject params, HttpServletRequest request)
+ throws ServletException {
JSONObject responseJsonObject;
switch (mode) {
case ADDFOLDER:
@@ -357,11 +362,10 @@ public class PolicyManagerServlet extends HttpServlet {
return responseJsonObject;
}
-
private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) {
List<Object> policyData = new ArrayList<>();
JSONArray policyList = null;
- if(params.has("policyList")){
+ if (params.has("policyList")) {
policyList = (JSONArray) params.get("policyList");
}
PolicyController controller = getPolicyControllerInstance();
@@ -370,66 +374,68 @@ public class PolicyManagerServlet extends HttpServlet {
if (!lookupPolicyData(request, policyData, policyList, controller, resultList))
return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
- }catch(Exception e){
- LOGGER.error("Exception occured while reading policy Data from Policy Version table for Policy Search Data"+e);
+ } catch (Exception e) {
+ LOGGER.error(
+ "Exception occured while reading policy Data from Policy Version table for Policy Search Data" + e);
}
return new JSONObject().put(RESULT, resultList);
}
- private boolean lookupPolicyData(HttpServletRequest request, List<Object> policyData, JSONArray policyList, PolicyController controller, List<JSONObject> resultList){
+ private boolean lookupPolicyData(HttpServletRequest request, List<Object> policyData, JSONArray policyList,
+ PolicyController controller, List<JSONObject> resultList) {
List<String> roles;
- Set<String> scopes;//Get the Login Id of the User from Request
- String userId = UserUtils.getUserSession(request).getOrgUserId();
+ Set<String> scopes;// Get the Login Id of the User from Request
+ String userId = UserUtils.getUserSession(request).getOrgUserId();
List<Object> userRoles = controller.getRoles(userId);
Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
roles = pair.u;
scopes = pair.t;
- if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
- if(scopes.isEmpty()){
+ if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)) {
+ if (scopes.isEmpty()) {
return false;
}
- Set<String> tempScopes = scopes;
- for(String scope : tempScopes){
+ for (String scope : scopes) {
addScope(scopes, scope);
}
}
- if(policyList!= null){
- for(int i = 0; i < policyList.length(); i++){
+ if (policyList != null) {
+ for (int i = 0; i < policyList.length(); i++) {
String policyName = policyList.get(i).toString().replace(".xml", "");
- String version = policyName.substring(policyName.lastIndexOf('.')+1);
+ String version = policyName.substring(policyName.lastIndexOf('.') + 1);
policyName = policyName.substring(0, policyName.lastIndexOf('.')).replace(".", File.separator);
parsePolicyList(resultList, controller, policyName, version);
}
- }else {
+ } else {
getPolicyDataForSUPERRoles(policyData, controller, resultList, roles, scopes);
}
return true;
}
- private void getPolicyDataForSUPERRoles(List<Object> policyData, PolicyController controller, List<JSONObject> resultList, List<String> roles, Set<String> scopes) {
- if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ){
+ private void getPolicyDataForSUPERRoles(List<Object> policyData, PolicyController controller,
+ List<JSONObject> resultList, List<String> roles, Set<String> scopes) {
+ if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) {
policyData = controller.getData(PolicyVersion.class);
- }else{
- List<Object> filterdatas = controller.getData(PolicyVersion.class);
- for(Object filter : filterdatas) {
+ } else {
+ List<Object> filterData = controller.getData(PolicyVersion.class);
+ for (Object filter : filterData) {
addFilterData(policyData, scopes, (PolicyVersion) filter);
}
}
- if(!policyData.isEmpty()){
+ if (!policyData.isEmpty()) {
updateResultList(policyData, resultList);
}
}
private void addFilterData(List<Object> policyData, Set<String> scopes, PolicyVersion filter) {
- try{
+ try {
String scopeName = filter.getPolicyName().substring(0, filter.getPolicyName().lastIndexOf(File.separator));
- if(scopes.contains(scopeName)){
+ if (scopes.contains(scopeName)) {
policyData.add(filter);
}
- }catch(Exception e){
- LOGGER.error("Exception occured while filtering policyversion data"+e);
+ } catch (Exception e) {
+ LOGGER.error("Exception occured while filtering policyversion data" + e);
}
}
@@ -448,8 +454,9 @@ public class PolicyManagerServlet extends HttpServlet {
}
}
- private void parsePolicyList(List<JSONObject> resultList, PolicyController controller, String policyName, String version) {
- if(policyName.contains(BACKSLASH)){
+ private void parsePolicyList(List<JSONObject> resultList, PolicyController controller, String policyName,
+ String version) {
+ if (policyName.contains(BACKSLASH)) {
policyName = policyName.replace(BACKSLASH, ESCAPE_BACKSLASH);
}
String policyVersionQuery = "From PolicyVersion where policy_name = :policyName and active_version = :version and id >0";
@@ -457,7 +464,7 @@ public class PolicyManagerServlet extends HttpServlet {
pvParams.put("policyName", policyName);
pvParams.put(VERSION, version);
List<Object> activeData = controller.getDataByQuery(policyVersionQuery, pvParams);
- if(!activeData.isEmpty()){
+ if (!activeData.isEmpty()) {
PolicyVersion policy = (PolicyVersion) activeData.get(0);
JSONObject el = new JSONObject();
el.put(NAME, policy.getPolicyName().replace(File.separator, FORWARD_SLASH));
@@ -473,7 +480,7 @@ public class PolicyManagerServlet extends HttpServlet {
private void addScope(Set<String> scopes, String scope) {
List<Object> scopesList = queryPolicyEditorScopes(scope);
- if(!scopesList.isEmpty()){
+ if (!scopesList.isEmpty()) {
for (Object aScopesList : scopesList) {
PolicyEditorScopes tempScope = (PolicyEditorScopes) aScopesList;
scopes.add(tempScope.getScopeName());
@@ -481,63 +488,64 @@ public class PolicyManagerServlet extends HttpServlet {
}
}
- //Switch Version Functionality
- private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{
+ // Switch Version Functionality
+ private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException {
String path = params.getString("path");
String userId = null;
try {
userId = UserUtils.getUserSession(request).getOrgUserId();
} catch (Exception e) {
- LOGGER.error("Exception Occured while reading userid from cookie" +e);
+ LOGGER.error("Exception Occured while reading userid from cookie" + e);
}
String policyName;
String removeExtension = path.replace(".xml", "");
- if(path.startsWith(FORWARD_SLASH)){
+ if (path.startsWith(FORWARD_SLASH)) {
policyName = removeExtension.substring(1, removeExtension.lastIndexOf('.'));
- }else{
+ } else {
policyName = removeExtension.substring(0, removeExtension.lastIndexOf('.'));
}
String activePolicy;
PolicyController controller = getPolicyControllerInstance();
- if(! params.toString().contains("activeVersion")){
+ if (!params.toString().contains("activeVersion")) {
return controller.switchVersionPolicyContent(policyName);
}
String activeVersion = params.getString("activeVersion");
String highestVersion = params.get("highestVersion").toString();
- if(Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)){
+ if (Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)) {
return error("The Version shouldn't be greater than Highest Value");
}
activePolicy = policyName + "." + activeVersion + ".xml";
String[] splitDBCheckName = modifyPolicyName(activePolicy);
- String peQuery = "FROM PolicyEntity where policyName = :splitDBCheckName_1 and scope = :splitDBCheckName_0";
+ String peQuery = "FROM PolicyEntity where policyName = :splitDBCheckName_1 and scope = :splitDBCheckName_0";
SimpleBindings policyParams = new SimpleBindings();
policyParams.put("splitDBCheckName_1", splitDBCheckName[1]);
policyParams.put("splitDBCheckName_0", splitDBCheckName[0]);
List<Object> policyEntity = controller.getDataByQuery(peQuery, policyParams);
PolicyEntity pentity = (PolicyEntity) policyEntity.get(0);
- if(pentity.isDeleted()){
+ if (pentity.isDeleted()) {
return error("The Policy is Not Existing in Workspace");
}
- if(policyName.contains(FORWARD_SLASH)){
+ if (policyName.contains(FORWARD_SLASH)) {
policyName = policyName.replace(FORWARD_SLASH, File.separator);
}
- policyName = policyName.substring(policyName.indexOf(File.separator)+1);
- if(policyName.contains(BACKSLASH)){
+ policyName = policyName.substring(policyName.indexOf(File.separator) + 1);
+ if (policyName.contains(BACKSLASH)) {
policyName = policyName.replace(File.separator, BACKSLASH);
}
- policyName = splitDBCheckName[0].replace(".", File.separator)+File.separator+policyName;
+ policyName = splitDBCheckName[0].replace(".", File.separator) + File.separator + policyName;
String watchPolicyName = policyName;
- if(policyName.contains(FORWARD_SLASH)){
+ if (policyName.contains(FORWARD_SLASH)) {
policyName = policyName.replace(FORWARD_SLASH, File.separator);
}
- if(policyName.contains(BACKSLASH)){
+ if (policyName.contains(BACKSLASH)) {
policyName = policyName.replace(BACKSLASH, ESCAPE_BACKSLASH);
}
- String query = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION +activeVersion+"' where policy_name ='"+policyName+"' and id >0";
- //query the database
+ String query = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION + activeVersion + "' where policy_name ='" + policyName
+ + "' and id >0";
+ // query the database
controller.executeQuery(query);
- //Policy Notification
+ // Policy Notification
PolicyVersion entity = new PolicyVersion();
entity.setPolicyName(watchPolicyName);
entity.setActiveVersion(Integer.parseInt(activeVersion));
@@ -546,24 +554,24 @@ public class PolicyManagerServlet extends HttpServlet {
return success();
}
- //Describe Policy
- private JSONObject describePolicy(JSONObject params) throws ServletException{
+ // Describe Policy
+ private JSONObject describePolicy(JSONObject params) throws ServletException {
JSONObject object;
String path = params.getString("path");
String policyName;
- if(path.startsWith(FORWARD_SLASH)){
+ if (path.startsWith(FORWARD_SLASH)) {
path = path.substring(1);
- policyName = path.substring(path.lastIndexOf('/') +1);
+ policyName = path.substring(path.lastIndexOf('/') + 1);
path = path.replace(FORWARD_SLASH, ".");
- }else{
+ } else {
path = path.replace(FORWARD_SLASH, ".");
policyName = path;
}
- if(path.contains(CONFIG2)){
+ if (path.contains(CONFIG2)) {
path = path.replace(CONFIG, CONFIG1);
- }else if(path.contains(ACTION2)){
+ } else if (path.contains(ACTION2)) {
path = path.replace(ACTION, ACTION1);
- }else if(path.contains(DECISION2)){
+ } else if (path.contains(DECISION2)) {
path = path.replace(DECISION, DECISION1);
}
PolicyController controller = getPolicyControllerInstance();
@@ -572,13 +580,8 @@ public class PolicyManagerServlet extends HttpServlet {
SimpleBindings peParams = new SimpleBindings();
peParams.put(SPLIT_1, split[1]);
peParams.put(SPLIT_0, split[0]);
- List<Object> queryData;
- if(PolicyController.isjUnit()){
- queryData = controller.getDataByQuery(query, null);
- }else{
- queryData = controller.getDataByQuery(query, peParams);
- }
- if(queryData.isEmpty()){
+ List<Object> queryData = getDataByQueryFromController(controller, query, peParams);
+ if (queryData.isEmpty()) {
return error("Error Occured while Describing the Policy - query is empty");
}
PolicyEntity entity = (PolicyEntity) queryData.get(0);
@@ -593,7 +596,7 @@ public class PolicyManagerServlet extends HttpServlet {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(temp))) {
bw.write(entity.getPolicyData());
} catch (IOException e) {
- LOGGER.error("Exception Occured while Describing the Policy"+e);
+ LOGGER.error("Exception Occured while Describing the Policy" + e);
}
object = HumanPolicyComponent.DescribePolicy(temp);
try {
@@ -604,7 +607,7 @@ public class PolicyManagerServlet extends HttpServlet {
return object;
}
- //Get the List of Policies and Scopes for Showing in Editor tab
+ // Get the List of Policies and Scopes for Showing in Editor tab
private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException {
try {
return processPolicyList(params, request);
@@ -616,27 +619,28 @@ public class PolicyManagerServlet extends HttpServlet {
private JSONObject processPolicyList(JSONObject params, HttpServletRequest request) throws ServletException {
PolicyController controller = getPolicyControllerInstance();
- //Get the Login Id of the User from Request
+ // Get the Login Id of the User from Request
String testUserID = getTestUserId();
- String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId();
+ String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId();
List<Object> userRoles = controller.getRoles(userId);
Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
List<String> roles = pair.u;
Set<String> scopes = pair.t;
+ Map<String, String> roleByScope = org.onap.policy.utils.UserUtils.getRoleByScope(userRoles);
List<JSONObject> resultList = new ArrayList<>();
- boolean onlyFolders = params.getBoolean("onlyFolders");
String path = params.getString("path");
- if(path.contains("..xml")){
+ if (path.contains("..xml")) {
path = path.replaceAll("..xml", "").trim();
}
- if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
- if(scopes.isEmpty()){
+ if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)) {
+ if (scopes.isEmpty()
+ && !(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST))) {
return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
- }else{
- if(!FORWARD_SLASH.equals(path)){
- String tempScope = path.substring(1, path.length());
+ } else {
+ if (!FORWARD_SLASH.equals(path)) {
+ String tempScope = path.substring(1);
tempScope = tempScope.replace(FORWARD_SLASH, File.separator);
scopes.add(tempScope);
}
@@ -644,26 +648,27 @@ public class PolicyManagerServlet extends HttpServlet {
}
if (!FORWARD_SLASH.equals(path)) {
- try{
- String scopeName = path.substring(path.indexOf('/') +1);
- activePolicyList(scopeName, resultList, roles, scopes, onlyFolders);
+ try {
+ String scopeName = path.substring(path.indexOf('/') + 1);
+ activePolicyList(scopeName, resultList, roles, scopes, roleByScope);
} catch (Exception ex) {
- LOGGER.error("Error Occured While reading Policy Files List"+ex );
+ LOGGER.error("Error Occurred While reading Policy Files List" + ex);
}
return new JSONObject().put(RESULT, resultList);
}
-
- processRoles(scopes, roles, resultList);
-
+ processRoles(scopes, roles, resultList, roleByScope);
return new JSONObject().put(RESULT, resultList);
}
- private void processRoles(Set<String> scopes, List<String> roles, List<JSONObject> resultList) {
- if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
+ private void processRoles(Set<String> scopes, List<String> roles, List<JSONObject> resultList,
+ Map<String, String> roleByScope) {
+ if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) {
List<Object> scopesList = queryPolicyEditorScopes(null);
- for(Object list : scopesList){
- PolicyEditorScopes scope = (PolicyEditorScopes) list;
- if(!(scope.getScopeName().contains(File.separator))){
+ scopesList.stream()
+ .map(list -> (PolicyEditorScopes) list)
+ .filter(scope -> !(scope.getScopeName().contains(File.separator))
+ && !scopes.contains(scope.getScopeName()))
+ .forEach(scope -> {
JSONObject el = new JSONObject();
el.put(NAME, scope.getScopeName());
el.put(DATE, scope.getModifiedDate());
@@ -671,14 +676,15 @@ public class PolicyManagerServlet extends HttpServlet {
el.put(TYPE, "dir");
el.put(CREATED_BY, scope.getUserCreatedBy().getUserName());
el.put(MODIFIED_BY, scope.getUserModifiedBy().getUserName());
+ el.put(ROLETYPE, roleByScope.get(ALLSCOPES));
resultList.add(el);
- }
- }
- }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){
- for(Object scope : scopes){
- JSONObject el = new JSONObject();
- List<Object> scopesList = queryPolicyEditorScopes(scope.toString());
- if(!scopesList.isEmpty()){
+ });
+ }
+ if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)) {
+ scopes.stream().map(this::queryPolicyEditorScopes)
+ .filter(scopesList -> !scopesList.isEmpty())
+ .forEach(scopesList -> {
+ JSONObject el = new JSONObject();
PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
el.put(NAME, scopeById.getScopeName());
el.put(DATE, scopeById.getModifiedDate());
@@ -686,83 +692,75 @@ public class PolicyManagerServlet extends HttpServlet {
el.put(TYPE, "dir");
el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName());
el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName());
- resultList.add(el);
- }
- }
+ if ((resultList).stream().noneMatch(item -> item.get("name").equals(scopeById.getScopeName()))) {
+ el.put(ROLETYPE, roleByScope.get(scopeById.getScopeName()));
+ resultList.add(el);
+ }
+ });
}
}
- private List<Object> queryPolicyEditorScopes(String scopeName){
- String scopeNamequery;
+ private List<Object> queryPolicyEditorScopes(String scopeName) {
+ String scopeNameQuery;
SimpleBindings params = new SimpleBindings();
- if(scopeName == null){
- scopeNamequery = "from PolicyEditorScopes";
- }else{
- scopeNamequery = FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME;
+ if (scopeName == null) {
+ scopeNameQuery = "from PolicyEditorScopes";
+ } else {
+ scopeNameQuery = FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME;
params.put(SCOPE_NAME, scopeName + "%");
}
PolicyController controller = getPolicyControllerInstance();
- List<Object> scopesList;
- if(PolicyController.isjUnit()){
- scopesList = controller.getDataByQuery(scopeNamequery, null);
- }else{
- scopesList = controller.getDataByQuery(scopeNamequery, params);
- }
- return scopesList;
+ return getDataByQueryFromController(controller, scopeNameQuery, params);
}
- //Get Active Policy List based on Scope Selection form Policy Version table
- private void activePolicyList(String inScopeName, List<JSONObject> resultList, List<String> roles, Set<String> scopes, boolean onlyFolders){
+ // Get Active Policy List based on Scope Selection from Policy Version table
+ private void activePolicyList(String inScopeName, List<JSONObject> resultList, List<String> roles,
+ Set<String> scopes, Map<String, String> roleByScope) {
PolicyController controller = getPolicyControllerInstance();
String scopeName = inScopeName;
- if(scopeName.contains(FORWARD_SLASH)){
+ if (scopeName.contains(FORWARD_SLASH)) {
scopeName = scopeName.replace(FORWARD_SLASH, File.separator);
}
- if(scopeName.contains(BACKSLASH)){
+ if (scopeName.contains(BACKSLASH)) {
scopeName = scopeName.replace(BACKSLASH, ESCAPE_BACKSLASH);
}
String query = "from PolicyVersion where POLICY_NAME like :scopeName";
- String scopeNamequery = FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME;
SimpleBindings params = new SimpleBindings();
params.put(SCOPE_NAME, scopeName + "%");
- List<Object> activePolicies;
- List<Object> scopesList;
- if(PolicyController.isjUnit()){
- activePolicies = controller.getDataByQuery(query, null);
- scopesList = controller.getDataByQuery(scopeNamequery, null);
- }else{
- activePolicies = controller.getDataByQuery(query, params);
- scopesList = controller.getDataByQuery(scopeNamequery, params);
+ List<Object> activePolicies = getDataByQueryFromController(controller, query, params);
+ List<Object> scopesList = getDataByQueryFromController(controller,
+ FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME, params);
+ for (Object list : scopesList) {
+ scopeName = checkScope(resultList, scopeName, (PolicyEditorScopes) list, roleByScope);
}
- for(Object list : scopesList) {
- scopeName = checkScope(resultList, scopeName, (PolicyEditorScopes) list);
- }
- String scopeNameCheck;
for (Object list : activePolicies) {
PolicyVersion policy = (PolicyVersion) list;
- String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator));
- if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
- if(scopeName.contains(ESCAPE_BACKSLASH)){
- scopeNameCheck = scopeName.replace(ESCAPE_BACKSLASH, File.separator);
- }else{
- scopeNameCheck = scopeName;
+ String scopeNameValue = policy.getPolicyName().substring(0,
+ policy.getPolicyName().lastIndexOf(File.separator));
+ if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) {
+ String scopeNameCheck =
+ scopeName.contains(ESCAPE_BACKSLASH) ? scopeName.replace(ESCAPE_BACKSLASH, File.separator) :
+ scopeName;
+ if (!scopeNameValue.equals(scopeNameCheck)) {
+ continue;
}
- if(scopeNameValue.equals(scopeNameCheck)){
- JSONObject el = new JSONObject();
- el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
- el.put(DATE, policy.getModifiedDate());
- el.put(VERSION, policy.getActiveVersion());
- el.put(SIZE, "");
- el.put(TYPE, "file");
- el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
- el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
- resultList.add(el);
- }
- }else if(!scopes.isEmpty() && scopes.contains(scopeNameValue)){
JSONObject el = new JSONObject();
- el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1));
+ el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator) + 1));
+ el.put(DATE, policy.getModifiedDate());
+ el.put(VERSION, policy.getActiveVersion());
+ el.put(SIZE, "");
+ el.put(TYPE, "file");
+ el.put(CREATED_BY, getUserName(policy.getCreatedBy()));
+ el.put(MODIFIED_BY, getUserName(policy.getModifiedBy()));
+ String roleType = Strings.isNullOrEmpty(roleByScope.get(scopeNameValue)) ?
+ roleByScope.get(ALLSCOPES) : roleByScope.get(scopeNameValue);
+ el.put(ROLETYPE, roleType);
+ resultList.add(el);
+ } else if (!scopes.isEmpty() && scopes.contains(scopeNameValue)) {
+ JSONObject el = new JSONObject();
+ el.put(NAME, policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator) + 1));
el.put(DATE, policy.getModifiedDate());
el.put(VERSION, policy.getActiveVersion());
el.put(SIZE, "");
@@ -774,48 +772,68 @@ public class PolicyManagerServlet extends HttpServlet {
}
}
- private String checkScope(List<JSONObject> resultList, String scopeName, PolicyEditorScopes scopeById) {
+ private List<Object> getDataByQueryFromController(final PolicyController controller, final String query,
+ final SimpleBindings params) {
+ final List<Object> activePolicies;
+ if (PolicyController.isjUnit()) {
+ activePolicies = controller.getDataByQuery(query, null);
+ } else {
+ activePolicies = controller.getDataByQuery(query, params);
+ }
+ return activePolicies;
+ }
+
+ private String checkScope(List<JSONObject> resultList, String scopeName, PolicyEditorScopes scopeById,
+ Map<String, String> roleByScope) {
String scope = scopeById.getScopeName();
- if(scope.contains(File.separator)){
- String targetScope = scope.substring(0, scope.lastIndexOf(File.separator));
- if(scopeName.contains(ESCAPE_BACKSLASH)){
- scopeName = scopeName.replace(ESCAPE_BACKSLASH, File.separator);
- }
- if(scope.contains(File.separator)){
- scope = scope.substring(targetScope.length()+1);
- if(scope.contains(File.separator)){
- scope = scope.substring(0, scope.indexOf(File.separator));
- }
+ if (!scope.contains(File.separator)) {
+ return scopeName;
+ }
+ String targetScope = scope.substring(0, scope.lastIndexOf(File.separator));
+ if (scopeName.contains(ESCAPE_BACKSLASH)) {
+ scopeName = scopeName.replace(ESCAPE_BACKSLASH, File.separator);
+ }
+ if (scope.contains(File.separator)) {
+ scope = scope.substring(targetScope.length() + 1);
+ if (scope.contains(File.separator)) {
+ scope = scope.substring(0, scope.indexOf(File.separator));
}
- if(scopeName.equalsIgnoreCase(targetScope)){
- JSONObject el = new JSONObject();
- el.put(NAME, scope);
- el.put(DATE, scopeById.getModifiedDate());
- el.put(SIZE, "");
- el.put(TYPE, "dir");
- el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName());
- el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName());
- resultList.add(el);
+ }
+ if (scopeName.equalsIgnoreCase(targetScope)) {
+ JSONObject el = new JSONObject();
+ el.put(NAME, scope);
+ el.put(DATE, scopeById.getModifiedDate());
+ el.put(SIZE, "");
+ el.put(TYPE, "dir");
+ el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName());
+ el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName());
+ String roleType = roleByScope.get(ALLSCOPES); // Set default role type to ALL_SCOPES
+ if (!Strings.isNullOrEmpty(roleByScope.get(scopeName))) {
+ roleType = roleByScope.get(scopeName);
+ } else if (!Strings.isNullOrEmpty(roleByScope.get(scopeName + File.separator + scope))) {
+ roleType = roleByScope.get(scopeName + File.separator + scope);
}
+ el.put(ROLETYPE, roleType);
+ resultList.add(el);
}
return scopeName;
}
- private String getUserName(String loginId){
+ private String getUserName(String loginId) {
PolicyController controller = getPolicyControllerInstance();
UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
- if(userInfo == null){
+ if (userInfo == null) {
return SUPERADMIN;
}
return userInfo.getUserName();
}
- //Rename Policy
+ // Rename Policy
private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException {
try {
return handlePolicyRename(params, request);
} catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Renaming Policy" + e);
return error(e.getMessage());
}
}
@@ -827,85 +845,84 @@ public class PolicyManagerServlet extends HttpServlet {
String userId = UserUtils.getUserSession(request).getOrgUserId();
String oldPath = params.getString("path");
String newPath = params.getString("newPath");
- oldPath = oldPath.substring(oldPath.indexOf('/')+1);
- newPath = newPath.substring(newPath.indexOf('/')+1);
+ oldPath = oldPath.substring(oldPath.indexOf('/') + 1);
+ newPath = newPath.substring(newPath.indexOf('/') + 1);
String checkValidation;
- if(oldPath.endsWith(".xml")){
+ if (oldPath.endsWith(".xml")) {
checkValidation = newPath.replace(".xml", "");
- checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf("."));
- checkValidation = checkValidation.substring(checkValidation.lastIndexOf(FORWARD_SLASH)+1);
- if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)){
+ checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1,
+ checkValidation.lastIndexOf('.'));
+ checkValidation = checkValidation.substring(checkValidation.lastIndexOf(FORWARD_SLASH) + 1);
+ if (!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)) {
return error("Policy Rename Failed. The Name contains special characters.");
}
JSONObject result = policyRename(oldPath, newPath, userId);
- if(!(Boolean)(result.getJSONObject(RESULT).get(SUCCESS))){
+ if (!(Boolean) (result.getJSONObject(RESULT).get(SUCCESS))) {
return result;
}
- }else{
+ } else {
String scopeName = oldPath;
String newScopeName = newPath;
- if(scopeName.contains(FORWARD_SLASH)){
+ if (scopeName.contains(FORWARD_SLASH)) {
scopeName = scopeName.replace(FORWARD_SLASH, File.separator);
newScopeName = newScopeName.replace(FORWARD_SLASH, File.separator);
}
- checkValidation = newScopeName.substring(newScopeName.lastIndexOf(File.separator)+1);
- if(scopeName.contains(BACKSLASH)){
+ checkValidation = newScopeName.substring(newScopeName.lastIndexOf(File.separator) + 1);
+ if (scopeName.contains(BACKSLASH)) {
scopeName = scopeName.replace(BACKSLASH, BACKSLASH_8TIMES);
newScopeName = newScopeName.replace(BACKSLASH, BACKSLASH_8TIMES);
}
- if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)){
+ if (!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)) {
return error("Scope Rename Failed. The Name contains special characters.");
}
PolicyController controller = getPolicyControllerInstance();
String query = "from PolicyVersion where POLICY_NAME like :scopeName";
- String scopeNamequery = FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME;
SimpleBindings pvParams = new SimpleBindings();
pvParams.put(SCOPE_NAME, scopeName + "%");
List<Object> activePolicies = controller.getDataByQuery(query, pvParams);
- List<Object> scopesList = controller.getDataByQuery(scopeNamequery, pvParams);
- for(Object object : activePolicies){
+ List<Object> scopesList = controller.getDataByQuery(FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME, pvParams);
+ for (Object object : activePolicies) {
PolicyVersion activeVersion = (PolicyVersion) object;
- String policyOldPath = activeVersion.getPolicyName().replace(File.separator, FORWARD_SLASH) + "." + activeVersion.getActiveVersion() + ".xml";
+ String policyOldPath = activeVersion.getPolicyName().replace(File.separator, FORWARD_SLASH) + "."
+ + activeVersion.getActiveVersion() + ".xml";
String policyNewPath = policyOldPath.replace(oldPath, newPath);
JSONObject result = policyRename(policyOldPath, policyNewPath, userId);
- if(!(Boolean)(result.getJSONObject("result").get(SUCCESS))){
+ if (!(Boolean) (result.getJSONObject("result").get(SUCCESS))) {
isActive = true;
policyActiveInPDP.add(policyOldPath);
String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf('/'));
scopeOfPolicyActiveInPDP.add(scope.replace(FORWARD_SLASH, File.separator));
}
}
- boolean rename = false;
- if(activePolicies.size() != policyActiveInPDP.size()){
- rename = true;
- }
-
- UserInfo userInfo = new UserInfo();
- userInfo.setUserLoginId(userId);
- if(policyActiveInPDP.isEmpty()){
+ boolean rename = activePolicies.size() != policyActiveInPDP.size();
+ if (policyActiveInPDP.isEmpty()) {
renameScope(scopesList, scopeName, newScopeName, controller);
- }else if(rename){
+ } else if (rename) {
renameScope(scopesList, scopeName, newScopeName, controller);
- for(String scope : scopeOfPolicyActiveInPDP){
+ UserInfo userInfo = new UserInfo();
+ userInfo.setUserLoginId(userId);
+ scopeOfPolicyActiveInPDP.forEach(scope -> {
PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes();
editorScopeEntity.setScopeName(scope.replace(BACKSLASH, BACKSLASH_8TIMES));
editorScopeEntity.setUserCreatedBy(userInfo);
editorScopeEntity.setUserModifiedBy(userInfo);
controller.saveData(editorScopeEntity);
- }
+ });
}
- if(isActive){
- return error("The Following policies rename failed. Since they are active in PDP Groups" +policyActiveInPDP);
+ if (isActive) {
+ return error("The Following policies rename failed. Since they are active in PDP Groups"
+ + policyActiveInPDP);
}
}
return success();
}
- private void renameScope(List<Object> scopesList, String inScopeName, String newScopeName, PolicyController controller){
- for(Object object : scopesList){
+ private void renameScope(List<Object> scopesList, String inScopeName, String newScopeName,
+ PolicyController controller) {
+ for (Object object : scopesList) {
PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object;
String scopeName = inScopeName;
- if(scopeName.contains(BACKSLASH_8TIMES)){
+ if (scopeName.contains(BACKSLASH_8TIMES)) {
scopeName = scopeName.replace(BACKSLASH_8TIMES, File.separator);
newScopeName = newScopeName.replace(BACKSLASH_8TIMES, File.separator);
}
@@ -921,52 +938,56 @@ public class PolicyManagerServlet extends HttpServlet {
PolicyController controller = getPolicyControllerInstance();
String policyVersionName = newPath.replace(".xml", "");
- String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')).replace(FORWARD_SLASH, File.separator);
+ String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.'))
+ .replace(FORWARD_SLASH, File.separator);
String oldpolicyVersionName = oldPath.replace(".xml", "");
- String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf('.')).replace(FORWARD_SLASH, File.separator);
+ String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf('.'))
+ .replace(FORWARD_SLASH, File.separator);
String newpolicyName = newPath.replace("/", ".");
String[] newPolicySplit = modifyPolicyName(newPath);
String[] oldPolicySplit = modifyPolicyName(oldPath);
- //Check PolicyEntity table with newPolicy Name
+ // Check PolicyEntity table with newPolicy Name
String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
SimpleBindings policyParams = new SimpleBindings();
policyParams.put("newPolicySplit_1", newPolicySplit[1]);
policyParams.put("newPolicySplit_0", newPolicySplit[0]);
List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
- if(!queryData.isEmpty()){
+ if (!queryData.isEmpty()) {
return error("Policy rename failed. Since, the policy with same name already exists.");
}
- //Query the Policy Entity with oldPolicy Name
+ // Query the Policy Entity with oldPolicy Name
String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf('.'));
- String oldpolicyEntityquery = "FROM PolicyEntity where policyName like :policyEntityCheck and scope = :oldPolicySplit_0";
+ String oldPolicyEntityQuery = "FROM PolicyEntity where policyName like :policyEntityCheck and scope = "
+ + ":oldPolicySplit_0";
SimpleBindings params = new SimpleBindings();
params.put("policyEntityCheck", policyEntityCheck + "%");
params.put("oldPolicySplit_0", oldPolicySplit[0]);
- List<Object> oldEntityData = controller.getDataByQuery(oldpolicyEntityquery, params);
- if(oldEntityData.isEmpty()){
- return error("Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin.");
+ List<Object> oldEntityData = controller.getDataByQuery(oldPolicyEntityQuery, params);
+ if (oldEntityData.isEmpty()) {
+ return error(
+ "Policy rename failed due to policy not able to retrieve from database. Please, contact super-admin.");
}
StringBuilder groupQuery = new StringBuilder();
groupQuery.append("FROM PolicyGroupEntity where (");
SimpleBindings geParams = new SimpleBindings();
- for(int i=0; i<oldEntityData.size(); i++){
+ for (int i = 0; i < oldEntityData.size(); i++) {
entity = (PolicyEntity) oldEntityData.get(i);
- if(i == 0){
+ if (i == 0) {
groupQuery.append("policyid = :policyId");
geParams.put("policyId", entity.getPolicyId());
- }else{
+ } else {
groupQuery.append(" or policyid = :policyId").append(i);
geParams.put("policyId" + i, entity.getPolicyId());
}
}
groupQuery.append(")");
List<Object> groupEntityData = controller.getDataByQuery(groupQuery.toString(), geParams);
- if(! groupEntityData.isEmpty()){
+ if (!groupEntityData.isEmpty()) {
return error("Policy rename failed. Since the policy or its version is active in PDP Groups.");
}
for (Object anOldEntityData : oldEntityData) {
@@ -975,13 +996,13 @@ public class PolicyManagerServlet extends HttpServlet {
checkEntityName = checkEntityName.substring(0, checkEntityName.lastIndexOf('.'));
String originalPolicyName = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator) + 1);
if (checkEntityName.equals(originalPolicyName)) {
- checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0], newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
+ checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0], newPolicySplit[1], oldPolicySplit[0],
+ oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId);
}
}
-
return success();
} catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e);
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Renaming Policy" + e);
return error(e.getMessage());
}
}
@@ -992,80 +1013,92 @@ public class PolicyManagerServlet extends HttpServlet {
private String[] modifyPolicyName(String separator, String pathName) {
String policyName = pathName.replace(separator, ".");
- if(policyName.contains(CONFIG2)){
+ if (policyName.contains(CONFIG2)) {
policyName = policyName.replace(CONFIG, CONFIG1);
- }else if(policyName.contains(ACTION2)){
+ } else if (policyName.contains(ACTION2)) {
policyName = policyName.replace(ACTION, ACTION1);
- }else if(policyName.contains(DECISION2)){
+ } else if (policyName.contains(DECISION2)) {
policyName = policyName.replace(DECISION, DECISION1);
}
return policyName.split(":");
}
- private void checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, String oldScope, String removeoldPolicyExtension,
- String policyName, String newpolicyName, String oldpolicyName, String userId) {
+ private void checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removeNewPolicyExtension,
+ String oldScope, String removeOldPolicyExtension, String policyName, String newPolicyName,
+ String oldPolicyName, String userId) {
try {
ConfigurationDataEntity configEntity = entity.getConfigurationData();
ActionBodyEntity actionEntity = entity.getActionBodyEntity();
PolicyController controller = getPolicyControllerInstance();
- String oldPolicyNameWithoutExtension = removeoldPolicyExtension;
- String newPolicyNameWithoutExtension = removenewPolicyExtension;
- if(removeoldPolicyExtension.endsWith(".xml")){
- oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf('.'));
- newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf('.'));
+ String oldPolicyNameWithoutExtension = removeOldPolicyExtension;
+ String newPolicyNameWithoutExtension = removeNewPolicyExtension;
+ if (removeOldPolicyExtension.endsWith(".xml")) {
+ oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0,
+ oldPolicyNameWithoutExtension.indexOf('.'));
+ newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0,
+ newPolicyNameWithoutExtension.indexOf('.'));
}
- entity.setPolicyName(entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
- entity.setPolicyData(entity.getPolicyData().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
+ entity.setPolicyName(
+ entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
+ entity.setPolicyData(entity.getPolicyData().replace(oldScope + "." + oldPolicyNameWithoutExtension,
+ newScope + "." + newPolicyNameWithoutExtension));
entity.setScope(newScope);
entity.setModifiedBy(userId);
String oldConfigurationName = null;
String newConfigurationName = null;
- if(newpolicyName.contains(CONFIG2)){
+ if (newPolicyName.contains(CONFIG2)) {
oldConfigurationName = configEntity.getConfigurationName();
- configEntity.setConfigurationName(configEntity.getConfigurationName().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
+ configEntity.setConfigurationName(
+ configEntity.getConfigurationName().replace(oldScope + "." + oldPolicyNameWithoutExtension,
+ newScope + "." + newPolicyNameWithoutExtension));
controller.updateData(configEntity);
newConfigurationName = configEntity.getConfigurationName();
File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName);
- if(file.exists()){
- File renamefile = new File(PolicyController.getConfigHome() + File.separator + newConfigurationName);
- file.renameTo(renamefile);
+ if (file.exists()) {
+ File renameFile = new File(
+ PolicyController.getConfigHome() + File.separator + newConfigurationName);
+ file.renameTo(renameFile);
}
- }else if(newpolicyName.contains(ACTION2)){
+ } else if (newPolicyName.contains(ACTION2)) {
oldConfigurationName = actionEntity.getActionBodyName();
- actionEntity.setActionBody(actionEntity.getActionBody().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
+ actionEntity.setActionBody(
+ actionEntity.getActionBody().replace(oldScope + "." + oldPolicyNameWithoutExtension,
+ newScope + "." + newPolicyNameWithoutExtension));
controller.updateData(actionEntity);
newConfigurationName = actionEntity.getActionBodyName();
File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName);
- if(file.exists()){
- File renamefile = new File(PolicyController.getActionHome() + File.separator + newConfigurationName);
- file.renameTo(renamefile);
+ if (file.exists()) {
+ File renameFile = new File(
+ PolicyController.getActionHome() + File.separator + newConfigurationName);
+ file.renameTo(renameFile);
}
}
controller.updateData(entity);
PolicyRestController restController = new PolicyRestController();
restController.notifyOtherPAPSToUpdateConfigurations("rename", newConfigurationName, oldConfigurationName);
- PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldpolicyName);
+ PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName",
+ oldPolicyName);
versionEntity.setPolicyName(policyName);
versionEntity.setModifiedBy(userId);
controller.updateData(versionEntity);
- String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator)+1);
- String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1);
- if(movePolicyCheck.equals(moveOldPolicyCheck)){
- controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move");
- }else{
- controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename");
+ String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator) + 1);
+ String moveOldPolicyCheck = oldPolicyName.substring(oldPolicyName.lastIndexOf(File.separator) + 1);
+ if (movePolicyCheck.equals(moveOldPolicyCheck)) {
+ controller.watchPolicyFunction(versionEntity, oldPolicyName, "Move");
+ } else {
+ controller.watchPolicyFunction(versionEntity, oldPolicyName, "Rename");
}
} catch (Exception e) {
- LOGGER.error(EXCEPTION_OCCURED +e);
+ LOGGER.error(EXCEPTION_OCCURED + e);
throw e;
}
}
private void cloneRecord(String newpolicyName, String oldScope, String inRemoveoldPolicyExtension, String newScope,
- String inRemovenewPolicyExtension, PolicyEntity entity, String userId) throws IOException{
+ String inRemovenewPolicyExtension, PolicyEntity entity, String userId) throws IOException {
String queryEntityName;
PolicyController controller = getPolicyControllerInstance();
PolicyEntity cloneEntity = new PolicyEntity();
@@ -1074,14 +1107,16 @@ public class PolicyManagerServlet extends HttpServlet {
String removenewPolicyExtension = inRemovenewPolicyExtension;
removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
removenewPolicyExtension = removenewPolicyExtension.replace(".xml", "");
- cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope+"."+removeoldPolicyExtension, newScope+"."+removenewPolicyExtension));
+ cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope + "." + removeoldPolicyExtension,
+ newScope + "." + removenewPolicyExtension));
cloneEntity.setScope(entity.getScope());
String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", "");
String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", "");
String newConfigurationName = null;
- if(newpolicyName.contains(CONFIG2)){
+ if (newpolicyName.contains(CONFIG2)) {
ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity();
- configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
+ configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName()
+ .replace(oldScope + "." + oldConfigRemoveExtension, newScope + "." + newConfigRemoveExtension));
queryEntityName = configurationDataEntity.getConfigurationName();
configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody());
configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType());
@@ -1089,33 +1124,38 @@ public class PolicyManagerServlet extends HttpServlet {
configurationDataEntity.setCreatedBy(userId);
configurationDataEntity.setModifiedBy(userId);
controller.saveData(configurationDataEntity);
- ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
+ ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller
+ .getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
cloneEntity.setConfigurationData(configEntiy);
newConfigurationName = configEntiy.getConfigurationName();
- try (FileWriter fw = new FileWriter(PolicyController.getConfigHome() + File.separator + newConfigurationName);
- BufferedWriter bw = new BufferedWriter(fw)){
+ try (FileWriter fw = new FileWriter(
+ PolicyController.getConfigHome() + File.separator + newConfigurationName);
+ BufferedWriter bw = new BufferedWriter(fw)) {
bw.write(configEntiy.getConfigBody());
} catch (IOException e) {
- LOGGER.error("Exception Occured While cloning the configuration file"+e);
+ LOGGER.error("Exception Occured While cloning the configuration file" + e);
throw e;
}
- }else if(newpolicyName.contains(ACTION2)){
+ } else if (newpolicyName.contains(ACTION2)) {
ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
- actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
+ actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName()
+ .replace(oldScope + "." + oldConfigRemoveExtension, newScope + "." + newConfigRemoveExtension));
queryEntityName = actionBodyEntity.getActionBodyName();
actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody());
actionBodyEntity.setDeleted(false);
actionBodyEntity.setCreatedBy(userId);
actionBodyEntity.setModifiedBy(userId);
controller.saveData(actionBodyEntity);
- ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class, "actionBodyName", queryEntityName);
+ ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class,
+ "actionBodyName", queryEntityName);
cloneEntity.setActionBodyEntity(actionEntiy);
newConfigurationName = actionEntiy.getActionBodyName();
- try (FileWriter fw = new FileWriter(PolicyController.getActionHome() + File.separator + newConfigurationName);
- BufferedWriter bw = new BufferedWriter(fw)){
+ try (FileWriter fw = new FileWriter(
+ PolicyController.getActionHome() + File.separator + newConfigurationName);
+ BufferedWriter bw = new BufferedWriter(fw)) {
bw.write(actionEntiy.getActionBody());
} catch (IOException e) {
- LOGGER.error("Exception Occured While cloning the configuration file"+e);
+ LOGGER.error("Exception Occured While cloning the configuration file" + e);
throw e;
}
}
@@ -1125,83 +1165,81 @@ public class PolicyManagerServlet extends HttpServlet {
cloneEntity.setModifiedBy(userId);
controller.saveData(cloneEntity);
- //Notify others paps regarding clone policy.
+ // Notify others paps regarding clone policy.
PolicyRestController restController = new PolicyRestController();
restController.notifyOtherPAPSToUpdateConfigurations("clonePolicy", newConfigurationName, null);
}
- //Clone the Policy
+ // Clone the Policy
private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
try {
String userId = UserUtils.getUserSession(request).getOrgUserId();
String oldPath = params.getString("path");
String newPath = params.getString("newPath");
- oldPath = oldPath.substring(oldPath.indexOf('/')+1);
- newPath = newPath.substring(newPath.indexOf('/')+1);
+ oldPath = oldPath.substring(oldPath.indexOf('/') + 1);
+ newPath = newPath.substring(newPath.indexOf('/') + 1);
String policyVersionName = newPath.replace(".xml", "");
- String version = policyVersionName.substring(policyVersionName.indexOf('.')+1);
- String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.')).replace(FORWARD_SLASH, File.separator);
+ String version = policyVersionName.substring(policyVersionName.indexOf('.') + 1);
+ String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf('.'))
+ .replace(FORWARD_SLASH, File.separator);
- String newpolicyName = newPath.replace(FORWARD_SLASH, ".");
+ String newPolicyName = newPath.replace(FORWARD_SLASH, ".");
- String orignalPolicyName = oldPath.replace(FORWARD_SLASH, ".");
+ String originalPolicyName = oldPath.replace(FORWARD_SLASH, ".");
- String newPolicyCheck = newpolicyName;
- if(newPolicyCheck.contains(CONFIG2)){
+ String newPolicyCheck = newPolicyName;
+ if (newPolicyCheck.contains(CONFIG2)) {
newPolicyCheck = newPolicyCheck.replace(CONFIG, CONFIG1);
- }else if(newPolicyCheck.contains(ACTION2)){
+ } else if (newPolicyCheck.contains(ACTION2)) {
newPolicyCheck = newPolicyCheck.replace(ACTION, ACTION1);
- }else if(newPolicyCheck.contains(DECISION2)){
+ } else if (newPolicyCheck.contains(DECISION2)) {
newPolicyCheck = newPolicyCheck.replace(DECISION, DECISION1);
}
- if(!newPolicyCheck.contains(":")){
+ if (!newPolicyCheck.contains(":")) {
return error("Policy Clone Failed. The Name contains special characters.");
}
String[] newPolicySplit = newPolicyCheck.split(":");
String checkValidation = newPolicySplit[1].replace(".xml", "");
- checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1, checkValidation.lastIndexOf("."));
- if(!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)){
+ checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1,
+ checkValidation.lastIndexOf('.'));
+ if (!PolicyUtils.policySpecialCharValidator(checkValidation).contains(SUCCESS)) {
return error("Policy Clone Failed. The Name contains special characters.");
}
- String[] oldPolicySplit = modifyPolicyName(orignalPolicyName);
+ String[] oldPolicySplit = modifyPolicyName(originalPolicyName);
PolicyController controller = getPolicyControllerInstance();
PolicyEntity entity = null;
boolean success = false;
- //Check PolicyEntity table with newPolicy Name
+ // Check PolicyEntity table with newPolicy Name
String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
SimpleBindings policyParams = new SimpleBindings();
policyParams.put("newPolicySplit_1", newPolicySplit[1]);
policyParams.put("newPolicySplit_0", newPolicySplit[0]);
List<Object> queryData = controller.getDataByQuery(policyEntityquery, policyParams);
- if(!queryData.isEmpty()){
+ if (!queryData.isEmpty()) {
return error("Policy already exists with same name");
}
- //Query the Policy Entity with oldPolicy Name
+ // Query the Policy Entity with oldPolicy Name
policyEntityquery = "FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0";
SimpleBindings peParams = new SimpleBindings();
peParams.put("oldPolicySplit_1", oldPolicySplit[1]);
peParams.put("oldPolicySplit_0", oldPolicySplit[0]);
- if(PolicyController.isjUnit()){
- queryData = controller.getDataByQuery(policyEntityquery, null);
- }else{
- queryData = controller.getDataByQuery(policyEntityquery, peParams);
- }
- if(!queryData.isEmpty()){
+ queryData = getDataByQueryFromController(controller, policyEntityquery, peParams);
+ if (!queryData.isEmpty()) {
entity = (PolicyEntity) queryData.get(0);
}
- if(entity != null){
- cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId);
+ if (entity != null) {
+ cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0],
+ newPolicySplit[1], entity, userId);
success = true;
}
-
- if(success){
+ if (success) {
PolicyVersion entityItem = new PolicyVersion();
entityItem.setActiveVersion(Integer.parseInt(version));
entityItem.setHigherVersion(Integer.parseInt(version));
@@ -1211,9 +1249,7 @@ public class PolicyManagerServlet extends HttpServlet {
entityItem.setModifiedDate(new Date());
controller.saveData(entityItem);
}
-
- LOGGER.debug("copy from: {} to: {}" + oldPath +newPath);
-
+ LOGGER.debug("copy from: {} to: {}" + oldPath + newPath);
return success();
} catch (Exception e) {
LOGGER.error("copy", e);
@@ -1221,7 +1257,7 @@ public class PolicyManagerServlet extends HttpServlet {
}
}
- //Delete Policy or Scope Functionality
+ // Delete Policy or Scope Functionality
private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
PolicyController controller = getPolicyControllerInstance();
PolicyRestController restController = new PolicyRestController();
@@ -1231,81 +1267,80 @@ public class PolicyManagerServlet extends HttpServlet {
String userId = UserUtils.getUserSession(request).getOrgUserId();
String deleteVersion = "";
String path = params.getString("path");
- LOGGER.debug("delete {}" +path);
- if(params.has("deleteVersion")){
- deleteVersion = params.getString("deleteVersion");
+ LOGGER.debug("delete {}" + path);
+ if (params.has("deleteVersion")) {
+ deleteVersion = params.getString("deleteVersion");
}
- path = path.substring(path.indexOf('/')+1);
+ path = path.substring(path.indexOf('/') + 1);
String policyNamewithExtension = path.replace(FORWARD_SLASH, File.separator);
String policyVersionName = policyNamewithExtension.replace(".xml", "");
String query;
SimpleBindings policyParams = new SimpleBindings();
- if(path.endsWith(".xml")){
+ if (path.endsWith(".xml")) {
policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf('.'));
String[] split = modifyPolicyName(File.separator, policyNamewithoutExtension);
query = "FROM PolicyEntity where policyName like :split_1 and scope = :split_0";
policyParams.put(SPLIT_1, split[1] + "%");
policyParams.put(SPLIT_0, split[0]);
- }else{
+ } else {
policyNamewithoutExtension = path.replace(File.separator, ".");
- query = "FROM PolicyEntity where scope like :policyNamewithoutExtension";
- policyParams.put("policyNamewithoutExtension", policyNamewithoutExtension + "%");
+ query = "FROM PolicyEntity where scope like :policyNamewithoutExtension or scope = :exactScope";
+ policyParams.put("policyNamewithoutExtension", policyNamewithoutExtension + ".%");
+ policyParams.put("exactScope", policyNamewithoutExtension);
}
- List<Object> policyEntityobjects = controller.getDataByQuery(query, policyParams);
+ List<Object> policyEntityObjects = controller.getDataByQuery(query, policyParams);
String activePolicyName = null;
boolean pdpCheck = false;
- if(path.endsWith(".xml")){
+ if (path.endsWith(".xml")) {
policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator);
- int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf('.')+1));
- if("ALL".equals(deleteVersion)){
- if(!policyEntityobjects.isEmpty()){
- for(Object object : policyEntityobjects){
+ int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf('.') + 1));
+ if ("ALL".equals(deleteVersion)) {
+ if (!policyEntityObjects.isEmpty()) {
+ for (Object object : policyEntityObjects) {
policyEntity = (PolicyEntity) object;
- String groupEntityquery = "from PolicyGroupEntity where policyid ='"+policyEntity.getPolicyId()+"'";
+ String groupEntityquery = "from PolicyGroupEntity where policyid ='"
+ + policyEntity.getPolicyId() + "'";
SimpleBindings pgeParams = new SimpleBindings();
List<Object> groupobject = controller.getDataByQuery(groupEntityquery, pgeParams);
- if(!groupobject.isEmpty()){
+ if (!groupobject.isEmpty()) {
pdpCheck = true;
- activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName();
- }else{
- //Delete the entity from Elastic Search Database
- String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
- restController.deleteElasticData(searchFileName);
- //Delete the entity from Policy Entity table
- controller.deleteData(policyEntity);
- if(policyNamewithoutExtension.contains(CONFIG2)){
- Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
- controller.deleteData(policyEntity.getConfigurationData());
- restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, policyEntity.getConfigurationData().getConfigurationName());
- }else if(policyNamewithoutExtension.contains(ACTION2)){
- Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
- controller.deleteData(policyEntity.getActionBodyEntity());
- restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, policyEntity.getActionBodyEntity().getActionBodyName());
- }
+ activePolicyName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
+ } else {
+ deleteEntityFromEsAndPolicyEntityTable(controller, restController, policyEntity,
+ policyNamewithoutExtension);
}
}
}
- //Policy Notification
+ // Policy Notification
PolicyVersion versionEntity = new PolicyVersion();
versionEntity.setPolicyName(policyNamewithoutExtension);
versionEntity.setModifiedBy(userId);
controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll");
- if(pdpCheck){
- //Delete from policyVersion table
+ if (pdpCheck) {
+ // Delete from policyVersion table
String getActivePDPPolicyVersion = activePolicyName.replace(".xml", "");
- getActivePDPPolicyVersion = getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf('.')+1);
- String policyVersionQuery = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION +getActivePDPPolicyVersion+"' , highest_version='"+getActivePDPPolicyVersion+"' where policy_name ='" +policyNamewithoutExtension.replace(BACKSLASH, ESCAPE_BACKSLASH)+"' and id >0";
+ getActivePDPPolicyVersion = getActivePDPPolicyVersion
+ .substring(getActivePDPPolicyVersion.lastIndexOf('.') + 1);
+ String policyVersionQuery = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION + getActivePDPPolicyVersion
+ + "' , highest_version='" + getActivePDPPolicyVersion + "' where policy_name ='"
+ + policyNamewithoutExtension.replace(BACKSLASH, ESCAPE_BACKSLASH) + "' and id >0";
controller.executeQuery(policyVersionQuery);
- return error("Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "+activePolicyName);
- }else{
- //No Active Policy in PDP. So, deleting all entries from policyVersion table
- String policyVersionQuery = DELETE_POLICY_VERSION_WHERE_POLICY_NAME +policyNamewithoutExtension.replace(BACKSLASH, ESCAPE_BACKSLASH)+"' and id >0";
+ return error(
+ "Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "
+ + activePolicyName);
+ } else {
+ // No Active Policy in PDP. So, deleting all entries from policyVersion table
+ String policyVersionQuery = DELETE_POLICY_VERSION_WHERE_POLICY_NAME
+ + policyNamewithoutExtension.replace(BACKSLASH, ESCAPE_BACKSLASH) + "' and id >0";
controller.executeQuery(policyVersionQuery);
}
- }else if("CURRENT".equals(deleteVersion)){
- String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1);
- String currentVersionScope = policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator)).replace(File.separator, ".");
+ } else if ("CURRENT".equals(deleteVersion)) {
+ String currentVersionPolicyName = policyNamewithExtension
+ .substring(policyNamewithExtension.lastIndexOf(File.separator) + 1);
+ String currentVersionScope = policyNamewithExtension
+ .substring(0, policyNamewithExtension.lastIndexOf(File.separator))
+ .replace(File.separator, ".");
query = "FROM PolicyEntity where policyName = :currentVersionPolicyName and scope = :currentVersionScope";
SimpleBindings peParams = new SimpleBindings();
@@ -1313,10 +1348,10 @@ public class PolicyManagerServlet extends HttpServlet {
peParams.put("currentVersionScope", currentVersionScope);
List<Object> policyEntitys = controller.getDataByQuery(query, peParams);
- if(!policyEntitys.isEmpty()){
+ if (!policyEntitys.isEmpty()) {
policyEntity = (PolicyEntity) policyEntitys.get(0);
}
- if(policyEntity == null){
+ if (policyEntity == null) {
return success();
}
@@ -1324,39 +1359,30 @@ public class PolicyManagerServlet extends HttpServlet {
SimpleBindings geParams = new SimpleBindings();
geParams.put("policyEntityId", policyEntity.getPolicyId());
List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
- if(!groupobject.isEmpty()){
- return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'");
+ if (!groupobject.isEmpty()) {
+ return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"
+ + policyEntity.getScope() + "." + policyEntity.getPolicyName() + "'");
}
- //Delete the entity from Elastic Search Database
- String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
- restController.deleteElasticData(searchFileName);
- //Delete the entity from Policy Entity table
- controller.deleteData(policyEntity);
- if(policyNamewithoutExtension.contains(CONFIG2)){
- Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
- controller.deleteData(policyEntity.getConfigurationData());
- restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, policyEntity.getConfigurationData().getConfigurationName());
- }else if(policyNamewithoutExtension.contains(ACTION2)){
- Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
- controller.deleteData(policyEntity.getActionBodyEntity());
- restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, policyEntity.getActionBodyEntity().getActionBodyName());
- }
+ // Delete the entity from Elastic Search Database
+ deleteEntityFromEsAndPolicyEntityTable(controller, restController, policyEntity,
+ policyNamewithoutExtension);
- if(version > 1){
+ if (version > 1) {
int highestVersion = 0;
- if(!policyEntityobjects.isEmpty()){
- for(Object object : policyEntityobjects){
+ if (!policyEntityObjects.isEmpty()) {
+ for (Object object : policyEntityObjects) {
policyEntity = (PolicyEntity) object;
String policyEntityName = policyEntity.getPolicyName().replace(".xml", "");
- int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf('.')+1));
- if(policyEntityVersion > highestVersion && policyEntityVersion != version){
+ int policyEntityVersion = Integer
+ .parseInt(policyEntityName.substring(policyEntityName.lastIndexOf('.') + 1));
+ if (policyEntityVersion > highestVersion && policyEntityVersion != version) {
highestVersion = policyEntityVersion;
}
}
}
- //Policy Notification
+ // Policy Notification
PolicyVersion entity = new PolicyVersion();
entity.setPolicyName(policyNamewithoutExtension);
entity.setActiveVersion(highestVersion);
@@ -1364,78 +1390,91 @@ public class PolicyManagerServlet extends HttpServlet {
controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne");
String updatequery;
- if(highestVersion != 0){
- updatequery = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION +highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"'";
- }else{
- updatequery = DELETE_POLICY_VERSION_WHERE_POLICY_NAME +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
+ if (highestVersion != 0) {
+ updatequery = UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION + highestVersion
+ + "' , highest_version='" + highestVersion + "' where policy_name ='"
+ + policyNamewithoutExtension.replace("\\", "\\\\") + "'";
+ } else {
+ updatequery = DELETE_POLICY_VERSION_WHERE_POLICY_NAME
+ + policyNamewithoutExtension.replace("\\", "\\\\") + "' and id >0";
}
controller.executeQuery(updatequery);
- }else{
- String policyVersionQuery = DELETE_POLICY_VERSION_WHERE_POLICY_NAME +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0";
+ } else {
+ String policyVersionQuery = DELETE_POLICY_VERSION_WHERE_POLICY_NAME
+ + policyNamewithoutExtension.replace("\\", "\\\\") + "' and id >0";
controller.executeQuery(policyVersionQuery);
}
}
- }else{
+ } else {
List<String> activePoliciesInPDP = new ArrayList<>();
- if(policyEntityobjects.isEmpty()){
- String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace(BACKSLASH, ESCAPE_BACKSLASH)+PERCENT_AND_ID_GT_0;
+ if (policyEntityObjects.isEmpty()) {
+ String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"
+ + path.replace(BACKSLASH, ESCAPE_BACKSLASH) + PERCENT_AND_ID_GT_0;
controller.executeQuery(policyScopeQuery);
return success();
}
- for(Object object : policyEntityobjects){
+ for (Object object : policyEntityObjects) {
policyEntity = (PolicyEntity) object;
- String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId";
+ String groupEntityQuery = "from PolicyGroupEntity where policyid = :policyEntityId";
SimpleBindings geParams = new SimpleBindings();
geParams.put("policyEntityId", policyEntity.getPolicyId());
- List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
- if(!groupobject.isEmpty()){
+ List<Object> groupobject = controller.getDataByQuery(groupEntityQuery, geParams);
+ if (!groupobject.isEmpty()) {
pdpCheck = true;
- activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName());
- }else{
- //Delete the entity from Elastic Search Database
+ activePoliciesInPDP.add(policyEntity.getScope() + "." + policyEntity.getPolicyName());
+ } else {
+ // Delete the entity from Elastic Search Database
String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
restController.deleteElasticData(searchFileName);
- //Delete the entity from Policy Entity table
+ // Delete the entity from Policy Entity table
controller.deleteData(policyEntity);
policyNamewithoutExtension = policyEntity.getPolicyName();
- if(policyNamewithoutExtension.contains(CONFIG2)){
- Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator + policyEntity.getConfigurationData().getConfigurationName()));
+ if (policyNamewithoutExtension.contains(CONFIG2)) {
+ Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator
+ + policyEntity.getConfigurationData().getConfigurationName()));
controller.deleteData(policyEntity.getConfigurationData());
- restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, policyEntity.getConfigurationData().getConfigurationName());
- }else if(policyNamewithoutExtension.contains(ACTION2)){
- Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator + policyEntity.getActionBodyEntity().getActionBodyName()));
+ restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null,
+ policyEntity.getConfigurationData().getConfigurationName());
+ } else if (policyNamewithoutExtension.contains(ACTION2)) {
+ Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator
+ + policyEntity.getActionBodyEntity().getActionBodyName()));
controller.deleteData(policyEntity.getActionBodyEntity());
- restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null, policyEntity.getActionBodyEntity().getActionBodyName());
+ restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null,
+ policyEntity.getActionBodyEntity().getActionBodyName());
}
}
}
- //Delete from policyVersion and policyEditor Scope table
- String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace(BACKSLASH, ESCAPE_BACKSLASH)+PERCENT_AND_ID_GT_0;
+ // Delete from policyVersion and policyEditor Scope table
+ String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"
+ + path.replace(BACKSLASH, ESCAPE_BACKSLASH) + File.separator + PERCENT_AND_ID_GT_0;
controller.executeQuery(policyVersionQuery);
- //Policy Notification
+ // Policy Notification
PolicyVersion entity = new PolicyVersion();
entity.setPolicyName(path);
entity.setModifiedBy(userId);
controller.watchPolicyFunction(entity, path, "DeleteScope");
- if(pdpCheck){
- //Add Active Policies List to PolicyVersionTable
+ if (pdpCheck) {
+ // Add Active Policies List to PolicyVersionTable
for (String anActivePoliciesInPDP : activePoliciesInPDP) {
String activePDPPolicyName = anActivePoliciesInPDP.replace(".xml", "");
- int activePDPPolicyVersion = Integer.parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf('.') + 1));
- activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf('.')).replace(".", File.separator);
- PolicyVersion insertactivePDPVersion = new PolicyVersion();
- insertactivePDPVersion.setPolicyName(activePDPPolicyName);
- insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion);
- insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion);
- insertactivePDPVersion.setCreatedBy(userId);
- insertactivePDPVersion.setModifiedBy(userId);
- controller.saveData(insertactivePDPVersion);
+ int activePDPPolicyVersion = Integer
+ .parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf('.') + 1));
+ activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf('.'))
+ .replace(".", File.separator);
+ PolicyVersion insertActivePDPVersion = new PolicyVersion();
+ insertActivePDPVersion.setPolicyName(activePDPPolicyName);
+ insertActivePDPVersion.setHigherVersion(activePDPPolicyVersion);
+ insertActivePDPVersion.setActiveVersion(activePDPPolicyVersion);
+ insertActivePDPVersion.setCreatedBy(userId);
+ insertActivePDPVersion.setModifiedBy(userId);
+ controller.saveData(insertActivePDPVersion);
}
-
- return error("All the Policies has been deleted in Scope. Except the following list of Policies:"+activePoliciesInPDP);
- }else{
- String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace(BACKSLASH, ESCAPE_BACKSLASH)+PERCENT_AND_ID_GT_0;
+ return error("All the Policies has been deleted in Scope. Except the following list of Policies:"
+ + activePoliciesInPDP);
+ } else {
+ String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"
+ + path.replace(BACKSLASH, ESCAPE_BACKSLASH) + PERCENT_AND_ID_GT_0;
controller.executeQuery(policyScopeQuery);
}
@@ -1447,14 +1486,37 @@ public class PolicyManagerServlet extends HttpServlet {
}
}
- //Edit the Policy
+ private void deleteEntityFromEsAndPolicyEntityTable(final PolicyController controller,
+ final PolicyRestController restController, final PolicyEntity policyEntity,
+ final String policyNamewithoutExtension) throws IOException {
+ // Delete the entity from Elastic Search Database
+ String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
+ restController.deleteElasticData(searchFileName);
+ // Delete the entity from Policy Entity table
+ controller.deleteData(policyEntity);
+ if (policyNamewithoutExtension.contains(CONFIG2)) {
+ Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator
+ + policyEntity.getConfigurationData().getConfigurationName()));
+ controller.deleteData(policyEntity.getConfigurationData());
+ restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null,
+ policyEntity.getConfigurationData().getConfigurationName());
+ } else if (policyNamewithoutExtension.contains(ACTION2)) {
+ Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator
+ + policyEntity.getActionBodyEntity().getActionBodyName()));
+ controller.deleteData(policyEntity.getActionBodyEntity());
+ restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null,
+ policyEntity.getActionBodyEntity().getActionBodyName());
+ }
+ }
+
+ // Edit the Policy
private JSONObject editFile(JSONObject params) throws ServletException {
// get content
try {
PolicyController controller = getPolicyControllerInstance();
String mode = params.getString("mode");
String path = params.getString("path");
- LOGGER.debug("editFile path: {}"+ path);
+ LOGGER.debug("editFile path: {}" + path);
String domain = path.substring(1, path.lastIndexOf('/'));
domain = domain.replace(FORWARD_SLASH, ".");
@@ -1468,24 +1530,18 @@ public class PolicyManagerServlet extends HttpServlet {
SimpleBindings peParams = new SimpleBindings();
peParams.put(SPLIT_1, split[1]);
peParams.put(SPLIT_0, split[0]);
- List<Object> queryData;
- if(PolicyController.isjUnit()){
- queryData = controller.getDataByQuery(query, null);
- }else{
- queryData = controller.getDataByQuery(query, peParams);
- }
+ List<Object> queryData = getDataByQueryFromController(controller, query, peParams);
PolicyEntity entity = (PolicyEntity) queryData.get(0);
InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
-
Object policy = XACMLPolicyScanner.readPolicy(stream);
- PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
+ PolicyRestAdapter policyAdapter = new PolicyRestAdapter();
policyAdapter.setData(policy);
- if("viewPolicy".equalsIgnoreCase(mode)){
+ if ("viewPolicy".equalsIgnoreCase(mode)) {
policyAdapter.setReadOnly(true);
policyAdapter.setEditPolicy(false);
- }else{
+ } else {
policyAdapter.setReadOnly(false);
policyAdapter.setEditPolicy(true);
}
@@ -1494,10 +1550,10 @@ public class PolicyManagerServlet extends HttpServlet {
policyAdapter.setPolicyData(policy);
String policyName = path.replace(".xml", "");
policyName = policyName.substring(0, policyName.lastIndexOf('.'));
- policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf('.')+1));
+ policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf('.') + 1));
- PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance();
- Objects.requireNonNull(setpolicyAdapter).configure(policyAdapter,entity);
+ PolicyAdapter setPolicyAdapter = PolicyAdapter.getInstance();
+ Objects.requireNonNull(setPolicyAdapter).configure(policyAdapter, entity);
policyAdapter.setParentPath(null);
ObjectMapper mapper = new ObjectMapper();
@@ -1511,54 +1567,35 @@ public class PolicyManagerServlet extends HttpServlet {
}
}
- //Add Scopes
+ // Add Scopes
private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
PolicyController controller = getPolicyControllerInstance();
- String name = "";
try {
- String userId = UserUtils.getUserSession(request).getOrgUserId();
- String path = params.getString("path");
- try{
- if(params.has(SUB_SCOPENAME)){
- if(! "".equals(params.getString(SUB_SCOPENAME))) {
- name = params.getString("path").replace(FORWARD_SLASH, File.separator) + File.separator +params.getString(SUB_SCOPENAME);
- }
- }else{
- name = params.getString(NAME);
- }
- }catch(Exception e){
- name = params.getString(NAME);
- LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e);
- }
- String validateName;
- if(name.contains(File.separator)){
- validateName = name.substring(name.lastIndexOf(File.separator)+1);
- }else{
- validateName = name;
- }
- if(!name.isEmpty()){
+ String name = getNameFromParams(params);
+ String validateName =
+ name.contains(File.separator) ? name.substring(name.lastIndexOf(File.separator) + 1) : name;
+ if (!name.isEmpty()) {
String validate = PolicyUtils.policySpecialCharValidator(validateName);
- if(!validate.contains(SUCCESS)){
+ if (!validate.contains(SUCCESS)) {
return error(validate);
}
- }
- LOGGER.debug("addFolder path: {} name: {}" + path +name);
- if(! "".equals(name)){
- if(name.startsWith(File.separator)){
+ LOGGER.debug("addFolder path: {} name: {}" + params.getString("path") + name);
+ if (name.startsWith(File.separator)) {
name = name.substring(1);
}
- PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, SCOPE_NAME, name);
- if(entity == null){
- UserInfo userInfo = new UserInfo();
- userInfo.setUserLoginId(userId);
- PolicyEditorScopes newScope = new PolicyEditorScopes();
- newScope.setScopeName(name);
- newScope.setUserCreatedBy(userInfo);
- newScope.setUserModifiedBy(userInfo);
- controller.saveData(newScope);
- }else{
+ PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class,
+ SCOPE_NAME, name);
+ if (entity != null) {
return error("Scope Already Exists");
}
+ String userId = UserUtils.getUserSession(request).getOrgUserId();
+ UserInfo userInfo = new UserInfo();
+ userInfo.setUserLoginId(userId);
+ PolicyEditorScopes newScope = new PolicyEditorScopes();
+ newScope.setScopeName(name);
+ newScope.setUserCreatedBy(userInfo);
+ newScope.setUserModifiedBy(userInfo);
+ controller.saveData(newScope);
}
return success();
} catch (Exception e) {
@@ -1567,7 +1604,25 @@ public class PolicyManagerServlet extends HttpServlet {
}
}
- //Return Error Object
+ private String getNameFromParams(final JSONObject params) {
+ String name = "";
+ try {
+ if (params.has(SUB_SCOPENAME)) {
+ if (!"".equals(params.getString(SUB_SCOPENAME))) {
+ name = params.getString("path").replace(FORWARD_SLASH, File.separator) + File.separator
+ + params.getString(SUB_SCOPENAME);
+ }
+ } else {
+ name = params.getString(NAME);
+ }
+ } catch (Exception e) {
+ name = params.getString(NAME);
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occurred While Adding Scope" + e);
+ }
+ return name;
+ }
+
+ // Return Error Object
private JSONObject error(String msg) throws ServletException {
try {
JSONObject result = new JSONObject();
@@ -1579,7 +1634,7 @@ public class PolicyManagerServlet extends HttpServlet {
}
}
- //Return Success Object
+ // Return Success Object
private JSONObject success() throws ServletException {
try {
JSONObject result = new JSONObject();
@@ -1591,7 +1646,7 @@ public class PolicyManagerServlet extends HttpServlet {
}
}
- private PolicyController getPolicyControllerInstance(){
+ private PolicyController getPolicyControllerInstance() {
return policyController != null ? getPolicyController() : new PolicyController();
}
@@ -1602,4 +1657,4 @@ public class PolicyManagerServlet extends HttpServlet {
public static void setTestUserId(String testUserId) {
PolicyManagerServlet.testUserId = testUserId;
}
-} \ No newline at end of file
+}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java
index a1bb73354..1fccfda78 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java
@@ -4,6 +4,7 @@
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
+ * Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,11 +25,11 @@ package org.onap.policy.admin;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
+import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
-import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.script.SimpleBindings;
@@ -82,9 +83,8 @@ public class PolicyNotificationMail{
* @param policyName Name of the policy for which notification is to be sent
* @param mode kind of operation done on the policy
* @param policyNotificationDao database access object for policy
- * @throws MessagingException
*/
- public void sendMail(PolicyVersion entityItem, String policyName, String mode, CommonClassDao policyNotificationDao) throws MessagingException {
+ public void sendMail(PolicyVersion entityItem, String policyName, String mode, CommonClassDao policyNotificationDao) {
String subject = "";
String message = "";
@@ -130,26 +130,25 @@ public class PolicyNotificationMail{
String policyFileName = findPolicyFileName(entityItem);
String query = "from WatchPolicyNotificationTable where policyName like:policyFileName";
List<Object> watchList = findWatchList(policyNotificationDao, policyFileName, query);
- if (watchList == null) {
- return;
+ if (!watchList.isEmpty()) {
+ composeAndSendMail(mode, policyNotificationDao, subject, message, checkPolicyName, watchList);
}
-
- composeAndSendMail(mode, policyNotificationDao, subject, message, checkPolicyName, watchList);
}
private List<Object> findWatchList(CommonClassDao policyNotificationDao, String policyFileName, String query) {
SimpleBindings params = new SimpleBindings();
params.put("policyFileName", policyFileName);
List<Object> watchList;
- if(PolicyController.isjUnit()){
+ if (PolicyController.isjUnit()) {
watchList = policyNotificationDao.getDataByQuery(query, null);
- }else{
+ } else {
watchList = policyNotificationDao.getDataByQuery(query, params);
}
- if(watchList == null || watchList.isEmpty()) {
- policyLogger.debug("List of policy being watched is either null or empty, hence return without sending mail");
- return null;
+ if (watchList == null || watchList.isEmpty()) {
+ policyLogger
+ .debug("List of policy being watched is either null or empty, hence return without sending mail");
+ watchList = new ArrayList<>();
}
return watchList;
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java
index d77f52b0e..6935c7203 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java
@@ -4,6 +4,7 @@
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
+ * Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,7 +34,6 @@ import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
-import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -136,25 +136,28 @@ public class PolicyRestController extends RestrictedBaseController{
}
}
- private void updateAndSendToPAP(HttpServletRequest request, HttpServletResponse response, String userId, ObjectMapper mapper) throws IOException, MessagingException {
+ private void updateAndSendToPAP(HttpServletRequest request, HttpServletResponse response, String userId, ObjectMapper mapper) throws IOException {
JsonNode root = mapper.readTree(request.getReader());
-
- policyLogger.info("****************************************Logging UserID while Create/Update Policy**************************************************");
- policyLogger.info(USER_ID + userId + "Policy Data Object: "+ root.get(PolicyController.getPolicydata()).get("policy").toString());
- policyLogger.info("***********************************************************************************************************************************");
-
- PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class);
-
+ policyLogger.info(
+ "****************************************Logging UserID while Create/Update Policy**************************************************");
+ policyLogger.info(
+ USER_ID + userId + "Policy Data Object: " + root.get(PolicyController.getPolicydata()).get("policy")
+ .toString());
+ policyLogger.info(
+ "***********************************************************************************************************************************");
+
+ PolicyRestAdapter policyData = mapper
+ .readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class);
modifyPolicyData(root, policyData);
- if(policyData.getConfigPolicyType() != null){
- if(CLOSED_LOOP_FAULT.equalsIgnoreCase(policyData.getConfigPolicyType())){
+ if (policyData.getConfigPolicyType() != null) {
+ if (CLOSED_LOOP_FAULT.equalsIgnoreCase(policyData.getConfigPolicyType())) {
policyData = new CreateClosedLoopFaultController().setDataToPolicyRestAdapter(policyData, root);
- }else if(FIREWALL_CONFIG.equalsIgnoreCase(policyData.getConfigPolicyType())){
+ } else if (FIREWALL_CONFIG.equalsIgnoreCase(policyData.getConfigPolicyType())) {
policyData = new CreateFirewallController().setDataToPolicyRestAdapter(policyData);
- }else if(MICRO_SERVICE.equalsIgnoreCase(policyData.getConfigPolicyType())){
+ } else if (MICRO_SERVICE.equalsIgnoreCase(policyData.getConfigPolicyType())) {
policyData = new CreateDcaeMicroServiceController().setDataToPolicyRestAdapter(policyData, root);
- }else if(OPTIMIZATION.equalsIgnoreCase(policyData.getConfigPolicyType())){
+ } else if (OPTIMIZATION.equalsIgnoreCase(policyData.getConfigPolicyType())) {
policyData = new CreateOptimizationController().setDataToPolicyRestAdapter(policyData, root);
}
}
@@ -165,17 +168,18 @@ public class PolicyRestController extends RestrictedBaseController{
String body = PolicyUtils.objectToJsonString(policyData);
String uri = request.getRequestURI();
ResponseEntity<?> responseEntity = sendToPAP(body, uri, HttpMethod.POST);
- if(responseEntity != null && responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)){
+ if (responseEntity != null && responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)) {
result = "PolicyExists";
- }else if(responseEntity != null){
- result = responseEntity.getBody().toString();
+ } else if (responseEntity != null) {
+ result = responseEntity.getBody().toString();
String policyName = responseEntity.getHeaders().get(POLICY_NAME).get(0);
- if(policyData.isEditPolicy() && SUCCESS.equalsIgnoreCase(result)){
+ if (policyData.isEditPolicy() && SUCCESS.equalsIgnoreCase(result)) {
PolicyNotificationMail email = new PolicyNotificationMail();
String mode = "EditPolicy";
String watchPolicyName = policyName.replace(XML, "");
- String version = watchPolicyName.substring(watchPolicyName.lastIndexOf('.')+1);
- watchPolicyName = watchPolicyName.substring(0, watchPolicyName.lastIndexOf('.')).replace(".", File.separator);
+ String version = watchPolicyName.substring(watchPolicyName.lastIndexOf('.') + 1);
+ watchPolicyName = watchPolicyName.substring(0, watchPolicyName.lastIndexOf('.'))
+ .replace(".", File.separator);
String policyVersionName = watchPolicyName.replace(".", File.separator);
watchPolicyName = watchPolicyName + "." + version + XML;
PolicyVersion entityItem = new PolicyVersion();
@@ -184,8 +188,8 @@ public class PolicyRestController extends RestrictedBaseController{
entityItem.setModifiedBy(userId);
email.sendMail(entityItem, watchPolicyName, mode, commonClassDao);
}
- }else{
- result = "Response is null from PAP";
+ } else {
+ result = "Response is null from PAP";
}
response.setCharacterEncoding(PolicyController.getCharacterencoding());
@@ -343,10 +347,11 @@ public class PolicyRestController extends RestrictedBaseController{
return null;
}
- private void checkURI(HttpServletRequest request, String uri, HttpURLConnection connection, FileItem item) throws IOException {
+ private void checkURI(HttpServletRequest request, String uri, HttpURLConnection connection, FileItem item)
+ throws IOException {
String boundary;
- if(!(uri.endsWith("set_BRMSParamData") || uri.contains(IMPORT_DICTIONARY))){
- connection.setRequestProperty(CONTENT_TYPE,PolicyController.getContenttype());
+ if (!(uri.endsWith("set_BRMSParamData") || uri.contains(IMPORT_DICTIONARY))) {
+ connection.setRequestProperty(CONTENT_TYPE, PolicyController.getContenttype());
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode root = getJsonNode(request, mapper);
@@ -358,26 +363,24 @@ public class PolicyRestController extends RestrictedBaseController{
String json = mapper1.writeValueAsString(obj);
// send current configuration
- try(InputStream content = new ByteArrayInputStream(json.getBytes());
+ try (InputStream content = new ByteArrayInputStream(json.getBytes());
OutputStream os = connection.getOutputStream()) {
int count = IOUtils.copy(content, os);
if (policyLogger.isDebugEnabled()) {
policyLogger.debug("copied to output, bytes=" + count);
}
}
- }else{
- if(uri.endsWith("set_BRMSParamData")){
- connection.setRequestProperty(CONTENT_TYPE,PolicyController.getContenttype());
- try (OutputStream os = connection.getOutputStream()) {
- IOUtils.copy((InputStream) request.getInputStream(), os);
- }
- }else{
- boundary = "===" + System.currentTimeMillis() + "===";
- connection.setRequestProperty(CONTENT_TYPE,"multipart/form-data; boundary=" + boundary);
- try (OutputStream os = connection.getOutputStream()) {
- if(item != null){
- IOUtils.copy((InputStream) item.getInputStream(), os);
- }
+ } else if (uri.endsWith("set_BRMSParamData")) {
+ connection.setRequestProperty(CONTENT_TYPE, PolicyController.getContenttype());
+ try (OutputStream os = connection.getOutputStream()) {
+ IOUtils.copy(request.getInputStream(), os);
+ }
+ } else {
+ boundary = "===" + System.currentTimeMillis() + "===";
+ connection.setRequestProperty(CONTENT_TYPE, "multipart/form-data; boundary=" + boundary);
+ try (OutputStream os = connection.getOutputStream()) {
+ if (item != null) {
+ IOUtils.copy(item.getInputStream(), os);
}
}
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java
index 96205c5b1..7e0aef2e9 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java
@@ -3,13 +3,14 @@
* ONAP Policy Engine
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -39,24 +40,23 @@ import com.fasterxml.jackson.databind.ObjectMapper;
@Controller
@RequestMapping("/")
-public class PolicyUserInfoController extends RestrictedBaseController{
-
- private static final Logger LOGGER = FlexLogger.getLogger(PolicyUserInfoController.class);
-
- @RequestMapping(value="/get_PolicyUserInfo", method = RequestMethod.GET)
- public void getPolicyUserInfo(HttpServletRequest request, HttpServletResponse response){
- JsonMessage msg = null;
- try {
- String userId = UserUtils.getUserSession(request).getOrgUserId();
- Map<String, Object> model = new HashMap<>();
- ObjectMapper mapper = new ObjectMapper();
- model.put("userid", userId);
- msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
- } catch (Exception e) {
- LOGGER.error("Exception Occured"+e);
- }
- }
+public class PolicyUserInfoController extends RestrictedBaseController {
+ private static final Logger LOGGER = FlexLogger.getLogger(PolicyUserInfoController.class);
+
+ @RequestMapping(value = "/get_PolicyUserInfo", method = RequestMethod.GET)
+ public void getPolicyUserInfo(HttpServletRequest request, HttpServletResponse response) {
+ JsonMessage msg;
+ try {
+ String userId = UserUtils.getUserSession(request).getOrgUserId();
+ Map<String, Object> model = new HashMap<>();
+ ObjectMapper mapper = new ObjectMapper();
+ model.put("userid", userId);
+ msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ } catch (Exception e) {
+ LOGGER.error("Exception Occurred" + e);
+ }
+ }
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java
index c09944c2f..2ccc92eb3 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java
@@ -4,6 +4,7 @@
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
+ * Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,8 +22,6 @@
package org.onap.policy.admin;
-
-
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@@ -33,6 +32,7 @@ import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
@@ -74,7 +74,7 @@ import org.onap.policy.common.logging.flexlogger.Logger;
public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyEngine {
private static final Logger LOGGER = FlexLogger.getLogger(RESTfulPAPEngine.class);
- private static final String groupID = "groupId=";
+ private static final String GROUP_ID = "groupId=";
//
// URL of the PAP Servlet that this Admin Console talks to
@@ -83,7 +83,7 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
/**
* Set up link with PAP Servlet and get our initial set of Groups
- * @throws Exception
+ * @throws PAPException When failing to register with PAP
*/
public RESTfulPAPEngine (String myURLString) throws PAPException {
//
@@ -112,40 +112,38 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
}
}
-
//
// High-level commands used by the Admin Console code through the PAPEngine Interface
//
@Override
public OnapPDPGroup getDefaultGroup() throws PAPException {
- return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID, "default=");
+ return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID, "default=");
}
@Override
public void setDefaultGroup(OnapPDPGroup group) throws PAPException {
- sendToPAP("POST", null, null, null, groupID + group.getId(), "default=true");
+ sendToPAP("POST", null, null, null, GROUP_ID + group.getId(), "default=true");
}
@SuppressWarnings("unchecked")
@Override
public Set<OnapPDPGroup> getOnapPDPGroups() throws PAPException {
Set<OnapPDPGroup> newGroupSet;
- newGroupSet = (Set<OnapPDPGroup>) this.sendToPAP("GET", null, Set.class, StdPDPGroup.class, groupID);
+ newGroupSet = (Set<OnapPDPGroup>) this.sendToPAP("GET", null, Set.class, StdPDPGroup.class, GROUP_ID);
return Collections.unmodifiableSet(newGroupSet);
}
-
@Override
public OnapPDPGroup getGroup(String id) throws PAPException {
- return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID + id);
+ return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID + id);
}
@Override
public void newGroup(String name, String description)
throws PAPException {
- String escapedName = null;
- String escapedDescription = null;
+ String escapedName;
+ String escapedDescription;
try {
escapedName = URLEncoder.encode(name, "UTF-8");
escapedDescription = URLEncoder.encode(description, "UTF-8");
@@ -153,10 +151,9 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
throw new PAPException("Unable to send name or description to PAP: " + e.getMessage() +e);
}
- this.sendToPAP("POST", null, null, null, groupID, "groupName="+escapedName, "groupDescription=" + escapedDescription);
+ this.sendToPAP("POST", null, null, null, GROUP_ID, "groupName="+escapedName, "groupDescription=" + escapedDescription);
}
-
/**
* Update the configuration on the PAP for a single Group.
*
@@ -166,24 +163,17 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
*/
@Override
public void updateGroup(OnapPDPGroup group) throws PAPException {
-
try {
-
//
// ASSUME that all of the policies mentioned in this group are already located in the correct directory on the PAP!
//
// Whenever a Policy is added to the group, that file must be automatically copied to the PAP from the Workspace.
//
-
-
// Copy all policies from the local machine's workspace to the PAP's PDPGroup directory.
// This is not efficient since most of the policies will already exist there.
// However, the policy files are (probably!) not too huge, and this is a good way to ensure that any corrupted files on the PAP get refreshed.
-
-
// now update the group object on the PAP
-
- sendToPAP("PUT", group, null, null, groupID + group.getId());
+ sendToPAP("PUT", group, null, null, GROUP_ID + group.getId());
} catch (Exception e) {
String message = "Unable to PUT policy '" + group.getId() + "', e:" + e;
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
@@ -191,15 +181,13 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
}
}
-
@Override
- public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup)
- throws PAPException {
+ public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup) throws PAPException {
String moveToGroupString = null;
if (newGroup != null) {
moveToGroupString = "movePDPsToGroupId=" + newGroup.getId();
}
- sendToPAP("DELETE", null, null, null, groupID + group.getId(), moveToGroupString);
+ sendToPAP("DELETE", null, null, null, GROUP_ID + group.getId(), moveToGroupString);
}
@Override
@@ -207,41 +195,36 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
return getPDPGroup(pdp.getId());
}
-
public OnapPDPGroup getPDPGroup(String pdpId) throws PAPException {
- return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID, "pdpId=" + pdpId, "getPDPGroup=");
+ return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID, "pdpId=" + pdpId, "getPDPGroup=");
}
@Override
public OnapPDP getPDP(String pdpId) throws PAPException {
- return (OnapPDP)sendToPAP("GET", null, null, StdPDP.class, groupID, "pdpId=" + pdpId);
+ return (OnapPDP)sendToPAP("GET", null, null, StdPDP.class, GROUP_ID, "pdpId=" + pdpId);
}
@Override
public void newPDP(String id, OnapPDPGroup group, String name, String description, int jmxport) throws PAPException {
StdPDP newPDP = new StdPDP(id, name, description, jmxport);
- sendToPAP("PUT", newPDP, null, null, groupID + group.getId(), "pdpId=" + id);
- return;
+ sendToPAP("PUT", newPDP, null, null, GROUP_ID + group.getId(), "pdpId=" + id);
}
@Override
public void movePDP(OnapPDP pdp, OnapPDPGroup newGroup) throws PAPException {
- sendToPAP("POST", null, null, null, groupID + newGroup.getId(), "pdpId=" + pdp.getId());
- return;
+ sendToPAP("POST", null, null, null, GROUP_ID + newGroup.getId(), "pdpId=" + pdp.getId());
}
@Override
public void updatePDP(OnapPDP pdp) throws PAPException {
OnapPDPGroup group = getPDPGroup(pdp);
- sendToPAP("PUT", pdp, null, null, groupID + group.getId(), "pdpId=" + pdp.getId());
- return;
+ sendToPAP("PUT", pdp, null, null, GROUP_ID + group.getId(), "pdpId=" + pdp.getId());
}
@Override
public void removePDP(OnapPDP pdp) throws PAPException {
OnapPDPGroup group = getPDPGroup(pdp);
- sendToPAP("DELETE", null, null, null, groupID + group.getId(), "pdpId=" + pdp.getId());
- return;
+ sendToPAP("DELETE", null, null, null, GROUP_ID + group.getId(), "pdpId=" + pdp.getId());
}
//Validate the Policy Data
@@ -257,8 +240,6 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
@Override
public void publishPolicy(String id, String name, boolean isRoot,
InputStream policy, OnapPDPGroup group) throws PAPException {
-
-
// copy the (one) file into the target directory on the PAP servlet
copyFile(id, group, policy);
@@ -268,8 +249,6 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
// tell the PAP servlet to include the policy in the configuration
updateGroup(group);
-
- return;
}
/**
@@ -285,7 +264,7 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
public void copyFile(String policyId, OnapPDPGroup group, InputStream policy) throws PAPException {
// send the policy file to the PAP Servlet
try {
- sendToPAP("POST", policy, null, null, groupID + group.getId(), "policyId="+policyId);
+ sendToPAP("POST", policy, null, null, GROUP_ID + group.getId(), "policyId="+policyId);
} catch (Exception e) {
String message = "Unable to PUT policy '" + policyId + "', e:" + e;
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
@@ -293,9 +272,8 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
}
}
-
@Override
- public void copyPolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
+ public void copyPolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
if (policy == null || group == null) {
throw new PAPException("Null input policy="+policy+" group="+group);
}
@@ -309,12 +287,10 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
}
@Override
- public void removePolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
+ public void removePolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
throw new PAPException("NOT IMPLEMENTED");
-
}
-
/**
* Special operation - Similar to the normal PAP operations but this one contacts the PDP directly
* to get detailed status info.
@@ -328,7 +304,6 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
return (StdPDPStatus)sendToPAP("GET", pdp, null, StdPDPStatus.class);
}
-
//
// Internal Operations called by the PAPEngine Interface methods
//
@@ -347,7 +322,7 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
* @param responseContentClass
* @param parameters
* @return
- * @throws Exception
+ * @throws PAPException
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
private Object sendToPAP(String method, Object content, Class collectionTypeClass, Class responseContentClass, String... parameters ) throws PAPException {
@@ -356,37 +331,34 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
LOGGER.info("User Id is " + papID);
String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
Base64.Encoder encoder = Base64.getEncoder();
- String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
+ String encoding = encoder.encodeToString((papID + ":" + papPass).getBytes(StandardCharsets.UTF_8));
Object contentObj = content;
LOGGER.info("Encoding for the PAP is: " + encoding);
try {
String fullURL = papServletURLString;
if (parameters != null && parameters.length > 0) {
StringBuilder queryString = new StringBuilder();
- for (String p : parameters) {
- queryString.append("&" + p);
- }
+ Arrays.stream(parameters).map(p -> "&" + p).forEach(queryString::append);
fullURL += "?" + queryString.substring(1);
}
// special case - Status (actually the detailed status) comes from the PDP directly, not the PAP
- if ("GET".equals(method) && (contentObj instanceof OnapPDP) && responseContentClass == StdPDPStatus.class) {
+ if ("GET".equals(method) && (contentObj instanceof OnapPDP) && responseContentClass == StdPDPStatus.class) {
// Adjust the url and properties appropriately
- String pdpID =((OnapPDP)contentObj).getId();
+ String pdpID = ((OnapPDP) contentObj).getId();
fullURL = pdpID + "?type=Status";
contentObj = null;
- if(CheckPDP.validateID(pdpID)){
+ if (CheckPDP.validateID(pdpID)) {
encoding = CheckPDP.getEncoding(pdpID);
}
}
-
URL url = new URL(fullURL);
//
// Open up the connection
//
- connection = (HttpURLConnection)url.openConnection();
+ connection = (HttpURLConnection) url.openConnection();
//
// Setup our method and headers
//
@@ -410,7 +382,7 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
} else {
// The contentObj is an object to be encoded in JSON
ObjectMapper mapper = new ObjectMapper();
- mapper.writeValue(connection.getOutputStream(), contentObj);
+ mapper.writeValue(connection.getOutputStream(), contentObj);
}
}
//
@@ -425,18 +397,18 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
String isValidData = connection.getHeaderField("isValidData");
String isSuccess = connection.getHeaderField("successMapKey");
Map<String, String> successMap = new HashMap<>();
- if (isValidData != null && "true".equalsIgnoreCase(isValidData)){
+ if ("true".equalsIgnoreCase(isValidData)) {
LOGGER.info("Policy Data is valid.");
return true;
- } else if (isValidData != null && "false".equalsIgnoreCase(isValidData)) {
+ } else if ("false".equalsIgnoreCase(isValidData)) {
LOGGER.info("Policy Data is invalid.");
return false;
- } else if (isSuccess != null && "success".equalsIgnoreCase(isSuccess)) {
- LOGGER.info("Policy Created Successfully!" );
+ } else if ("success".equalsIgnoreCase(isSuccess)) {
+ LOGGER.info("Policy Created Successfully!");
String finalPolicyPath = connection.getHeaderField("finalPolicyPath");
successMap.put("success", finalPolicyPath);
return successMap;
- } else if (isSuccess != null && "error".equalsIgnoreCase(isSuccess)) {
+ } else if ("error".equalsIgnoreCase(isSuccess)) {
LOGGER.info("There was an error while creating the policy!");
successMap.put("error", "error");
return successMap;
@@ -450,21 +422,21 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
if (collectionTypeClass != null) {
// collection of objects expected
final CollectionType javaType =
- mapper.getTypeFactory().constructCollectionType(collectionTypeClass, responseContentClass);
-
+ mapper.getTypeFactory().constructCollectionType(collectionTypeClass, responseContentClass);
return mapper.readValue(json, javaType);
} else {
// single value object expected
return mapper.readValue(json, responseContentClass);
}
}
-
- } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) {
+ } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) {
// redirection
String newURL = connection.getHeaderField("Location");
if (newURL == null) {
- LOGGER.error("No Location header to redirect to when response code="+connection.getResponseCode());
- throw new IOException("No redirect Location header when response code="+connection.getResponseCode());
+ LOGGER
+ .error("No Location header to redirect to when response code=" + connection.getResponseCode());
+ throw new IOException(
+ "No redirect Location header when response code=" + connection.getResponseCode());
}
int qIndex = newURL.indexOf('?');
if (qIndex > 0) {
@@ -473,12 +445,13 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
LOGGER.info("Redirect seen. Redirecting " + fullURL + " to " + newURL);
return newURL;
} else {
- LOGGER.warn("Unexpected response code: " + connection.getResponseCode() + " message: " + connection.getResponseMessage());
- throw new IOException("Server Response: " + connection.getResponseCode() + ": " + connection.getResponseMessage());
+ LOGGER.warn("Unexpected response code: " + connection.getResponseCode() + " message: " + connection
+ .getResponseMessage());
+ throw new IOException(
+ "Server Response: " + connection.getResponseCode() + ": " + connection.getResponseMessage());
}
-
} catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "HTTP Request/Response to PAP: " + e,e);
+ LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "HTTP Request/Response to PAP: " + e, e);
throw new PAPException("Request/Response threw :" + e);
} finally {
// cleanup the connection
@@ -515,7 +488,7 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
}
private String getJsonString(final HttpURLConnection connection) throws IOException {
- String json = null;
+ String json;
// read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
try(java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream())) {
scanner.useDelimiter("\\A");
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java
index ea0dce2c0..b116af6ef 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java
@@ -3,6 +3,7 @@
* ONAP Policy Engine
* ================================================================================
* Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -65,8 +66,6 @@ import org.onap.policy.rest.jpa.FunctionDefinition;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.policy.xacml.util.XACMLPolicyScanner;
-
-
public class HumanPolicyComponent {
private static final Logger LOGGER = FlexLogger.getLogger(HumanPolicyComponent.class);
@@ -218,8 +217,7 @@ class HtmlProcessor extends SimpleCallback {
throw new IllegalArgumentException(msg);
}
- if (policyObject == null
- || (!(policyObject instanceof PolicySetType) && !(policyObject instanceof PolicyType))) {
+ if ((!(policyObject instanceof PolicySetType) && !(policyObject instanceof PolicyType))) {
String msg = "Invalid unmarshalled object: " + policyObject;
LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + msg);
throw new IllegalArgumentException(msg);
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java
index a556beeaa..578258403 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java
@@ -3,6 +3,7 @@
* ONAP Policy Engine
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,7 +23,6 @@ package org.onap.policy.controller;
import java.util.ArrayList;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
@@ -33,7 +33,6 @@ import javax.xml.bind.JAXBElement;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
-import org.onap.policy.rest.jpa.PolicyEntity;
import org.onap.portalsdk.core.controller.RestrictedBaseController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@@ -56,132 +55,149 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
@RequestMapping({ "/" })
public class ActionPolicyController extends RestrictedBaseController {
private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicyController.class);
+ private static final String PERFORMER_ATTRIBUTE_ID = "performer";
+ private static final String DYNAMIC_RULE_ALGORITHM_FIELD_1 = "dynamicRuleAlgorithmField1";
+ private static final String DYNAMIC_RULE_ALGORITHM_FIELD_2 = "dynamicRuleAlgorithmField2";
+ private LinkedList<Integer> ruleAlgorithmTracker;
+ private Map<String, String> performer = new HashMap<>();
+ private List<Object> ruleAlgorithmList;
public ActionPolicyController() {
// Default Constructor
}
- private ArrayList<Object> attributeList;
- protected LinkedList<Integer> ruleAlgoirthmTracker;
- public static final String PERFORMER_ATTRIBUTEID = "performer";
- protected Map<String, String> performer = new HashMap<>();
- private ArrayList<Object> ruleAlgorithmList;
-
- public void prePopulateActionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
- attributeList = new ArrayList<>();
+ public void prePopulateActionPolicyData(PolicyRestAdapter policyAdapter) {
ruleAlgorithmList = new ArrayList<>();
performer.put("PDP", "PDPAction");
performer.put("PEP", "PEPAction");
if (policyAdapter.getPolicyData() instanceof PolicyType) {
- Object policyData = policyAdapter.getPolicyData();
- PolicyType policy = (PolicyType) policyData;
- policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
- String policyNameValue = policyAdapter.getPolicyName()
- .substring(policyAdapter.getPolicyName().indexOf('_') + 1);
- policyAdapter.setPolicyName(policyNameValue);
- String description = "";
- try {
- description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
- } catch (Exception e) {
- LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e);
- description = policy.getDescription();
- }
- policyAdapter.setPolicyDescription(description);
- // Get the target data under policy for Action.
+ PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
+
+ // 1. Set policy-name, policy-filename and description to Policy Adapter
+ setPolicyAdapterPolicyNameAndDesc(policyAdapter, policy);
+
+ // 2a. Get the target data under policy for Action.
TargetType target = policy.getTarget();
- if (target != null) {
- // under target we have AnyOFType
- List<AnyOfType> anyOfList = target.getAnyOf();
- if (anyOfList != null) {
- Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
- while (iterAnyOf.hasNext()) {
- AnyOfType anyOf = iterAnyOf.next();
- // Under AntOfType we have AllOfType
- List<AllOfType> allOfList = anyOf.getAllOf();
- if (allOfList != null) {
- Iterator<AllOfType> iterAllOf = allOfList.iterator();
- while (iterAllOf.hasNext()) {
- AllOfType allOf = iterAllOf.next();
- // Under AllOfType we have Mathch.
- List<MatchType> matchList = allOf.getMatch();
- if (matchList != null) {
- Iterator<MatchType> iterMatch = matchList.iterator();
- while (iterMatch.hasNext()) {
- MatchType match = iterMatch.next();
- //
- // Under the match we have attributevalue and
- // attributeDesignator. So,finally down to the actual attribute.
- //
- AttributeValueType attributeValue = match.getAttributeValue();
- String value = (String) attributeValue.getContent().get(0);
- AttributeDesignatorType designator = match.getAttributeDesignator();
- String attributeId = designator.getAttributeId();
- // Component attributes are saved under Target here we are fetching them back.
- // One row is default so we are not adding dynamic component at index 0.
- Map<String, String> attribute = new HashMap<>();
- attribute.put("key", attributeId);
- attribute.put("value", value);
- attributeList.add(attribute);
- }
- }
- policyAdapter.setAttributes(attributeList);
- }
- }
- }
+ if (target == null) {
+ return;
+ }
+
+ // 2b. Set attributes to Policy Adapter
+ setPolicyAdapterAttributes(policyAdapter, target.getAnyOf());
+
+ List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
+ // Under rule we have Condition and obligation.
+ for (Object o : ruleList) {
+ if (!(o instanceof RuleType)) {
+ continue;
}
+ // 3. Set rule-algorithm choices to Policy Adapter
+ setPolicyAdapterRuleAlgorithmschoices(policyAdapter, (RuleType) o);
- List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
- // Under rule we have Condition and obligation.
- for (Object o : ruleList) {
- if (o instanceof RuleType) {
- ConditionType condition = ((RuleType) o).getCondition();
- ObligationExpressionsType obligations = ((RuleType) o).getObligationExpressions();
- if (condition != null) {
- int index = 0;
- ApplyType actionApply = (ApplyType) condition.getExpression().getValue();
- ruleAlgoirthmTracker = new LinkedList<>();
- // Populating Rule Algorithms starting from compound.
- prePopulateCompoundRuleAlgorithm(index, actionApply);
- }
- policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList);
- // get the Obligation data under the rule for Form elements.
- if (obligations != null) {
- // Under the obligationExpressions we have obligationExpression.
- List<ObligationExpressionType> obligationList = obligations.getObligationExpression();
- if (obligationList != null) {
- Iterator<ObligationExpressionType> iterObligation = obligationList.iterator();
- while (iterObligation.hasNext()) {
- ObligationExpressionType obligation = iterObligation.next();
- policyAdapter.setActionAttributeValue(obligation.getObligationId());
- // Under the obligationExpression we have attributeAssignmentExpression.
- List<AttributeAssignmentExpressionType> attributeAssignmentExpressionList = obligation
- .getAttributeAssignmentExpression();
- if (attributeAssignmentExpressionList != null) {
- Iterator<AttributeAssignmentExpressionType> iterAttributeAssignmentExpression = attributeAssignmentExpressionList
- .iterator();
- while (iterAttributeAssignmentExpression.hasNext()) {
- AttributeAssignmentExpressionType attributeAssignmentExpression = iterAttributeAssignmentExpression
- .next();
- String attributeID = attributeAssignmentExpression.getAttributeId();
- AttributeValueType attributeValue = (AttributeValueType) attributeAssignmentExpression
- .getExpression().getValue();
- if (attributeID.equals(PERFORMER_ATTRIBUTEID)) {
- for ( Entry<String, String> entry: performer.entrySet()) {
- String key = entry.getKey();
- String keyValue = entry.getValue();
- if (keyValue.equals(attributeValue.getContent().get(0))) {
- policyAdapter.setActionPerformer(key);
- }
- }
- }
- }
- }
- }
- }
- }
+ // 4a. Get the Obligation data under the rule for Form elements.
+ ObligationExpressionsType obligations = ((RuleType) o).getObligationExpressions();
+
+ // 4b. Set action attribute-value and action-performer to Policy Adapter
+ setPolicyAdapterActionData(policyAdapter, obligations);
+ }
+ }
+ }
+
+ private void setPolicyAdapterActionData(PolicyRestAdapter policyAdapter, ObligationExpressionsType obligations) {
+ if (obligations == null) {
+ return;
+ }
+ // Under the obligationExpressions we have obligationExpression.
+ List<ObligationExpressionType> obligationList = obligations.getObligationExpression();
+ if (obligationList == null) {
+ return;
+ }
+ for (ObligationExpressionType obligation : obligationList) {
+ policyAdapter.setActionAttributeValue(obligation.getObligationId());
+ // Under the obligationExpression we have attributeAssignmentExpression.
+ List<AttributeAssignmentExpressionType> attributeAssignmentExpressionList = obligation
+ .getAttributeAssignmentExpression();
+ if (attributeAssignmentExpressionList == null) {
+ continue;
+ }
+ for (AttributeAssignmentExpressionType attributeAssignmentExpression : attributeAssignmentExpressionList) {
+ String attributeID = attributeAssignmentExpression.getAttributeId();
+ AttributeValueType attributeValue = (AttributeValueType) attributeAssignmentExpression
+ .getExpression().getValue();
+ if (!attributeID.equals(PERFORMER_ATTRIBUTE_ID)) {
+ continue;
+ }
+ performer.forEach((key, keyValue) -> {
+ if (keyValue.equals(attributeValue.getContent().get(0))) {
+ policyAdapter.setActionPerformer(key);
}
+ });
+ }
+ }
+ }
+
+ private void setPolicyAdapterPolicyNameAndDesc(PolicyRestAdapter policyAdapter, PolicyType policy) {
+ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+ String policyNameValue = policyAdapter.getPolicyName()
+ .substring(policyAdapter.getPolicyName().indexOf('_') + 1);
+ policyAdapter.setPolicyName(policyNameValue);
+ String description;
+ try {
+ description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+ } catch (Exception e) {
+ LOGGER.error("Error while collecting the description tag in ActionPolicy " + policyNameValue, e);
+ description = policy.getDescription();
+ }
+ policyAdapter.setPolicyDescription(description);
+ }
+
+ private void setPolicyAdapterRuleAlgorithmschoices(PolicyRestAdapter policyAdapter, RuleType o) {
+ ConditionType condition = o.getCondition();
+ if (condition != null) {
+ int index = 0;
+ ApplyType actionApply = (ApplyType) condition.getExpression().getValue();
+ ruleAlgorithmTracker = new LinkedList<>();
+ // Populating Rule Algorithms starting from compound.
+ prePopulateCompoundRuleAlgorithm(index, actionApply);
+ }
+ policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList);
+ }
+
+ private void setPolicyAdapterAttributes(PolicyRestAdapter policyAdapter, List<AnyOfType> anyOfList) {
+ List<Object> attributeList = new ArrayList<>();
+ if (anyOfList == null) {
+ return;
+ }
+ // under target we have AnyOFType
+ for (AnyOfType anyOf : anyOfList) {
+ // Under AntOfType we have AllOfType
+ List<AllOfType> allOfList = anyOf.getAllOf();
+ if (allOfList == null) {
+ continue;
+ }
+ // Under AllOfType we have Match.
+ for (AllOfType allOfType : allOfList) {
+ List<MatchType> matchList = allOfType.getMatch();
+ if (matchList != null) {
+ //
+ // Under the match we have attributeValue and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ // Component attributes are saved under Target here we are fetching them back.
+ // One row is default so we are not adding dynamic component at index 0.
+ matchList.forEach(match -> {
+ AttributeValueType attributeValue = match.getAttributeValue();
+ String value = (String) attributeValue.getContent().get(0);
+ AttributeDesignatorType designator = match.getAttributeDesignator();
+ String attributeId = designator.getAttributeId();
+ Map<String, String> attribute = new HashMap<>();
+ attribute.put("key", attributeId);
+ attribute.put("value", value);
+ attributeList.add(attribute);
+ });
}
+ policyAdapter.setAttributes(attributeList);
}
}
}
@@ -197,7 +213,7 @@ public class ActionPolicyController extends RestrictedBaseController {
// Check to see if Attribute Value exists, if yes then it is not a compound rule
if (jaxbElement.getValue() instanceof AttributeValueType) {
prePopulateRuleAlgorithms(index, actionApply, jaxbActionTypes);
- ruleAlgoirthmTracker.addLast(index);
+ ruleAlgorithmTracker.addLast(index);
isCompoundRule = false;
index++;
}
@@ -221,11 +237,11 @@ public class ActionPolicyController extends RestrictedBaseController {
}
rule.put("id", "A" + (index + 1));
// Populate Key and values for Compound Rule
- rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1));
- ruleAlgoirthmTracker.removeLast();
- rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1));
- ruleAlgoirthmTracker.removeLast();
- ruleAlgoirthmTracker.addLast(index);
+ rule.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, "A" + (ruleAlgorithmTracker.getLast() + 1));
+ ruleAlgorithmTracker.removeLast();
+ rule.put(DYNAMIC_RULE_ALGORITHM_FIELD_2, "A" + (ruleAlgorithmTracker.getLast() + 1));
+ ruleAlgorithmTracker.removeLast();
+ ruleAlgorithmTracker.addLast(index);
ruleAlgorithmList.add(rule);
index++;
}
@@ -250,26 +266,25 @@ public class ActionPolicyController extends RestrictedBaseController {
List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression();
AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0)
.getValue();
- ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId());
+ ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, attributeDesignator.getAttributeId());
// Get from Attribute Value
AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbActionTypes.get(1).getValue();
String attributeValue = (String) actionConditionAttributeValue.getContent().get(0);
- ruleMap.put("dynamicRuleAlgorithmField2", attributeValue);
+ ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_2, attributeValue);
}
// Rule Attribute added as value
else if ((jaxbActionTypes.get(0).getValue()) instanceof AttributeValueType) {
AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbActionTypes.get(0).getValue();
String attributeValue = (String) actionConditionAttributeValue.getContent().get(0);
- ruleMap.put("dynamicRuleAlgorithmField2", attributeValue);
+ ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_2, attributeValue);
ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(1).getValue();
List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression();
AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0)
.getValue();
- ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId());
+ ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, attributeDesignator.getAttributeId());
}
ruleAlgorithmList.add(ruleMap);
}
-
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java
index 346b95aff..fc25e29f0 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java
@@ -3,13 +3,14 @@
* ONAP Policy Engine
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,7 +21,6 @@
package org.onap.policy.controller;
-
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
@@ -50,77 +50,82 @@ import com.fasterxml.jackson.databind.ObjectMapper;
@Controller
@RequestMapping({"/"})
-public class AdminTabController extends RestrictedBaseController{
-
- private static final Logger LOGGER = FlexLogger.getLogger(AdminTabController.class);
-
- private static CommonClassDao commonClassDao;
-
- public AdminTabController() {
- //default constructor
- }
-
- @Autowired
- private AdminTabController(CommonClassDao commonClassDao){
- AdminTabController.commonClassDao = commonClassDao;
- }
-
- public static CommonClassDao getCommonClassDao() {
- return commonClassDao;
- }
-
- public static void setCommonClassDao(CommonClassDao commonClassDao) {
- AdminTabController.commonClassDao = commonClassDao;
- }
-
- @RequestMapping(value={"/get_LockDownData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
- public void getAdminTabEntityData(HttpServletRequest request, HttpServletResponse response){
- try{
- Map<String, Object> model = new HashMap<>();
- ObjectMapper mapper = new ObjectMapper();
- model.put("lockdowndata", mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class)));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
- }
- catch (Exception e){
- LOGGER.error("Exception Occured"+e);
- }
- }
-
- @RequestMapping(value={"/adminTabController/save_LockDownValue.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
- public ModelAndView saveAdminTabLockdownValue(HttpServletRequest request, HttpServletResponse response) throws IOException{
- try {
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- String userId = UserUtils.getUserSession(request).getOrgUserId();
- LOGGER.info("****************************************Logging UserID for Application Lockdown Function*****************************************");
- LOGGER.info("UserId: " + userId);
- LOGGER.info("*********************************************************************************************************************************");
- JsonNode root = mapper.readTree(request.getReader());
- GlobalRoleSettings globalRole = mapper.readValue(root.get("lockdowndata").toString(), GlobalRoleSettings.class);
- globalRole.setRole("super-admin");
- commonClassDao.update(globalRole);
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
-
- PrintWriter out = response.getWriter();
- String responseString = mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class));
- JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}");
-
- out.write(j.toString());
-
- return null;
- }
- catch (Exception e){
- LOGGER.error("Exception Occured"+e);
- response.setCharacterEncoding("UTF-8");
- request.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- out.write(PolicyUtils.CATCH_EXCEPTION);
- }
- return null;
- }
+public class AdminTabController extends RestrictedBaseController {
+
+ private static final Logger LOGGER = FlexLogger.getLogger(AdminTabController.class);
+ private static final String CHARACTER_ENCODING = "UTF-8";
+
+ private static CommonClassDao commonClassDao;
+
+ public AdminTabController() {
+ //default constructor
+ }
+
+ @Autowired
+ private AdminTabController(CommonClassDao commonClassDao) {
+ AdminTabController.commonClassDao = commonClassDao;
+ }
+
+ public static CommonClassDao getCommonClassDao() {
+ return commonClassDao;
+ }
+
+ public static void setCommonClassDao(CommonClassDao commonClassDao) {
+ AdminTabController.commonClassDao = commonClassDao;
+ }
+
+ @RequestMapping(value = {"/get_LockDownData"}, method = {
+ org.springframework.web.bind.annotation.RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE)
+ public void getAdminTabEntityData(HttpServletRequest request, HttpServletResponse response) {
+ try {
+ Map<String, Object> model = new HashMap<>();
+ ObjectMapper mapper = new ObjectMapper();
+ model.put("lockdowndata", mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class)));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ } catch (Exception e) {
+ LOGGER.error("Exception Occured" + e);
+ }
+ }
+
+ @RequestMapping(value = {"/adminTabController/save_LockDownValue.htm"}, method = {
+ org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView saveAdminTabLockdownValue(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
+ try {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ String userId = UserUtils.getUserSession(request).getOrgUserId();
+ LOGGER.info(
+ "****************************************Logging UserID for Application Lockdown Function*****************************************");
+ LOGGER.info("UserId: " + userId);
+ LOGGER.info(
+ "*********************************************************************************************************************************");
+ JsonNode root = mapper.readTree(request.getReader());
+ GlobalRoleSettings globalRole = mapper
+ .readValue(root.get("lockdowndata").toString(), GlobalRoleSettings.class);
+ globalRole.setRole("super-admin");
+ commonClassDao.update(globalRole);
+
+ response.setCharacterEncoding(CHARACTER_ENCODING);
+ response.setContentType("application / json");
+ request.setCharacterEncoding(CHARACTER_ENCODING);
+
+ PrintWriter out = response.getWriter();
+ String responseString = mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class));
+ JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}");
+
+ out.write(j.toString());
+
+ return null;
+ } catch (Exception e) {
+ LOGGER.error("Exception Occured" + e);
+ response.setCharacterEncoding(CHARACTER_ENCODING);
+ request.setCharacterEncoding(CHARACTER_ENCODING);
+ PrintWriter out = response.getWriter();
+ out.write(PolicyUtils.CATCH_EXCEPTION);
+ }
+ return null;
+ }
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java
index e5e868fd9..3af430f45 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java
@@ -2,7 +2,8 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,7 +21,6 @@
package org.onap.policy.controller;
-
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
@@ -38,6 +38,9 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
import javax.script.SimpleBindings;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -64,6 +67,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.att.research.xacml.api.pap.PAPException;
@@ -72,336 +76,324 @@ import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
-
@Controller
-@RequestMapping({"/"})
-public class AutoPushController extends RestrictedBaseController{
+@RequestMapping({ "/" })
+public class AutoPushController extends RestrictedBaseController {
- private static final Logger logger = FlexLogger.getLogger(AutoPushController.class);
+ private static final Logger logger = FlexLogger.getLogger(AutoPushController.class);
private static final String UTF8 = "UTF-8";
-
- @Autowired
- CommonClassDao commonClassDao;
-
- private PDPGroupContainer container;
- protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<OnapPDPGroup>());
-
- private PDPPolicyContainer policyContainer;
-
- private PolicyController policyController;
- public PolicyController getPolicyController() {
- return policyController;
- }
-
- public void setPolicyController(PolicyController policyController) {
- this.policyController = policyController;
- }
-
- private List<Object> data;
-
- public synchronized void refreshGroups() {
- synchronized(this.groups) {
- this.groups.clear();
- try {
- PolicyController controller = getPolicyControllerInstance();
- this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
- } catch (PAPException e) {
- String message = "Unable to retrieve Groups from server: " + e;
- logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
- }
-
- }
- }
-
- private PolicyController getPolicyControllerInstance(){
- return policyController != null ? getPolicyController() : new PolicyController();
- }
-
- @RequestMapping(value={"/get_AutoPushPoliciesContainerData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
- public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response){
- try{
- Set<String> scopes;
- List<String> roles;
- data = new ArrayList<>();
- String userId = UserUtils.getUserSession(request).getOrgUserId();
- Map<String, Object> model = new HashMap<>();
- ObjectMapper mapper = new ObjectMapper();
- PolicyController controller = policyController != null ? getPolicyController() : new PolicyController();
- List<Object> userRoles = controller.getRoles(userId);
- roles = new ArrayList<>();
- scopes = new HashSet<>();
- for(Object role: userRoles){
- Roles userRole = (Roles) role;
- roles.add(userRole.getRole());
- if(userRole.getScope() != null){
- if(userRole.getScope().contains(",")){
- String[] multipleScopes = userRole.getScope().split(",");
- for(int i =0; i < multipleScopes.length; i++){
- scopes.add(multipleScopes[i]);
- }
- }else{
- if(!"".equals(userRole.getScope())){
- scopes.add(userRole.getScope());
- }
- }
- }
- }
- if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) {
- data = commonClassDao.getData(PolicyVersion.class);
- }else{
- if(!scopes.isEmpty()){
- for(String scope : scopes){
- scope += "%";
- String query = "From PolicyVersion where policy_name like :scope and id > 0";
- SimpleBindings params = new SimpleBindings();
- params.put("scope", scope);
- List<Object> filterdatas = commonClassDao.getDataByQuery(query, params);
- if(filterdatas != null){
- for(int i =0; i < filterdatas.size(); i++){
- data.add(filterdatas.get(i));
- }
- }
- }
- }else{
- PolicyVersion emptyPolicyName = new PolicyVersion();
- emptyPolicyName.setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you");
- data.add(emptyPolicyName);
- }
- }
- model.put("policydatas", mapper.writeValueAsString(data));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
- }
- catch (Exception e){
- logger.error("Exception Occured"+e);
- }
- }
-
- @RequestMapping(value={"/auto_Push/PushPolicyToPDP.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
- public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
- try {
- ArrayList<Object> selectedPDPS = new ArrayList<>();
- ArrayList<String> selectedPoliciesInUI = new ArrayList<>();
- PolicyController controller = getPolicyControllerInstance();
- this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
- ObjectMapper mapper = new ObjectMapper();
- this.container = new PDPGroupContainer(controller.getPapEngine());
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
-
- String userId = UserUtils.getUserSession(request).getOrgUserId();
- logger.info("****************************************Logging UserID while Pushing Policy to PDP Group*****************************************");
- logger.info("UserId: " + userId + "Push Policy Data: "+ root.get("pushTabData").toString());
- logger.info("***********************************************************************************************************************************");
-
- AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
- for (Object pdpGroupId : adapter.getPdpDatas()) {
- LinkedHashMap<?, ?> selectedPDP = (LinkedHashMap<?, ?>)pdpGroupId;
- for(OnapPDPGroup pdpGroup : this.groups){
- if(pdpGroup.getId().equals(selectedPDP.get("id"))){
- selectedPDPS.add(pdpGroup);
- }
- }
- }
-
- for (Object policyId : adapter.getPolicyDatas()) {
- LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>)policyId;
- String policyName = selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml";
- selectedPoliciesInUI.add(policyName);
- }
-
- for (Object pdpDestinationGroupId : selectedPDPS) {
- Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
- Set<PDPPolicy> selectedPolicies = new HashSet<>();
- for (String policyId : selectedPoliciesInUI) {
- logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId);
-
- //
- // Get the current selection
- String selectedItem = policyId;
- //
- assert selectedItem != null;
- // create the id of the target file
- // Our standard for file naming is:
- // <domain>.<filename>.<version>.xml
- // since the file name usually has a ".xml", we need to strip
- // that
- // before adding the other parts
- String name = selectedItem.replace(File.separator, ".");
- String id = name;
- if (id.endsWith(".xml")) {
- id = id.replace(".xml", "");
- id = id.substring(0, id.lastIndexOf('.'));
- }
-
- // Default policy to be Root policy; user can change to deferred
- // later
-
- StdPDPPolicy selectedPolicy = null;
- String dbCheckName = name;
- if(dbCheckName.contains("Config_")){
- dbCheckName = dbCheckName.replace(".Config_", ":Config_");
- }else if(dbCheckName.contains("Action_")){
- dbCheckName = dbCheckName.replace(".Action_", ":Action_");
- }else if(dbCheckName.contains("Decision_")){
- dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
- }
- String[] split = dbCheckName.split(":");
- String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
- SimpleBindings policyParams = new SimpleBindings();
- policyParams.put("split_1", split[1]);
- policyParams.put("split_0", split[0]);
- List<Object> queryData = controller.getDataByQuery(query, policyParams);
- PolicyEntity policyEntity = (PolicyEntity) queryData.get(0);
- File temp = new File(name);
- BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
- bw.write(policyEntity.getPolicyData());
- bw.close();
- URI selectedURI = temp.toURI();
- try {
- //
- // Create the policy
- selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI);
- } catch (IOException e) {
- logger.error("Unable to create policy '" + name + "': "+ e.getMessage(), e);
- }
- StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId;
- if (selectedPolicy != null) {
- // Add Current policies from container
- for (OnapPDPGroup group : container.getGroups()) {
- if (group.getId().equals(selectedGroup.getId())) {
- currentPoliciesInGroup.addAll(group.getPolicies());
- }
- }
- // copy policy to PAP
- try {
- controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
- } catch (PAPException e) {
- logger.error("Exception Occured"+e);
- return null;
- }
- selectedPolicies.add(selectedPolicy);
- }
- temp.delete();
- }
- StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId;
- StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(), pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory());
- updatedGroupObject.setOnapPdps(pdpGroup.getOnapPdps());
- updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs());
- updatedGroupObject.setStatus(pdpGroup.getStatus());
- updatedGroupObject.setOperation("push");
-
- // replace the original set of Policies with the set from the
- // container (possibly modified by the user)
- // do not allow multiple copies of same policy
- Iterator<PDPPolicy> policyIterator = currentPoliciesInGroup.iterator();
- logger.debug("policyIterator....." + selectedPolicies);
- while (policyIterator.hasNext()) {
- PDPPolicy existingPolicy = policyIterator.next();
- for (PDPPolicy selPolicy : selectedPolicies) {
- if (selPolicy.getName().equals(existingPolicy.getName())) {
- if (selPolicy.getVersion().equals(existingPolicy.getVersion())) {
- if (selPolicy.getId().equals(existingPolicy.getId())) {
- policyIterator.remove();
- logger.debug("Removing policy: " + selPolicy);
- break;
- }
- } else {
- policyIterator.remove();
- logger.debug("Removing Old Policy version: "+ selPolicy);
- break;
- }
- }
- }
- }
-
- currentPoliciesInGroup.addAll(selectedPolicies);
- updatedGroupObject.setPolicies(currentPoliciesInGroup);
- this.container.updateGroup(updatedGroupObject);
-
- response.setCharacterEncoding(UTF8);
- response.setContentType("application / json");
- request.setCharacterEncoding(UTF8);
-
- PrintWriter out = response.getWriter();
- refreshGroups();
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
- JSONObject j = new JSONObject(msg);
- out.write(j.toString());
- //
- // Why is this here? This defeats the purpose of the loop??
- // Sonar says to remove it or make it conditional
- //
- return null;
- }
- }
- catch (Exception e){
- response.setCharacterEncoding(UTF8);
- request.setCharacterEncoding(UTF8);
- PrintWriter out = response.getWriter();
- logger.error(e);
- out.write(PolicyUtils.CATCH_EXCEPTION);
- }
- return null;
- }
-
- @SuppressWarnings("unchecked")
- @RequestMapping(value={"/auto_Push/remove_GroupPolicies.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
- public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
- try {
- PolicyController controller = getPolicyControllerInstance();
- this.container = new PDPGroupContainer(controller.getPapEngine());
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- StdPDPGroup group = mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
- JsonNode removePolicyData = root.get("data");
-
- String userId = UserUtils.getUserSession(request).getOrgUserId();
- logger.info("****************************************Logging UserID while Removing Policy from PDP Group*****************************************");
- logger.info("UserId: " + userId + "PDP Group Data: "+ root.get("activePdpGroup").toString() + "Remove Policy Data: "+root.get("data"));
- logger.info("***********************************************************************************************************************************");
-
- policyContainer = new PDPPolicyContainer(group);
- if(removePolicyData.size() > 0){
- for(int i = 0 ; i < removePolicyData.size(); i++){
- String polData = removePolicyData.get(i).toString();
- this.policyContainer.removeItem(polData);
- }
- Set<PDPPolicy> changedPolicies = new HashSet<>();
- changedPolicies.addAll((Collection<PDPPolicy>) this.policyContainer.getItemIds());
- StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(), group.getDescription(),null);
- updatedGroupObject.setPolicies(changedPolicies);
- updatedGroupObject.setOnapPdps(group.getOnapPdps());
- updatedGroupObject.setPipConfigs(group.getPipConfigs());
- updatedGroupObject.setStatus(group.getStatus());
- updatedGroupObject.setOperation("delete");
- this.container.updateGroup(updatedGroupObject);
- }
-
- response.setCharacterEncoding(UTF8);
- response.setContentType("application / json");
- request.setCharacterEncoding(UTF8);
-
- PrintWriter out = response.getWriter();
- refreshGroups();
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
- JSONObject j = new JSONObject(msg);
-
- out.write(j.toString());
-
- return null;
- }
- catch (Exception e){
- response.setCharacterEncoding(UTF8);
- request.setCharacterEncoding(UTF8);
- PrintWriter out = response.getWriter();
- logger.error(e);
- out.write(PolicyUtils.CATCH_EXCEPTION);
- }
- return null;
- }
+ @Autowired
+ CommonClassDao commonClassDao;
+
+ private PDPGroupContainer container;
+ private PDPPolicyContainer policyContainer;
+ private PolicyController policyController;
+ protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<>());
+
+ public PolicyController getPolicyController() {
+ return policyController;
+ }
+
+ public void setPolicyController(PolicyController policyController) {
+ this.policyController = policyController;
+ }
+
+ public synchronized void refreshGroups() {
+ synchronized (this.groups) {
+ this.groups.clear();
+ try {
+ PolicyController controller = getPolicyControllerInstance();
+ this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
+ } catch (PAPException e) {
+ String message = "Unable to retrieve Groups from server: " + e;
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
+ }
+
+ }
+ }
+
+ private PolicyController getPolicyControllerInstance() {
+ return policyController != null ? getPolicyController() : new PolicyController();
+ }
+
+ @RequestMapping(value = {"/get_AutoPushPoliciesContainerData"}, method = {
+ RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE)
+ public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response) {
+ try {
+ Set<String> scopes = new HashSet<>();
+ List<String> roles = new ArrayList<>();
+ List<Object> data = new ArrayList<>();
+ Map<String, Object> model = new HashMap<>();
+
+ String userId = UserUtils.getUserSession(request).getOrgUserId();
+
+ PolicyController controller = policyController != null ? getPolicyController() : new PolicyController();
+ List<Object> userRoles = controller.getRoles(userId);
+ for (Object role : userRoles) {
+ Roles userRole = (Roles) role;
+ roles.add(userRole.getRole());
+ scopes.addAll(Stream.of(userRole.getScope().split(","))
+ .map(String::new)
+ .collect(Collectors.toSet())
+ );
+ }
+ if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) {
+ data = commonClassDao.getData(PolicyVersion.class);
+ } else {
+ if (!scopes.isEmpty()) {
+ for (String scope : scopes) {
+ scope += "%";
+ String query = "From PolicyVersion where policy_name like :scope and id > 0";
+ SimpleBindings params = new SimpleBindings();
+ params.put("scope", scope);
+ List<Object> filterdatas = commonClassDao.getDataByQuery(query, params);
+ if (filterdatas != null) {
+ data.addAll(filterdatas);
+ }
+ }
+ } else {
+ PolicyVersion emptyPolicyName = new PolicyVersion();
+ emptyPolicyName
+ .setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you");
+ data.add(emptyPolicyName);
+ }
+ }
+ ObjectMapper mapper = new ObjectMapper();
+ model.put("policydatas", mapper.writeValueAsString(data));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ } catch (Exception e) {
+ logger.error("Exception Occurred" + e);
+ }
+ }
+
+ @RequestMapping(value = { "/auto_Push/PushPolicyToPDP.htm" }, method = { RequestMethod.POST })
+ public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
+ try {
+ ArrayList<Object> selectedPDPS = new ArrayList<>();
+ ArrayList<String> selectedPoliciesInUI = new ArrayList<>();
+ PolicyController controller = getPolicyControllerInstance();
+ this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
+ ObjectMapper mapper = new ObjectMapper();
+ this.container = new PDPGroupContainer(controller.getPapEngine());
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+
+ String userId = UserUtils.getUserSession(request).getOrgUserId();
+ logger.info(
+ "****************************************Logging UserID while Pushing Policy to PDP Group*****************************************");
+ logger.info("UserId: " + userId + "Push Policy Data: " + root.get("pushTabData").toString());
+ logger.info(
+ "***********************************************************************************************************************************");
+
+ AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
+ for (Object pdpGroupId : adapter.getPdpDatas()) {
+ LinkedHashMap<?, ?> selectedPDP = (LinkedHashMap<?, ?>) pdpGroupId;
+ for (OnapPDPGroup pdpGroup : this.groups) {
+ if (pdpGroup.getId().equals(selectedPDP.get("id"))) {
+ selectedPDPS.add(pdpGroup);
+ }
+ }
+ }
+
+ for (Object policyId : adapter.getPolicyDatas()) {
+ LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>) policyId;
+ String policyName = selected.get("policyName").toString() + "."
+ + selected.get("activeVersion").toString() + ".xml";
+ selectedPoliciesInUI.add(policyName);
+ }
+
+ for (Object pdpDestinationGroupId : selectedPDPS) {
+ Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
+ Set<PDPPolicy> selectedPolicies = new HashSet<>();
+ for (String policyId : selectedPoliciesInUI) {
+ logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId);
+
+ //
+ // Get the current selection
+ //
+ assert policyId != null;
+ // create the id of the target file
+ // Our standard for file naming is:
+ // <domain>.<filename>.<version>.xml
+ // since the file name usually has a ".xml", we need to strip
+ // that
+ // before adding the other parts
+ String name = policyId.replace(File.separator, ".");
+ String id = name;
+ if (id.endsWith(".xml")) {
+ id = id.replace(".xml", "");
+ id = id.substring(0, id.lastIndexOf('.'));
+ }
+
+ // Default policy to be Root policy; user can change to deferred
+ // later
+
+ StdPDPPolicy selectedPolicy = null;
+ String dbCheckName = name;
+ if (dbCheckName.contains("Config_")) {
+ dbCheckName = dbCheckName.replace(".Config_", ":Config_");
+ } else if (dbCheckName.contains("Action_")) {
+ dbCheckName = dbCheckName.replace(".Action_", ":Action_");
+ } else if (dbCheckName.contains("Decision_")) {
+ dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
+ }
+ String[] split = dbCheckName.split(":");
+ String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
+ SimpleBindings policyParams = new SimpleBindings();
+ policyParams.put("split_1", split[1]);
+ policyParams.put("split_0", split[0]);
+ List<Object> queryData = controller.getDataByQuery(query, policyParams);
+ PolicyEntity policyEntity = (PolicyEntity) queryData.get(0);
+ File temp = new File(name);
+ BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
+ bw.write(policyEntity.getPolicyData());
+ bw.close();
+ URI selectedURI = temp.toURI();
+ try {
+ // Create the policy
+ selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI);
+ } catch (IOException e) {
+ logger.error("Unable to create policy '" + name + "': " + e.getMessage(), e);
+ }
+ StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId;
+ if (selectedPolicy != null) {
+ // Add Current policies from container
+ for (OnapPDPGroup group : container.getGroups()) {
+ if (group.getId().equals(selectedGroup.getId())) {
+ currentPoliciesInGroup.addAll(group.getPolicies());
+ }
+ }
+ // copy policy to PAP
+ try {
+ controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
+ } catch (PAPException e) {
+ logger.error("Exception Occured" + e);
+ return null;
+ }
+ selectedPolicies.add(selectedPolicy);
+ }
+ temp.delete();
+ }
+ StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId;
+ StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(),
+ pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory());
+ updatedGroupObject.setOnapPdps(pdpGroup.getOnapPdps());
+ updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs());
+ updatedGroupObject.setStatus(pdpGroup.getStatus());
+ updatedGroupObject.setOperation("push");
+
+ // replace the original set of Policies with the set from the
+ // container (possibly modified by the user)
+ // do not allow multiple copies of same policy
+ Iterator<PDPPolicy> policyIterator = currentPoliciesInGroup.iterator();
+ logger.debug("policyIterator....." + selectedPolicies);
+ while (policyIterator.hasNext()) {
+ PDPPolicy existingPolicy = policyIterator.next();
+ for (PDPPolicy selPolicy : selectedPolicies) {
+ if (selPolicy.getName().equals(existingPolicy.getName())) {
+ if (selPolicy.getVersion().equals(existingPolicy.getVersion())) {
+ if (selPolicy.getId().equals(existingPolicy.getId())) {
+ policyIterator.remove();
+ logger.debug("Removing policy: " + selPolicy);
+ break;
+ }
+ } else {
+ policyIterator.remove();
+ logger.debug("Removing Old Policy version: " + selPolicy);
+ break;
+ }
+ }
+ }
+ }
+
+ currentPoliciesInGroup.addAll(selectedPolicies);
+ updatedGroupObject.setPolicies(currentPoliciesInGroup);
+ this.container.updateGroup(updatedGroupObject);
+
+ response.setCharacterEncoding(UTF8);
+ response.setContentType("application / json");
+ request.setCharacterEncoding(UTF8);
+
+ PrintWriter out = response.getWriter();
+ refreshGroups();
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
+ JSONObject j = new JSONObject(msg);
+ out.write(j.toString());
+ //
+ // Why is this here? This defeats the purpose of the loop??
+ // Sonar says to remove it or make it conditional
+ //
+ return null;
+ }
+ } catch (Exception e) {
+ response.setCharacterEncoding(UTF8);
+ request.setCharacterEncoding(UTF8);
+ PrintWriter out = response.getWriter();
+ logger.error(e);
+ out.write(PolicyUtils.CATCH_EXCEPTION);
+ }
+ return null;
+ }
+
+ @SuppressWarnings("unchecked")
+ @RequestMapping(value = { "/auto_Push/remove_GroupPolicies.htm" }, method = { RequestMethod.POST })
+ public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
+ try {
+ PolicyController controller = getPolicyControllerInstance();
+ this.container = new PDPGroupContainer(controller.getPapEngine());
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ StdPDPGroup group = mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
+ JsonNode removePolicyData = root.get("data");
+
+ String userId = UserUtils.getUserSession(request).getOrgUserId();
+ logger.info(
+ "****************************************Logging UserID while Removing Policy from PDP Group*****************************************");
+ logger.info("UserId: " + userId + "PDP Group Data: " + root.get("activePdpGroup").toString()
+ + "Remove Policy Data: " + root.get("data"));
+ logger.info(
+ "***********************************************************************************************************************************");
+
+ policyContainer = new PDPPolicyContainer(group);
+ if (removePolicyData.size() > 0) {
+ IntStream.range(0, removePolicyData.size()).mapToObj(i -> removePolicyData.get(i).toString())
+ .forEach(polData -> this.policyContainer.removeItem(polData));
+ Set<PDPPolicy> changedPolicies = new HashSet<>(
+ (Collection<PDPPolicy>) this.policyContainer.getItemIds());
+ StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(),
+ group.getDescription(), null);
+ updatedGroupObject.setPolicies(changedPolicies);
+ updatedGroupObject.setOnapPdps(group.getOnapPdps());
+ updatedGroupObject.setPipConfigs(group.getPipConfigs());
+ updatedGroupObject.setStatus(group.getStatus());
+ updatedGroupObject.setOperation("delete");
+ this.container.updateGroup(updatedGroupObject);
+ }
+
+ response.setCharacterEncoding(UTF8);
+ response.setContentType("application / json");
+ request.setCharacterEncoding(UTF8);
+
+ PrintWriter out = response.getWriter();
+ refreshGroups();
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
+ JSONObject j = new JSONObject(msg);
+
+ out.write(j.toString());
+ return null;
+ } catch (Exception e) {
+ response.setCharacterEncoding(UTF8);
+ request.setCharacterEncoding(UTF8);
+ PrintWriter out = response.getWriter();
+ logger.error(e);
+ out.write(PolicyUtils.CATCH_EXCEPTION);
+ }
+ return null;
+ }
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java
index e7ed57add..67a94474f 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,6 +21,15 @@
package org.onap.policy.controller;
+import com.att.research.xacml.util.XACMLProperties;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.ObjectWriter;
+import com.fasterxml.jackson.databind.node.JsonNodeFactory;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.google.gson.Gson;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
@@ -47,7 +56,6 @@ import java.util.TreeMap;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
-
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
@@ -57,7 +65,13 @@ import javax.json.JsonReader;
import javax.json.JsonValue;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
@@ -86,1419 +100,1562 @@ import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
-import com.att.research.xacml.util.XACMLProperties;
-import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.ObjectWriter;
-import com.fasterxml.jackson.databind.node.JsonNodeFactory;
-import com.fasterxml.jackson.databind.node.ObjectNode;
-import com.google.gson.Gson;
-
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
@Controller
@RequestMapping("/")
public class CreateDcaeMicroServiceController extends RestrictedBaseController {
- private static final Logger LOGGER = FlexLogger.getLogger(CreateDcaeMicroServiceController.class);
-
- private static CommonClassDao commonClassDao;
-
- public static CommonClassDao getCommonClassDao() {
- return commonClassDao;
- }
-
- public static void setCommonClassDao(CommonClassDao commonClassDao) {
- CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
- }
-
- private MicroServiceModels newModel;
- private String newFile;
- private String directory;
- private List<String> modelList = new ArrayList<>();
- private List<String> dirDependencyList = new ArrayList<>();
- private LinkedHashMap<String,MSAttributeObject > classMap = new LinkedHashMap<>();
- String referenceAttributes;
- String attributeString;
- Set<String> allManyTrueKeys= new HashSet <>();
-
- public static final String DATATYPE = "data_types.policy.data.";
- public static final String PROPERTIES=".properties.";
- public static final String TYPE=".type";
- public static final String STRING="string";
- public static final String INTEGER="integer";
- public static final String LIST="list";
- public static final String DEFAULT=".default";
- public static final String REQUIRED=".required";
- public static final String MATCHABLE=".matchable";
- public static final String MANYFALSE=":MANY-false";
-
-
- @Autowired
- private CreateDcaeMicroServiceController(CommonClassDao commonClassDao){
- CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
- }
-
- public CreateDcaeMicroServiceController(){
- // Empty Constructor
- }
-
- protected PolicyRestAdapter policyAdapter = null;
- private int priorityCount;
- private Map<String, String> attributesListRefMap = new HashMap<>();
- private Map<String, LinkedList<String>> arrayTextList = new HashMap<>();
-
- public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
-
- String jsonContent = null;
- try{
- LOGGER.info("policyJSON :" + (root.get("policyJSON")).toString());
-
- String tempJson = root.get("policyJSON").toString();
-
- //---replace empty value with the value below before calling decodeContent method.
- String dummyValue = "*empty-value*" + UUID.randomUUID().toString();
- LOGGER.info("dummyValue:" + dummyValue);
- tempJson = StringUtils.replaceEach(tempJson, new String[]{"\"\""}, new String[]{"\""+dummyValue+"\""});
- ObjectMapper mapper = new ObjectMapper();
- JsonNode tempJsonNode = mapper.readTree(tempJson);
- jsonContent = decodeContent(tempJsonNode).toString();
- constructJson(policyData, jsonContent, dummyValue);
- }catch(Exception e){
- LOGGER.error("Error while decoding microservice content", e);
- }
-
- return policyData;
- }
-
- private GroupPolicyScopeList getPolicyObject(String policyScope) {
- return (GroupPolicyScopeList) commonClassDao.getEntityItem(GroupPolicyScopeList.class, "name", policyScope);
- }
-
- private PolicyRestAdapter constructJson(PolicyRestAdapter policyAdapter, String jsonContent, String dummyValue) {
- ObjectWriter om = new ObjectMapper().writer();
- String json="";
- DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject();
- MicroServiceModels returnModel = new MicroServiceModels();
- microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS));
- if(policyAdapter.getServiceType() !=null){
- microServiceObject.setService(policyAdapter.getServiceType());
- microServiceObject.setVersion(policyAdapter.getVersion());
- returnModel = getAttributeObject(microServiceObject.getService(), microServiceObject.getVersion());
- }
- if (returnModel.getAnnotation()==null || returnModel.getAnnotation().isEmpty()){
- if(policyAdapter.getUuid()!=null){
- microServiceObject.setUuid(policyAdapter.getUuid());
- }
- if(policyAdapter.getLocation()!=null){
- microServiceObject.setLocation(policyAdapter.getLocation());
- }
- if(policyAdapter.getConfigName()!=null){
- microServiceObject.setConfigName(policyAdapter.getConfigName());
- }
- GroupPolicyScopeList policyScopeValue = getPolicyObject(policyAdapter.getPolicyScope());
- if(policyScopeValue!=null){
- microServiceObject.setPolicyScope(policyScopeValue.getGroupList());
- }
- }
-
- if(policyAdapter.getPolicyName()!=null){
- microServiceObject.setPolicyName(policyAdapter.getPolicyName());
- }
- if(policyAdapter.getPolicyDescription()!=null){
- microServiceObject.setDescription(policyAdapter.getPolicyDescription());
- }
- if (policyAdapter.getPriority()!=null){
- microServiceObject.setPriority(policyAdapter.getPriority());
- }else {
- microServiceObject.setPriority("9999");
- }
-
- if (policyAdapter.getRiskLevel()!=null){
- microServiceObject.setRiskLevel(policyAdapter.getRiskLevel());
- }
- if (policyAdapter.getRiskType()!=null){
- microServiceObject.setRiskType(policyAdapter.getRiskType());
- }
- if (policyAdapter.getGuard()!=null){
- microServiceObject.setGuard(policyAdapter.getGuard());
- }
- microServiceObject.setContent(jsonContent);
-
- try {
- json = om.writeValueAsString(microServiceObject);
- } catch (JsonProcessingException e) {
- LOGGER.error("Error writing out the object", e);
- }
- LOGGER.info("input json: " + json);
- LOGGER.info("input jsonContent: " + jsonContent);
- String cleanJson = cleanUPJson(json);
- //--- reset empty value back after called cleanUPJson method and before calling removeNullAttributes
- String tempJson = StringUtils.replaceEach(cleanJson, new String[]{"\""+dummyValue+"\""}, new String[]{"\"\""});
- LOGGER.info("tempJson: " + tempJson);
- cleanJson = removeNullAttributes(tempJson);
- policyAdapter.setJsonBody(cleanJson);
- return policyAdapter;
- }
-
- public String removeNullAttributes(String cleanJson) {
- ObjectMapper mapper = new ObjectMapper();
-
- try {
- JsonNode rootNode = mapper.readTree(cleanJson);
- JsonNode returnNode = mapper.readTree(cleanJson);
- Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
- boolean remove = false;
- JsonObject removed = null;
- boolean contentChanged = false;
- while (fieldsIterator.hasNext()) {
- Map.Entry<String, JsonNode> field = fieldsIterator.next();
- final String key = field.getKey();
- final JsonNode value = field.getValue();
- if("content".equalsIgnoreCase(key)){
- String contentStr = value.toString();
- try(JsonReader reader = Json.createReader(new StringReader(contentStr))){
- JsonObject jsonContent = reader.readObject();
- removed = removeNull(jsonContent);
- if(!jsonContent.toString().equals(removed.toString())){
- contentChanged = true;
- }
+ private static final Logger LOGGER = FlexLogger.getLogger(CreateDcaeMicroServiceController.class);
+
+ private static CommonClassDao commonClassDao;
+
+ public static CommonClassDao getCommonClassDao() {
+ return commonClassDao;
+ }
+
+ public static void setCommonClassDao(CommonClassDao commonClassDao) {
+ CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
+ }
+
+ private MicroServiceModels newModel;
+ private String newFile;
+ private String directory;
+ private List<String> modelList = new ArrayList<>();
+ private List<String> dirDependencyList = new ArrayList<>();
+ private LinkedHashMap<String, MSAttributeObject> classMap = new LinkedHashMap<>();
+ String referenceAttributes;
+ String attributeString;
+ Set<String> allManyTrueKeys = new HashSet<>();
+
+ public static final String DATATYPE = "data_types.policy.data.";
+ public static final String PROPERTIES = ".properties.";
+ public static final String TYPE = ".type";
+ public static final String STRING = "string";
+ public static final String INTEGER = "integer";
+ public static final String LIST = "list";
+ public static final String DEFAULT = ".default";
+ public static final String REQUIRED = ".required";
+ public static final String MATCHABLE = ".matchable";
+ public static final String MANYFALSE = ":MANY-false";
+
+
+ @Autowired
+ private CreateDcaeMicroServiceController(CommonClassDao commonClassDao) {
+ CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
+ }
+
+ public CreateDcaeMicroServiceController() {
+ // Empty Constructor
+ }
+
+ protected PolicyRestAdapter policyAdapter = null;
+ private int priorityCount;
+ private Map<String, String> attributesListRefMap = new HashMap<>();
+ private Map<String, LinkedList<String>> arrayTextList = new HashMap<>();
+ private Map<String, String> jsonStringValues = new HashMap<>();
+
+ public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
+
+ String jsonContent = null;
+ try {
+ LOGGER.info("policyJSON :" + (root.get("policyJSON")).toString());
+
+ String tempJson = root.get("policyJSON").toString();
+ JSONObject policyJSON = new JSONObject(root.get("policyJSON").toString());
+ if (policyJSON != null) {
+ saveOriginalJsonObject(policyJSON, jsonStringValues);
+ }
+ // ---replace empty value with the value below before calling decodeContent method.
+ String dummyValue = "*empty-value*" + UUID.randomUUID().toString();
+ LOGGER.info("dummyValue:" + dummyValue);
+ tempJson =
+ StringUtils.replaceEach(tempJson, new String[] {"\"\""}, new String[] {"\"" + dummyValue + "\""});
+ ObjectMapper mapper = new ObjectMapper();
+ JsonNode tempJsonNode = mapper.readTree(tempJson);
+ jsonContent = decodeContent(tempJsonNode).toString();
+ constructJson(policyData, jsonContent, dummyValue);
+ } catch (Exception e) {
+ LOGGER.error("Error while decoding microservice content", e);
+ }
+
+ // ----Here is the final step to reset the original value back.
+ if(policyData.getJsonBody() != null && jsonStringValues.size() > 0){
+ String contentBody = policyData.getJsonBody();
+ JSONObject contentJson= new JSONObject(contentBody);
+ JSONObject content = contentJson.getJSONObject("content");
+ content = setOriginalJsonObject(content, jsonStringValues);
+ contentJson.put("content", content);
+ policyData.setJsonBody(contentJson.toString());
+ }
+
+ return policyData;
+ }
+
+ /**
+ * To save the original JSON string from the root.
+ *
+ * @param jsonObj holds the value from the root.
+ * @param jsonStringValues value get saved.
+ */
+ private void saveOriginalJsonObject(JSONObject jsonObj, Map<String, String> jsonStringValues) {
+ for (Object key : jsonObj.keySet()) {
+ String keyStr = (String) key;
+ Object keyvalue = jsonObj.get(keyStr);
+ if (keyvalue.toString().contains("{\\\"") || keyvalue.toString().contains("\\\"")) {
+ jsonStringValues.put(keyStr, keyvalue.toString());
+ }
+
+ // for nested objects iteration if required
+ if (keyvalue instanceof JSONObject) {
+ saveOriginalJsonObject((JSONObject) keyvalue, jsonStringValues);
+ }
+ }
+ }
+
+ /**
+ * To reset the original JSON string back associated to its key.
+ *
+ * @param jsonObj holds the original json.
+ * @param jsonStringValues value to be reset.
+ * @return
+ */
+ private JSONObject setOriginalJsonObject(JSONObject jsonObj , Map<String, String> jsonStringValues) {
+ for (Object key : jsonObj.keySet()) {
+ String keyStr = (String)key;
+ Object keyvalue = jsonObj.get(keyStr);
+ String originalValue = getOriginalValue(keyStr);
+ if (originalValue != null) {
+ jsonObj.put(keyStr, originalValue);
+ }
+
+ //for nested objects iteration if required
+ if (keyvalue instanceof JSONObject) {
+ setOriginalJsonObject((JSONObject)keyvalue, jsonStringValues);
+ jsonObj.put(keyStr, originalValue);
+ }
+
+ if (keyvalue instanceof JSONArray) {
+ for (int i = 0; i < ((JSONArray)keyvalue).length(); i++) {
+ JSONObject temp = ((JSONArray)keyvalue).getJSONObject(i);
+ setOriginalJsonObject(temp, jsonStringValues);
+ }
+ }
+ }
+
+ return jsonObj;
+ }
+
+ private GroupPolicyScopeList getPolicyObject(String policyScope) {
+ return (GroupPolicyScopeList) commonClassDao.getEntityItem(GroupPolicyScopeList.class, "name", policyScope);
+ }
+
+ private PolicyRestAdapter constructJson(PolicyRestAdapter policyAdapter, String jsonContent, String dummyValue) {
+ ObjectWriter om = new ObjectMapper().writer();
+ String json = "";
+ DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject();
+ MicroServiceModels returnModel = new MicroServiceModels();
+ microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS));
+ if (policyAdapter.getServiceType() != null) {
+ microServiceObject.setService(policyAdapter.getServiceType());
+ microServiceObject.setVersion(policyAdapter.getVersion());
+ returnModel = getAttributeObject(microServiceObject.getService(), microServiceObject.getVersion());
+ }
+ if (returnModel.getAnnotation() == null || returnModel.getAnnotation().isEmpty()) {
+ if (policyAdapter.getUuid() != null) {
+ microServiceObject.setUuid(policyAdapter.getUuid());
+ }
+ if (policyAdapter.getLocation() != null) {
+ microServiceObject.setLocation(policyAdapter.getLocation());
+ }
+ if (policyAdapter.getConfigName() != null) {
+ microServiceObject.setConfigName(policyAdapter.getConfigName());
+ }
+ GroupPolicyScopeList policyScopeValue = getPolicyObject(policyAdapter.getPolicyScope());
+ if (policyScopeValue != null) {
+ microServiceObject.setPolicyScope(policyScopeValue.getGroupList());
+ }
+ }
+
+ if (policyAdapter.getPolicyName() != null) {
+ microServiceObject.setPolicyName(policyAdapter.getPolicyName());
+ }
+ if (policyAdapter.getPolicyDescription() != null) {
+ microServiceObject.setDescription(policyAdapter.getPolicyDescription());
+ }
+ if (policyAdapter.getPriority() != null) {
+ microServiceObject.setPriority(policyAdapter.getPriority());
+ } else {
+ microServiceObject.setPriority("9999");
+ }
+
+ if (policyAdapter.getRiskLevel() != null) {
+ microServiceObject.setRiskLevel(policyAdapter.getRiskLevel());
+ }
+ if (policyAdapter.getRiskType() != null) {
+ microServiceObject.setRiskType(policyAdapter.getRiskType());
+ }
+ if (policyAdapter.getGuard() != null) {
+ microServiceObject.setGuard(policyAdapter.getGuard());
+ }
+ microServiceObject.setContent(jsonContent);
+
+ try {
+ json = om.writeValueAsString(microServiceObject);
+ } catch (JsonProcessingException e) {
+ LOGGER.error("Error writing out the object", e);
+ }
+ LOGGER.info("input json: " + json);
+ LOGGER.info("input jsonContent: " + jsonContent);
+ String cleanJson = cleanUPJson(json);
+ // --- reset empty value back after called cleanUPJson method and before calling removeNullAttributes
+ String tempJson =
+ StringUtils.replaceEach(cleanJson, new String[] {"\"" + dummyValue + "\""}, new String[] {"\"\""});
+ LOGGER.info("tempJson: " + tempJson);
+ cleanJson = removeNullAttributes(tempJson);
+ policyAdapter.setJsonBody(cleanJson);
+ return policyAdapter;
+ }
+
+ public String removeNullAttributes(String cleanJson) {
+ ObjectMapper mapper = new ObjectMapper();
+
+ try {
+ JsonNode rootNode = mapper.readTree(cleanJson);
+ JsonNode returnNode = mapper.readTree(cleanJson);
+ Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
+ boolean remove = false;
+ JsonObject removed = null;
+ boolean contentChanged = false;
+ while (fieldsIterator.hasNext()) {
+ Map.Entry<String, JsonNode> field = fieldsIterator.next();
+ final String key = field.getKey();
+ final JsonNode value = field.getValue();
+ if ("content".equalsIgnoreCase(key)) {
+ String contentStr = value.toString();
+ try (JsonReader reader = Json.createReader(new StringReader(contentStr))) {
+ JsonObject jsonContent = reader.readObject();
+ removed = removeNull(jsonContent);
+ if (!jsonContent.toString().equals(removed.toString())) {
+ contentChanged = true;
+ }
}
- if (value==null || value.isNull()){
- ((ObjectNode) returnNode).remove(key);
- remove = true;
- }
- }
- if (remove){
- cleanJson = returnNode.toString();
- }
- if (value==null || value.isNull()){
- ((ObjectNode) returnNode).remove(key);
- remove = true;
- }
- }
- if (remove){
- cleanJson = returnNode.toString();
- }
-
- if(contentChanged){
- //set modified content to cleanJson
- JSONObject jObject = new JSONObject(cleanJson);
- jObject.put("content",removed.toString());
- cleanJson = cleanUPJson(jObject.toString());
- }
-
- } catch (IOException e) {
- LOGGER.error("Error writing out the JsonNode",e);
- }
- return cleanJson;
- }
-
- public static JsonArray removeNull(JsonArray array) {
- JsonArrayBuilder builder = Json.createArrayBuilder();
- int i = 0;
- for (Iterator<JsonValue> it = array.iterator(); it.hasNext(); ++i) {
- JsonValue value = it.next();
- switch (value.getValueType()) {
- case ARRAY:
- JsonArray a = removeNull(array.getJsonArray(i));
- if (!a.isEmpty())
- builder.add(a);
- break;
- case OBJECT:
- JsonObject object = removeNull(array.getJsonObject(i));
- if (!object.isEmpty())
- builder.add(object);
- break;
- case STRING:
- String s = array.getString(i);
- if (s != null && !s.isEmpty())
- builder.add(s);
- break;
- case NUMBER:
- builder.add(array.getJsonNumber(i));
- break;
- case TRUE:
- case FALSE:
- builder.add(array.getBoolean(i));
- break;
- case NULL:
- break;
- }
- }
- return builder.build();
- }
-
- public static JsonObject removeNull(JsonObject obj) {
- JsonObjectBuilder builder = Json.createObjectBuilder();
- for (Iterator<Entry<String, JsonValue>> it = obj.entrySet().iterator(); it.hasNext();) {
- Entry<String, JsonValue> e = it.next();
- String key = e.getKey();
- JsonValue value = e.getValue();
- switch (value.getValueType()) {
- case ARRAY:
- JsonArray array = removeNull(obj.getJsonArray(key));
- if (!array.isEmpty())
- builder.add(key, array);
- break;
- case OBJECT:
- JsonObject object = removeNull(obj.getJsonObject(key));
- if (!object.isEmpty())
- builder.add(key, object);
- break;
- case STRING:
- String s = obj.getString(key);
- if (s != null && !s.isEmpty())
- builder.add(key, s);
- break;
- case NUMBER:
- builder.add(key, obj.getJsonNumber(key));
- break;
- case TRUE:
- case FALSE:
- builder.add(key, obj.getBoolean(key));
- break;
- case NULL:
- break;
- }
- }
- return builder.build();
- }
-
- public String cleanUPJson(String json) {
- String cleanJson = StringUtils.replaceEach(json, new String[]{"\\\\", "\\\\\\", "\\\\\\\\"}, new String[]{"\\", "\\", "\\"});
- cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\"}, new String[]{"\\"});
- cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\", "[[", "]]"}, new String[]{"\\", "[", "]"});
-
- cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\"", "\\\"", "\"[{", "}]\""}, new String[]{"\"", "\"", "[{", "}]"});
- cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[{", "}]\""}, new String[]{"[{", "}]"});
- cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"});
- cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"{", "}\""}, new String[]{"{", "}"});
- cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\"\"", "\"\""}, new String[]{"\"", "\""});
- cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\""}, new String[]{""});
- cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\""}, new String[]{"\""});
- cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\\\\\\"}, new String[]{"\""});
- cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\\""}, new String[]{"\""});
- cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"});
- return cleanJson;
- }
-
- public JSONObject decodeContent(JsonNode jsonNode){
- Iterator<JsonNode> jsonElements = jsonNode.elements();
- Iterator<String> jsonKeys = jsonNode.fieldNames();
- Map<String,String> element = new TreeMap<>();
- while(jsonElements.hasNext() && jsonKeys.hasNext()){
- element.put(jsonKeys.next(), jsonElements.next().toString());
- }
- JSONObject jsonResult = new JSONObject();
- JSONArray jsonArray = null;
- String oldValue = null;
- String nodeKey = null;
- String arryKey = null;
- Boolean isArray = false;
- JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
- ObjectNode node = nodeFactory.objectNode();
- String prevKey = null;
- String presKey;
- for(Entry<String, String> entry: element.entrySet()){
- String key = entry.getKey();
- String value = entry.getValue();
- if(key.contains(".")){
- presKey = key.substring(0,key.indexOf('.'));
- }else if(key.contains("@")){
- presKey = key.substring(0,key.indexOf('@'));
- }else{
- presKey = key;
- }
- // first check if we are different from old.
- LOGGER.info(key+"\n");
- if(jsonArray!=null && jsonArray.length()>0 && key.contains("@") && !key.contains(".") && oldValue!=null){
- if(!oldValue.equals(key.substring(0,key.indexOf('@')))){
- jsonResult.put(oldValue, jsonArray);
- jsonArray = new JSONArray();
- }
- }else if(jsonArray!=null && jsonArray.length()>0 && !presKey.equals(prevKey) && oldValue!=null){
- jsonResult.put(oldValue, jsonArray);
- isArray = false;
- jsonArray = new JSONArray();
- }
-
- prevKey = presKey;
- //
- if(key.contains(".")){
- if(nodeKey==null){
- nodeKey = key.substring(0,key.indexOf('.'));
- }
- if(nodeKey.equals(key.substring(0,key.indexOf('.')))){
- node.put(key.substring(key.indexOf('.')+1), value);
- }else{
- if(node.size()!=0){
- if(nodeKey.contains("@")){
- if(arryKey==null){
- arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
- }
- if(nodeKey.endsWith("@0")){
- isArray = true;
- jsonArray = new JSONArray();
- }
- if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf('@')))){
- jsonArray.put(decodeContent(node));
- }
- if((key.contains("@") && !arryKey.equals(key.substring(0,nodeKey.indexOf('@')))) || !key.contains("@")){
- jsonResult.put(arryKey, jsonArray);
- jsonArray = new JSONArray();
- }
- arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
- }else{
- isArray = false;
- jsonResult.put(nodeKey, decodeContent(node));
- }
- node = nodeFactory.objectNode();
- }
- nodeKey = key.substring(0,key.indexOf('.'));
- if(nodeKey.contains("@")){
- arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
- }
- node.put(key.substring(key.indexOf('.')+1), value);
- }
- }else {
- if(node.size()!=0){
- if(nodeKey.contains("@")){
- if(arryKey==null){
- arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
- }
- if(nodeKey.endsWith("@0")){
- isArray = true;
- jsonArray = new JSONArray();
- }
- if(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf('@')))){
- jsonArray.put(decodeContent(node));
- }
- jsonResult.put(arryKey, jsonArray);
- jsonArray = new JSONArray();
- arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
- }else{
- isArray = false;
- jsonResult.put(nodeKey, decodeContent(node));
- }
- node = nodeFactory.objectNode();
- }
- if(key.contains("@")){
- isArray = true;
- if(key.endsWith("@0")|| jsonArray==null){
- jsonArray = new JSONArray();
- }
- }else if(!key.contains("@")){
- isArray = false;
- }
- if(isArray){
- if(oldValue==null){
- oldValue = key.substring(0,key.indexOf('@'));
- }
- if(oldValue!=prevKey){
- oldValue = key.substring(0,key.indexOf('@'));
- }
- if(oldValue.equals(key.substring(0,key.indexOf('@')))){
- jsonArray.put(value);
- }else{
- jsonResult.put(oldValue, jsonArray);
- jsonArray = new JSONArray();
- }
- oldValue = key.substring(0,key.indexOf('@'));
- }else{
- jsonResult.put(key, value);
- }
- }
- }
- if(node.size()>0){
- if(nodeKey.contains("@")){
- if(jsonArray==null){
- jsonArray = new JSONArray();
- }
- if(arryKey==null){
- arryKey = nodeKey.substring(0,nodeKey.indexOf('@'));
- }
- jsonArray.put(decodeContent(node));
- jsonResult.put(arryKey, jsonArray);
- isArray = false;
- }else{
- jsonResult.put(nodeKey, decodeContent(node));
- }
- }
- if(isArray && jsonArray.length() > 0){
- jsonResult.put(oldValue, jsonArray);
- }
- return jsonResult;
- }
-
- @RequestMapping(value={"/policyController/getDCAEMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
- public ModelAndView getDCAEMSTemplateData(HttpServletRequest request, HttpServletResponse response) throws IOException{
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
-
- String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
- String servicename = value.split("-v")[0];
- String version = null;
- if (value.contains("-v")){
- version = value.split("-v")[1];
- }
- MicroServiceModels returnModel = getAttributeObject(servicename, version);
-
- MicroserviceHeaderdeFaults returnHeaderDefauls = getHeaderDefaultsObject(value);
- JSONObject jsonHdDefaultObj = null;
- if(returnHeaderDefauls != null){
- jsonHdDefaultObj = new JSONObject();
- jsonHdDefaultObj.put("onapName", returnHeaderDefauls.getOnapName());
- jsonHdDefaultObj.put("guard", returnHeaderDefauls.getGuard());
- jsonHdDefaultObj.put("riskLevel", returnHeaderDefauls.getRiskLevel());
- jsonHdDefaultObj.put("riskType", returnHeaderDefauls.getRiskType());
- jsonHdDefaultObj.put("priority", returnHeaderDefauls.getPriority());
- }
- String headDefautlsData = "";
- if(jsonHdDefaultObj != null){
- headDefautlsData = jsonHdDefaultObj.toString();
- }else{
- headDefautlsData = "null";
- }
-
- //Get all keys with "MANY-true" defined in their value from subAttribute
- Set<String> allkeys = null;
- if(returnModel.getSub_attributes() != null && !returnModel.getSub_attributes().isEmpty()){
- JSONObject json = new JSONObject(returnModel.getSub_attributes());
- getAllKeys(json);
- allkeys = allManyTrueKeys;
- allManyTrueKeys = new HashSet <>();
- LOGGER.info("allkeys : " + allkeys);
- }
-
- //Get element order info
- String dataOrderInfo = returnModel.getDataOrderInfo();
- if(dataOrderInfo != null && !dataOrderInfo.startsWith("\"")){
+ if (value == null || value.isNull()) {
+ ((ObjectNode) returnNode).remove(key);
+ remove = true;
+ }
+ }
+ if (remove) {
+ cleanJson = returnNode.toString();
+ }
+ if (value == null || value.isNull()) {
+ ((ObjectNode) returnNode).remove(key);
+ remove = true;
+ }
+ }
+ if (remove) {
+ cleanJson = returnNode.toString();
+ }
+
+ if (contentChanged) {
+ // set modified content to cleanJson
+ JSONObject jObject = new JSONObject(cleanJson);
+ jObject.put("content", removed.toString());
+ cleanJson = cleanUPJson(jObject.toString());
+ }
+
+ } catch (IOException e) {
+ LOGGER.error("Error writing out the JsonNode", e);
+ }
+ return cleanJson;
+ }
+
+ /**
+ * To verify if it is a JSON string. If it is, then return its original value.
+ *
+ * @param key holds the values
+ * @return
+ */
+ private String getOriginalValue(String key) {
+ for (String k : jsonStringValues.keySet()) {
+ if (k.contains("@")) {
+ String[] arrOfKeys = k.split("@");
+ for (int i = 0; i < arrOfKeys.length; i++) {
+ if (arrOfKeys[i].contains(".")) {
+ arrOfKeys[i] = arrOfKeys[i].substring(arrOfKeys[i].indexOf(".") + 1);
+ if (arrOfKeys[i].equals(key)) {
+ return StringUtils.replaceEach(jsonStringValues.get(k), new String[] {"\""},
+ new String[] {"\\\""});
+ }
+ }
+ }
+ }
+ if (k.endsWith(key)) {
+ return StringUtils.replaceEach(jsonStringValues.get(k), new String[] {"\""}, new String[] {"\\\""});
+ }
+ }
+
+ return null;
+ }
+
+ public JsonArray removeNull(JsonArray array) {
+ JsonArrayBuilder builder = Json.createArrayBuilder();
+ int i = 0;
+ for (Iterator<JsonValue> it = array.iterator(); it.hasNext(); ++i) {
+ JsonValue value = it.next();
+ switch (value.getValueType()) {
+ case ARRAY:
+ JsonArray a = removeNull(array.getJsonArray(i));
+ if (!a.isEmpty())
+ builder.add(a);
+ break;
+ case OBJECT:
+ JsonObject object = removeNull(array.getJsonObject(i));
+ if (!object.isEmpty())
+ builder.add(object);
+ break;
+ case STRING:
+ String s = array.getString(i);
+ if (s != null && !s.isEmpty())
+ builder.add(s);
+ break;
+ case NUMBER:
+ builder.add(array.getJsonNumber(i));
+ break;
+ case TRUE:
+ case FALSE:
+ builder.add(array.getBoolean(i));
+ break;
+ case NULL:
+ break;
+ }
+ }
+ return builder.build();
+ }
+
+ public JsonObject removeNull(JsonObject obj) {
+ JsonObjectBuilder builder = Json.createObjectBuilder();
+ for (Iterator<Entry<String, JsonValue>> it = obj.entrySet().iterator(); it.hasNext();) {
+ Entry<String, JsonValue> e = it.next();
+ String key = e.getKey();
+ JsonValue value = e.getValue();
+ switch (value.getValueType()) {
+ case ARRAY:
+ JsonArray array = removeNull(obj.getJsonArray(key));
+ if (!array.isEmpty())
+ builder.add(key, array);
+ break;
+ case OBJECT:
+ JsonObject object = removeNull(obj.getJsonObject(key));
+ if (!object.isEmpty()) {
+ if (!jsonStringValues.isEmpty()) {
+ String originalValue = getOriginalValue(key);
+ if (originalValue != null) {
+ builder.add(key, object.toString());
+ break;
+ }
+ }
+ builder.add(key, object);
+ }
+ break;
+ case STRING:
+ String s = obj.getString(key);
+ if (s != null && !s.isEmpty()) {
+ if (!jsonStringValues.isEmpty()) {
+ String originalValue = getOriginalValue(key);
+ if (originalValue != null) {
+ s = getOriginalValue(key);
+ }
+ }
+ builder.add(key, s);
+ }
+ break;
+ case NUMBER:
+ builder.add(key, obj.getJsonNumber(key));
+ break;
+ case TRUE:
+ case FALSE:
+ builder.add(key, obj.getBoolean(key));
+ break;
+ case NULL:
+ break;
+ }
+ }
+ return builder.build();
+ }
+
+ public String cleanUPJson(String json) {
+ String cleanJson = StringUtils.replaceEach(json, new String[] {"\\\\", "\\\\\\", "\\\\\\\\"},
+ new String[] {"\\", "\\", "\\"});
+ cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\\\\"}, new String[] {"\\"});
+ cleanJson =
+ StringUtils.replaceEach(cleanJson, new String[] {"\\\\", "[[", "]]"}, new String[] {"\\", "[", "]"});
+
+ cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\\\"", "\\\"", "\"[{", "}]\""},
+ new String[] {"\"", "\"", "[{", "}]"});
+ cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"[{", "}]\""}, new String[] {"[{", "}]"});
+ cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"[", "]\""}, new String[] {"[", "]"});
+ cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"{", "}\""}, new String[] {"{", "}"});
+ cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"\"\"", "\"\""}, new String[] {"\"", "\""});
+ cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\""}, new String[] {""});
+ cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"\""}, new String[] {"\""});
+ cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"\\\\\\"}, new String[] {"\""});
+ cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\\\\\""}, new String[] {"\""});
+ cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\"[", "]\""}, new String[] {"[", "]"});
+ return cleanJson;
+ }
+
+ public JSONObject decodeContent(JsonNode jsonNode) {
+ Iterator<JsonNode> jsonElements = jsonNode.elements();
+ Iterator<String> jsonKeys = jsonNode.fieldNames();
+ Map<String, String> element = new TreeMap<>();
+ while (jsonElements.hasNext() && jsonKeys.hasNext()) {
+ element.put(jsonKeys.next(), jsonElements.next().toString());
+ }
+ JSONObject jsonResult = new JSONObject();
+ JSONArray jsonArray = null;
+ String oldValue = null;
+ String nodeKey = null;
+ String arryKey = null;
+ Boolean isArray = false;
+ JsonNodeFactory nodeFactory = JsonNodeFactory.instance;
+ ObjectNode node = nodeFactory.objectNode();
+ String prevKey = null;
+ String presKey;
+ for (Entry<String, String> entry : element.entrySet()) {
+ String key = entry.getKey();
+ String value = entry.getValue();
+ if (key.contains(".")) {
+ presKey = key.substring(0, key.indexOf('.'));
+ } else if (key.contains("@")) {
+ presKey = key.substring(0, key.indexOf('@'));
+ } else {
+ presKey = key;
+ }
+ // first check if we are different from old.
+ LOGGER.info(key + "\n");
+ if (jsonArray != null && jsonArray.length() > 0 && key.contains("@") && !key.contains(".")
+ && oldValue != null) {
+ if (!oldValue.equals(key.substring(0, key.indexOf('@')))) {
+ jsonResult.put(oldValue, jsonArray);
+ jsonArray = new JSONArray();
+ }
+ } else if (jsonArray != null && jsonArray.length() > 0 && !presKey.equals(prevKey) && oldValue != null) {
+ jsonResult.put(oldValue, jsonArray);
+ isArray = false;
+ jsonArray = new JSONArray();
+ }
+
+ prevKey = presKey;
+ //
+ if (key.contains(".")) {
+ if (nodeKey == null) {
+ nodeKey = key.substring(0, key.indexOf('.'));
+ }
+ if (nodeKey.equals(key.substring(0, key.indexOf('.')))) {
+ node.put(key.substring(key.indexOf('.') + 1), value);
+ } else {
+ if (node.size() != 0) {
+ if (nodeKey.contains("@")) {
+ if (arryKey == null) {
+ arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
+ }
+ if (nodeKey.endsWith("@0")) {
+ isArray = true;
+ jsonArray = new JSONArray();
+ }
+ if (jsonArray != null && arryKey.equals(nodeKey.substring(0, nodeKey.indexOf('@')))) {
+ jsonArray.put(decodeContent(node));
+ }
+ if ((key.contains("@") && !arryKey.equals(key.substring(0, nodeKey.indexOf('@'))))
+ || !key.contains("@")) {
+ jsonResult.put(arryKey, jsonArray);
+ jsonArray = new JSONArray();
+ }
+ arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
+ } else {
+ isArray = false;
+ jsonResult.put(nodeKey, decodeContent(node));
+ }
+ node = nodeFactory.objectNode();
+ }
+ nodeKey = key.substring(0, key.indexOf('.'));
+ if (nodeKey.contains("@")) {
+ arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
+ }
+ node.put(key.substring(key.indexOf('.') + 1), value);
+ }
+ } else {
+ if (node.size() != 0) {
+ if (nodeKey.contains("@")) {
+ if (arryKey == null) {
+ arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
+ }
+ if (nodeKey.endsWith("@0")) {
+ isArray = true;
+ jsonArray = new JSONArray();
+ }
+ if (jsonArray != null && arryKey.equals(nodeKey.substring(0, nodeKey.indexOf('@')))) {
+ jsonArray.put(decodeContent(node));
+ }
+ jsonResult.put(arryKey, jsonArray);
+ jsonArray = new JSONArray();
+ arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
+ } else {
+ isArray = false;
+ jsonResult.put(nodeKey, decodeContent(node));
+ }
+ node = nodeFactory.objectNode();
+ }
+ if (key.contains("@")) {
+ isArray = true;
+ if (key.endsWith("@0") || jsonArray == null) {
+ jsonArray = new JSONArray();
+ }
+ } else if (!key.contains("@")) {
+ isArray = false;
+ }
+ if (isArray) {
+ if (oldValue == null) {
+ oldValue = key.substring(0, key.indexOf('@'));
+ }
+ if (oldValue != prevKey) {
+ oldValue = key.substring(0, key.indexOf('@'));
+ }
+ if (oldValue.equals(key.substring(0, key.indexOf('@')))) {
+ jsonArray.put(value);
+ } else {
+ jsonResult.put(oldValue, jsonArray);
+ jsonArray = new JSONArray();
+ }
+ oldValue = key.substring(0, key.indexOf('@'));
+ } else {
+ jsonResult.put(key, value);
+ }
+ }
+ }
+ if (node.size() > 0) {
+ if (nodeKey.contains("@")) {
+ if (jsonArray == null) {
+ jsonArray = new JSONArray();
+ }
+ if (arryKey == null) {
+ arryKey = nodeKey.substring(0, nodeKey.indexOf('@'));
+ }
+ jsonArray.put(decodeContent(node));
+ jsonResult.put(arryKey, jsonArray);
+ isArray = false;
+ } else {
+ jsonResult.put(nodeKey, decodeContent(node));
+ }
+ }
+ if (isArray && jsonArray.length() > 0) {
+ jsonResult.put(oldValue, jsonArray);
+ }
+ return jsonResult;
+ }
+
+ @RequestMapping(value = {"/policyController/getDCAEMSTemplateData.htm"},
+ method = {org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView getDCAEMSTemplateData(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+
+ String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
+ String servicename = value.split("-v")[0];
+ String version = null;
+ if (value.contains("-v")) {
+ version = value.split("-v")[1];
+ }
+ MicroServiceModels returnModel = getAttributeObject(servicename, version);
+
+ MicroserviceHeaderdeFaults returnHeaderDefauls = getHeaderDefaultsObject(value);
+ JSONObject jsonHdDefaultObj = null;
+ if (returnHeaderDefauls != null) {
+ jsonHdDefaultObj = new JSONObject();
+ jsonHdDefaultObj.put("onapName", returnHeaderDefauls.getOnapName());
+ jsonHdDefaultObj.put("guard", returnHeaderDefauls.getGuard());
+ jsonHdDefaultObj.put("riskLevel", returnHeaderDefauls.getRiskLevel());
+ jsonHdDefaultObj.put("riskType", returnHeaderDefauls.getRiskType());
+ jsonHdDefaultObj.put("priority", returnHeaderDefauls.getPriority());
+ }
+ String headDefautlsData = "";
+ if (jsonHdDefaultObj != null) {
+ headDefautlsData = jsonHdDefaultObj.toString();
+ } else {
+ headDefautlsData = "null";
+ }
+
+ // Get all keys with "MANY-true" defined in their value from subAttribute
+ Set<String> allkeys = null;
+ if (returnModel.getSub_attributes() != null && !returnModel.getSub_attributes().isEmpty()) {
+ JSONObject json = new JSONObject(returnModel.getSub_attributes());
+ getAllKeys(json);
+ allkeys = allManyTrueKeys;
+ allManyTrueKeys = new HashSet<>();
+ LOGGER.info("allkeys : " + allkeys);
+ }
+
+ // Get element order info
+ String dataOrderInfo = returnModel.getDataOrderInfo();
+ if (dataOrderInfo != null && !dataOrderInfo.startsWith("\"")) {
dataOrderInfo = "\"" + dataOrderInfo + "\"";
}
LOGGER.info("dataOrderInfo : " + dataOrderInfo);
-
- String allManyTrueKeys = "";
- if(allkeys != null){
- allManyTrueKeys = allkeys.toString();
- }
-
- String jsonModel = createMicroSeriveJson(returnModel, allkeys);
-
- JSONObject jsonObject = new JSONObject(jsonModel);
-
- JSONObject finalJsonObject = null;
- if(allkeys != null){
- Iterator<String> iter = allkeys.iterator();
- while(iter.hasNext()){
- //Convert to array values for MANY-true keys
- finalJsonObject = convertToArrayElement(jsonObject, iter.next());
- }
- }
-
- if(finalJsonObject != null){
- LOGGER.info(finalJsonObject.toString());
- jsonModel = finalJsonObject.toString();
- }
-
- //get all properties with "MANY-true" defined in Ref_attributes
- Set<String> manyTrueProperties = getManyTrueProperties(returnModel.getRef_attributes());
- if(manyTrueProperties != null){
- JSONObject jsonObj = new JSONObject(jsonModel);
- for (String s : manyTrueProperties) {
- LOGGER.info(s);
- //convert to array element for MANY-true properties
- finalJsonObject = convertToArrayElement(jsonObj, s.trim());
- }
-
- if(finalJsonObject != null){
- LOGGER.info(finalJsonObject.toString());
- jsonModel = finalJsonObject.toString();
- }
- }
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
- List<Object> list = new ArrayList<>();
- PrintWriter out = response.getWriter();
- String responseString = mapper.writeValueAsString(returnModel);
-
- JSONObject j = null;
-
- if("".equals(allManyTrueKeys)){
- j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData +"}");
- }else{
- j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",allManyTrueKeys: " + allManyTrueKeys+",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData+ "}");
- }
- list.add(j);
- out.write(list.toString());
- return null;
- }
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- private String createMicroSeriveJson(MicroServiceModels returnModel, Set<String> allkeys) {
- Map<String, String> attributeMap = new HashMap<>();
- Map<String, String> refAttributeMap = new HashMap<>();
- String attribute = returnModel.getAttributes();
- if(attribute != null){
- attribute = attribute.trim();
- }
- String refAttribute = returnModel.getRef_attributes();
- if(refAttribute != null){
- refAttribute = refAttribute.trim();
- }
- String enumAttribute = returnModel.getEnumValues();
- if(enumAttribute != null){
- enumAttribute = enumAttribute.trim();
- }
- if (!StringUtils.isEmpty(attribute)){
- attributeMap = convert(attribute, ",");
- }
- if (!StringUtils.isEmpty(refAttribute)){
- refAttributeMap = convert(refAttribute, ",");
- }
-
- Gson gson = new Gson();
-
- String subAttributes = returnModel.getSub_attributes();
- if(subAttributes != null){
- subAttributes = subAttributes.trim();
- }else{
- subAttributes = "";
- }
-
- Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class);
-
- JSONObject object = new JSONObject();
- JSONArray array = new JSONArray();
-
- for (Entry<String, String> keySet : attributeMap.entrySet()){
- array = new JSONArray();
- String value = keySet.getValue();
- if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])){
- array.put(value);
- object.put(keySet.getKey().trim(), array);
- }else {
- object.put(keySet.getKey().trim(), value.trim());
- }
- }
-
- for (Entry<String, String> keySet : refAttributeMap.entrySet()){
- array = new JSONArray();
- String value = keySet.getValue().split(":")[0];
- if (gsonObject.containsKey(value)){
- if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])){
- array.put(recursiveReference(value, gsonObject, enumAttribute));
- object.put(keySet.getKey().trim(), array);
- }else {
- object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute));
- }
- }else {
- if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])){
- array.put(value.trim());
- object.put(keySet.getKey().trim(), array);
- }else {
- object.put(keySet.getKey().trim(), value.trim());
- }
- }
- }
-
- return object.toString();
- }
-
- @SuppressWarnings("unchecked")
- private JSONObject recursiveReference(String name, Map<String,String> subAttributeMap, String enumAttribute) {
- JSONObject object = new JSONObject();
- Map<String, String> map;
- Object returnClass = subAttributeMap.get(name);
- map = (Map<String, String>) returnClass;
- JSONArray array;
-
- for( Entry<String, String> m:map.entrySet()){
- String[] splitValue = m.getValue().split(":");
- array = new JSONArray();
- if (subAttributeMap.containsKey(splitValue[0])){
- if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])){
- array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
- object.put(m.getKey().trim(), array);
- }else {
- object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
- }
- } else{
- if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])){
- array.put(splitValue[0].trim());
- object.put(m.getKey().trim(), array);
- }else {
- object.put(m.getKey().trim(), splitValue[0].trim());
- }
- }
- }
-
- return object;
- }
-
-
- public static JSONObject convertToArrayElement(JSONObject json, String keyValue) {
- return convertToArrayElement(json, new HashSet<>(), keyValue);
- }
-
- private static JSONObject convertToArrayElement(JSONObject json, Set<String> keys, String keyValue) {
- for (String key : json.keySet()) {
- Object obj = json.get(key);
- if(key.equals(keyValue.trim())){
- if(!(obj instanceof JSONArray)){
- JSONArray newJsonArray = new JSONArray();
- newJsonArray.put(obj);
- json.put(key, newJsonArray);
- }
- LOGGER.info("key : " + key);
- LOGGER.info("obj : " + obj);
- LOGGER.info("json.get(key) : " + json.get(key));
- LOGGER.info("keyValue : " + keyValue);
- keys.addAll(json.keySet());
-
- return json;
- }
-
- if (obj instanceof JSONObject) convertToArrayElement(json.getJSONObject(key), keyValue);
- }
-
- return json;
- }
-
- // call this method to get all MANY-true properties
- public static Set<String> getManyTrueProperties(String referAttributes){
- LOGGER.info("referAttributes : " + referAttributes);
- Set<String> manyTrueProperties = new HashSet<>();
-
- if(referAttributes != null){
- String[] referAarray = referAttributes.split(",");
- String []element= null;
- for(int i=0; i<referAarray.length; i++){
- element = referAarray[i].split("=");
- if(element.length > 1 && element[1].contains("MANY-true")){
- manyTrueProperties.add(element[0]);
- }
- }
- }
-
- return manyTrueProperties;
- }
-
- //call this method to start the recursive
- private Set<String> getAllKeys(JSONObject json) {
- return getAllKeys(json, new HashSet<>());
- }
-
- private Set<String> getAllKeys(JSONArray arr) {
- return getAllKeys(arr, new HashSet<>());
- }
-
- private Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
- for (int i = 0; i < arr.length(); i++) {
- Object obj = arr.get(i);
- if (obj instanceof JSONObject) keys.addAll(getAllKeys(arr.getJSONObject(i)));
- if (obj instanceof JSONArray) keys.addAll(getAllKeys(arr.getJSONArray(i)));
- }
-
- return keys;
- }
-
+
+ String allManyTrueKeys = "";
+ if (allkeys != null) {
+ allManyTrueKeys = allkeys.toString();
+ }
+
+ String jsonModel = createMicroSeriveJson(returnModel, allkeys);
+
+ JSONObject jsonObject = new JSONObject(jsonModel);
+
+ JSONObject finalJsonObject = null;
+ if (allkeys != null) {
+ Iterator<String> iter = allkeys.iterator();
+ while (iter.hasNext()) {
+ // Convert to array values for MANY-true keys
+ finalJsonObject = convertToArrayElement(jsonObject, iter.next());
+ }
+ }
+
+ if (finalJsonObject != null) {
+ LOGGER.info(finalJsonObject.toString());
+ jsonModel = finalJsonObject.toString();
+ }
+
+ // get all properties with "MANY-true" defined in Ref_attributes
+ Set<String> manyTrueProperties = getManyTrueProperties(returnModel.getRef_attributes());
+ if (manyTrueProperties != null) {
+ JSONObject jsonObj = new JSONObject(jsonModel);
+ for (String s : manyTrueProperties) {
+ LOGGER.info(s);
+ // convert to array element for MANY-true properties
+ finalJsonObject = convertToArrayElement(jsonObj, s.trim());
+ }
+
+ if (finalJsonObject != null) {
+ LOGGER.info(finalJsonObject.toString());
+ jsonModel = finalJsonObject.toString();
+ }
+ }
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+ List<Object> list = new ArrayList<>();
+ PrintWriter out = response.getWriter();
+ String responseString = mapper.writeValueAsString(returnModel);
+
+ JSONObject j = null;
+
+ if ("".equals(allManyTrueKeys)) {
+ j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",dataOrderInfo:"
+ + dataOrderInfo + ",headDefautlsData:" + headDefautlsData + "}");
+ } else {
+ j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",allManyTrueKeys: "
+ + allManyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData
+ + "}");
+ }
+ list.add(j);
+ out.write(list.toString());
+ return null;
+ }
+
+ @SuppressWarnings({"unchecked", "rawtypes"})
+ private String createMicroSeriveJson(MicroServiceModels returnModel, Set<String> allkeys) {
+ Map<String, String> attributeMap = new HashMap<>();
+ Map<String, String> refAttributeMap = new HashMap<>();
+ String attribute = returnModel.getAttributes();
+ if (attribute != null) {
+ attribute = attribute.trim();
+ }
+ String refAttribute = returnModel.getRef_attributes();
+ if (refAttribute != null) {
+ refAttribute = refAttribute.trim();
+ }
+ String enumAttribute = returnModel.getEnumValues();
+ if (enumAttribute != null) {
+ enumAttribute = enumAttribute.trim();
+ }
+ if (!StringUtils.isEmpty(attribute)) {
+ attributeMap = convert(attribute, ",");
+ }
+ if (!StringUtils.isEmpty(refAttribute)) {
+ refAttributeMap = convert(refAttribute, ",");
+ }
+
+ Gson gson = new Gson();
+
+ String subAttributes = returnModel.getSub_attributes();
+ if (subAttributes != null) {
+ subAttributes = subAttributes.trim();
+ } else {
+ subAttributes = "";
+ }
+
+ Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class);
+
+ JSONObject object = new JSONObject();
+ JSONArray array = new JSONArray();
+
+ for (Entry<String, String> keySet : attributeMap.entrySet()) {
+ array = new JSONArray();
+ String value = keySet.getValue();
+ if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
+ array.put(value);
+ object.put(keySet.getKey().trim(), array);
+ } else {
+ object.put(keySet.getKey().trim(), value.trim());
+ }
+ }
+
+ for (Entry<String, String> keySet : refAttributeMap.entrySet()) {
+ array = new JSONArray();
+ String value = keySet.getValue().split(":")[0];
+ if (gsonObject.containsKey(value)) {
+ if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
+ array.put(recursiveReference(value, gsonObject, enumAttribute));
+ object.put(keySet.getKey().trim(), array);
+ } else {
+ object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute));
+ }
+ } else {
+ if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
+ array.put(value.trim());
+ object.put(keySet.getKey().trim(), array);
+ } else {
+ object.put(keySet.getKey().trim(), value.trim());
+ }
+ }
+ }
+
+ return object.toString();
+ }
+
+ @SuppressWarnings("unchecked")
+ private JSONObject recursiveReference(String name, Map<String, String> subAttributeMap, String enumAttribute) {
+ JSONObject object = new JSONObject();
+ Map<String, String> map;
+ Object returnClass = subAttributeMap.get(name);
+ map = (Map<String, String>) returnClass;
+ JSONArray array;
+
+ for (Entry<String, String> m : map.entrySet()) {
+ String[] splitValue = m.getValue().split(":");
+ array = new JSONArray();
+ if (subAttributeMap.containsKey(splitValue[0])) {
+ if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])) {
+ array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
+ object.put(m.getKey().trim(), array);
+ } else {
+ object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute));
+ }
+ } else {
+ if ("true".equalsIgnoreCase(m.getValue().split("MANY-")[1])) {
+ array.put(splitValue[0].trim());
+ object.put(m.getKey().trim(), array);
+ } else {
+ object.put(m.getKey().trim(), splitValue[0].trim());
+ }
+ }
+ }
+
+ return object;
+ }
+
+
+ public static JSONObject convertToArrayElement(JSONObject json, String keyValue) {
+ return convertToArrayElement(json, new HashSet<>(), keyValue);
+ }
+
+ private static JSONObject convertToArrayElement(JSONObject json, Set<String> keys, String keyValue) {
+ for (String key : json.keySet()) {
+ Object obj = json.get(key);
+ if (key.equals(keyValue.trim())) {
+ if (!(obj instanceof JSONArray)) {
+ JSONArray newJsonArray = new JSONArray();
+ newJsonArray.put(obj);
+ json.put(key, newJsonArray);
+ }
+ LOGGER.info("key : " + key);
+ LOGGER.info("obj : " + obj);
+ LOGGER.info("json.get(key) : " + json.get(key));
+ LOGGER.info("keyValue : " + keyValue);
+ keys.addAll(json.keySet());
+
+ return json;
+ }
+
+ if (obj instanceof JSONObject)
+ convertToArrayElement(json.getJSONObject(key), keyValue);
+ }
+
+ return json;
+ }
+
+ // call this method to get all MANY-true properties
+ public static Set<String> getManyTrueProperties(String referAttributes) {
+ LOGGER.info("referAttributes : " + referAttributes);
+ Set<String> manyTrueProperties = new HashSet<>();
+
+ if (referAttributes != null) {
+ String[] referAarray = referAttributes.split(",");
+ String[] element = null;
+ for (int i = 0; i < referAarray.length; i++) {
+ element = referAarray[i].split("=");
+ if (element.length > 1 && element[1].contains("MANY-true")) {
+ manyTrueProperties.add(element[0]);
+ }
+ }
+ }
+
+ return manyTrueProperties;
+ }
+
+ // call this method to start the recursive
+ private Set<String> getAllKeys(JSONObject json) {
+ return getAllKeys(json, new HashSet<>());
+ }
+
+ private Set<String> getAllKeys(JSONArray arr) {
+ return getAllKeys(arr, new HashSet<>());
+ }
+
+ private Set<String> getAllKeys(JSONArray arr, Set<String> keys) {
+ for (int i = 0; i < arr.length(); i++) {
+ Object obj = arr.get(i);
+ if (obj instanceof JSONObject)
+ keys.addAll(getAllKeys(arr.getJSONObject(i)));
+ if (obj instanceof JSONArray)
+ keys.addAll(getAllKeys(arr.getJSONArray(i)));
+ }
+
+ return keys;
+ }
+
// this method returns a set of keys with "MANY-true" defined in their value.
- private Set<String> getAllKeys(JSONObject json, Set<String> keys) {
- for (String key : json.keySet()) {
- Object obj = json.get(key);
- if(obj instanceof String && ((String) obj).contains("MANY-true")){
- LOGGER.info("key : " + key);
- LOGGER.info("obj : " + obj);
- allManyTrueKeys.add(key);
- }
- if (obj instanceof JSONObject) keys.addAll(getAllKeys(json.getJSONObject(key)));
- if (obj instanceof JSONArray) keys.addAll(getAllKeys(json.getJSONArray(key)));
- }
-
- return keys;
- }
-
-
- @RequestMapping(value={"/policyController/getModelServiceVersioneData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
- public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response) throws IOException{
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
-
- String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
- String servicename = value.split("-v")[0];
- Set<String> returnList = getVersionList(servicename);
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
- List<Object> list = new ArrayList<>();
- PrintWriter out = response.getWriter();
- String responseString = mapper.writeValueAsString(returnList);
- JSONObject j = new JSONObject("{dcaeModelVersionData: " + responseString +"}");
- list.add(j);
- out.write(list.toString());
- return null;
- }
-
- private Set<String> getVersionList(String name) {
- MicroServiceModels workingModel;
- Set<String> list = new HashSet<>();
- List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
- for (int i = 0; i < microServiceModelsData.size(); i++) {
- workingModel = (MicroServiceModels) microServiceModelsData.get(i);
- if (workingModel.getVersion()!=null){
- list.add(workingModel.getVersion());
- }else{
- list.add("Default");
- }
- }
- return list;
- }
-
- private MicroServiceModels getAttributeObject(String name, String version) {
- MicroServiceModels workingModel = new MicroServiceModels();
- List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
- for (int i = 0; i < microServiceModelsData.size(); i++) {
- workingModel = (MicroServiceModels) microServiceModelsData.get(i);
- if(version != null){
- if (workingModel.getVersion()!=null){
- if (workingModel.getVersion().equals(version)){
- return workingModel;
- }
- }else{
- return workingModel;
- }
- }else{
- return workingModel;
- }
-
- }
- return workingModel;
- }
-
- private MicroserviceHeaderdeFaults getHeaderDefaultsObject(String modelName) {
- return (MicroserviceHeaderdeFaults) commonClassDao.getEntityItem(MicroserviceHeaderdeFaults.class, "modelName", modelName);
- }
-
- @RequestMapping(value={"/get_DCAEPriorityValues"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
- public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response){
- try{
- Map<String, Object> model = new HashMap<>();
- ObjectMapper mapper = new ObjectMapper();
- List<String> priorityList = new ArrayList<>();
- priorityCount = 10;
- for (int i = 1; i < priorityCount; i++) {
- priorityList.add(String.valueOf(i));
- }
- model.put("priorityDatas", mapper.writeValueAsString(priorityList));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
- }
- catch (Exception e){
- LOGGER.error(e);
- }
- }
-
- public void prePopulateDCAEMSPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
- if (policyAdapter.getPolicyData() instanceof PolicyType) {
- Object policyData = policyAdapter.getPolicyData();
- PolicyType policy = (PolicyType) policyData;
- policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
- String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") +3);
- policyAdapter.setPolicyName(policyNameValue);
- String description = "";
- try{
- description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
- }catch(Exception e){
- LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue ,e);
- description = policy.getDescription();
- }
- policyAdapter.setPolicyDescription(description);
- // Get the target data under policy.
- TargetType target = policy.getTarget();
- if (target != null) {
- // Under target we have AnyOFType
- List<AnyOfType> anyOfList = target.getAnyOf();
- if (anyOfList != null) {
- Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
- while (iterAnyOf.hasNext()) {
- AnyOfType anyOf = iterAnyOf.next();
- // Under AnyOFType we have AllOFType
- List<AllOfType> allOfList = anyOf.getAllOf();
- if (allOfList != null) {
- Iterator<AllOfType> iterAllOf = allOfList.iterator();
- while (iterAllOf.hasNext()) {
- AllOfType allOf = iterAllOf.next();
- // Under AllOFType we have Match
- List<MatchType> matchList = allOf.getMatch();
- if (matchList != null) {
- Iterator<MatchType> iterMatch = matchList.iterator();
- while (matchList.size()>1 && iterMatch.hasNext()) {
- MatchType match = iterMatch.next();
- //
- // Under the match we have attribute value and
- // attributeDesignator. So,finally down to the actual attribute.
- //
- AttributeValueType attributeValue = match.getAttributeValue();
- String value = (String) attributeValue.getContent().get(0);
- AttributeDesignatorType designator = match.getAttributeDesignator();
- String attributeId = designator.getAttributeId();
- // First match in the target is OnapName, so set that value.
- if ("ONAPName".equals(attributeId)) {
- policyAdapter.setOnapName(value);
- }
- if ("ConfigName".equals(attributeId)){
- policyAdapter.setConfigName(value);
- }
- if ("uuid".equals(attributeId)){
- policyAdapter.setUuid(value);
- }
- if ("location".equals(attributeId)){
- policyAdapter.setLocation(value);
- }
- if ("RiskType".equals(attributeId)){
- policyAdapter.setRiskType(value);
- }
- if ("RiskLevel".equals(attributeId)){
- policyAdapter.setRiskLevel(value);
- }
- if ("guard".equals(attributeId)){
- policyAdapter.setGuard(value);
- }
- if ("TTLDate".equals(attributeId) && !value.contains("NA")){
- PolicyController controller = new PolicyController();
- String newDate = controller.convertDate(value);
- policyAdapter.setTtlDate(newDate);
- }
- }
- readFile(policyAdapter, entity);
- }
- }
- }
- }
- }
- }
- }
- }
-
- public static Map<String, String> convert(String str, String split) {
- Map<String, String> map = new HashMap<>();
- for(final String entry : str.split(split)) {
- String[] parts = entry.split("=");
- map.put(parts[0], parts[1]);
- }
- return map;
- }
-
-
- @SuppressWarnings("unchecked")
- private void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
- String policyScopeName = null;
- ObjectMapper mapper = new ObjectMapper();
- try {
- DCAEMicroServiceObject msBody = mapper.readValue(entity.getConfigurationData().getConfigBody(), DCAEMicroServiceObject.class);
- policyScopeName = getPolicyScope(msBody.getPolicyScope());
- policyAdapter.setPolicyScope(policyScopeName);
-
- policyAdapter.setPriority(msBody.getPriority());
-
- if (msBody.getVersion()!= null){
- policyAdapter.setServiceType(msBody.getService());
- policyAdapter.setVersion(msBody.getVersion());
- }else{
- policyAdapter.setServiceType(msBody.getService());
- }
- if(msBody.getContent() != null){
- LinkedHashMap<String, Object> data = new LinkedHashMap<>();
- LinkedHashMap<String, ?> map = (LinkedHashMap<String, ?>) msBody.getContent();
- readRecursivlyJSONContent(map, data);
- policyAdapter.setRuleData(data);
- }
-
- } catch (Exception e) {
- LOGGER.error(e);
- }
-
- }
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- public void readRecursivlyJSONContent(LinkedHashMap<String, ?> map, LinkedHashMap<String, Object> data){
- for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
- Object key = iterator.next();
- Object value = map.get(key);
- if(value instanceof LinkedHashMap<?, ?>){
- LinkedHashMap<String, Object> secondObjec = new LinkedHashMap<>();
- readRecursivlyJSONContent((LinkedHashMap<String, ?>) value, secondObjec);
- for( Entry<String, Object> entry : secondObjec.entrySet()){
- data.put(key+"." + entry.getKey(), entry.getValue());
- }
- }else if(value instanceof ArrayList){
- ArrayList<?> jsonArrayVal = (ArrayList<?>)value;
- for(int i = 0; i < jsonArrayVal.size(); i++){
- Object arrayvalue = jsonArrayVal.get(i);
- if(arrayvalue instanceof LinkedHashMap<?, ?>){
- LinkedHashMap<String, Object> newData = new LinkedHashMap<>();
- readRecursivlyJSONContent((LinkedHashMap<String, ?>) arrayvalue, newData);
- for(Entry<String, Object> entry: newData.entrySet()){
- data.put(key+"@"+i+"." +entry.getKey(), entry.getValue());
- }
- }else if(arrayvalue instanceof ArrayList){
- ArrayList<?> jsonArrayVal1 = (ArrayList<?>)value;
- for(int j = 0; j < jsonArrayVal1.size(); j++){
- Object arrayvalue1 = jsonArrayVal1.get(i);
- data.put(key+"@"+j, arrayvalue1.toString());
- }
- }else{
- data.put(key+"@"+i, arrayvalue.toString());
- }
- }
- }else{
- data.put(key.toString(), value.toString());
- }
- }
- }
-
- public String getPolicyScope(String value) {
- List<Object> groupList= commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value);
- if(groupList != null && !groupList.isEmpty()){
- GroupPolicyScopeList pScope = (GroupPolicyScopeList) groupList.get(0);
- return pScope.getGroupName();
- }
- return null;
- }
-
- //Convert the map values and set into JSON body
- public Map<String, String> convertMap(Map<String, String> attributesMap, Map<String, String> attributesRefMap) {
- Map<String, String> attribute = new HashMap<>();
- StringBuilder temp;
- String key;
- String value;
- for (Entry<String, String> entry : attributesMap.entrySet()) {
- key = entry.getKey();
- value = entry.getValue();
- attribute.put(key, value);
- }
- for (Entry<String, String> entryRef : attributesRefMap.entrySet()) {
- key = entryRef.getKey();
- value = entryRef.getValue();
- attribute.put(key, value);
- }
- for (Entry<String, String> entryList : attributesListRefMap.entrySet()) {
- key = entryList.getKey();
- value = entryList.getValue();
- attribute.put(key, value);
- }
- for (Entry<String, LinkedList<String>> arrayList : arrayTextList.entrySet()){
- key = arrayList.getKey();
- temp = null;
- for (Object textList : arrayList.getValue()){
- if (temp == null){
- temp = new StringBuilder();
- temp.append("[" + textList);
- }else{
- temp.append("," + textList);
- }
- }
- attribute.put(key, temp+ "]");
- }
-
- return attribute;
- }
-
- @RequestMapping(value={"/ms_dictionary/set_MSModelData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
- public void SetMSModelData(HttpServletRequest request, HttpServletResponse response) throws IOException, FileUploadException{
- modelList = new ArrayList<>();
- dirDependencyList = new ArrayList<>();
- classMap = new LinkedHashMap<>();
- List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
- boolean zip = false;
- boolean yml= false;
- String errorMsg = "";
- for (FileItem item : items) {
- if(item.getName().endsWith(".zip") || item.getName().endsWith(".xmi")||item.getName().endsWith(".yml")){
- this.newModel = new MicroServiceModels();
- try{
- File file = new File(item.getName());
- OutputStream outputStream = new FileOutputStream(file);
- IOUtils.copy(item.getInputStream(), outputStream);
- outputStream.close();
- this.newFile = file.toString();
- this.newModel.setModelName(this.newFile.split("-v")[0]);
-
- if (this.newFile.contains("-v")){
- if (item.getName().endsWith(".zip")){
- this.newModel.setVersion(this.newFile.split("-v")[1].replace(".zip", ""));
- zip = true;
- }else if(item.getName().endsWith(".yml")){
- this.newModel.setVersion(this.newFile.split("-v")[1].replace(".yml", ""));
- yml = true;
- }
- else {
- this.newModel.setVersion(this.newFile.split("-v")[1].replace(".xmi", ""));
- }
- }
- }catch(Exception e){
- LOGGER.error("Upload error : ", e);
- errorMsg = "Upload error:" + e.getMessage();
- }
- }
-
- }
-
- if(!errorMsg.isEmpty()){
-
- PrintWriter out = response.getWriter();
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
-
- JSONObject j = new JSONObject();
- j.put("errorMsg", errorMsg);
- out.write(j.toString());
- return;
- }
-
- List<File> fileList = new ArrayList<>();
- MSModelUtils msMLUtils = new MSModelUtils();
- this.directory = "model";
- if (zip){
- extractFolder(this.newFile);
- fileList = listModelFiles(this.directory);
- }else if (yml==true){
-
- errorMsg = msMLUtils.parseTosca(this.newFile);
- if(errorMsg != null){
- PrintWriter out = response.getWriter();
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
- JSONObject j = new JSONObject();
- j.put("errorMsg", errorMsg);
- out.write(j.toString());
- return;
- }
-
- }else {
- File file = new File(this.newFile);
- fileList.add(file);
- }
- String modelType= "";
- if(!yml){
- modelType="xmi";
- //Process Main Model file first
- classMap = new LinkedHashMap<>();
- for (File file : fileList) {
- if(!file.isDirectory() && file.getName().endsWith(".xmi")){
- retreiveDependency(file.toString(), true);
- }
- }
-
- modelList = createList();
-
- cleanUp(this.newFile);
- cleanUp(directory);
- }else{
- modelType="yml";
- modelList.add(this.newModel.getModelName());
- String className=this.newModel.getModelName();
- MSAttributeObject msAttributes= new MSAttributeObject();
- msAttributes.setClassName(className);
-
- LinkedHashMap<String, String> returnAttributeList =new LinkedHashMap<>();
- returnAttributeList.put(className, msMLUtils.getAttributeString());
- msAttributes.setAttribute(returnAttributeList);
-
- msAttributes.setSubClass(msMLUtils.getRetmap());
-
- msAttributes.setMatchingSet(msMLUtils.getMatchableValues());
-
- LinkedHashMap<String, String> returnReferenceList =new LinkedHashMap<>();
-
- returnReferenceList.put(className, msMLUtils.getReferenceAttributes());
- msAttributes.setRefAttribute(returnReferenceList);
-
- if(msMLUtils.getListConstraints()!=""){
- LinkedHashMap<String, String> enumList =new LinkedHashMap<>();
- String[] listArray=msMLUtils.getListConstraints().split("#");
- for(String str:listArray){
- String[] strArr= str.split("=");
- if(strArr.length>1){
+ private Set<String> getAllKeys(JSONObject json, Set<String> keys) {
+ for (String key : json.keySet()) {
+ Object obj = json.get(key);
+ if (obj instanceof String && ((String) obj).contains("MANY-true")) {
+ LOGGER.info("key : " + key);
+ LOGGER.info("obj : " + obj);
+ allManyTrueKeys.add(key);
+ }
+ if (obj instanceof JSONObject)
+ keys.addAll(getAllKeys(json.getJSONObject(key)));
+ if (obj instanceof JSONArray)
+ keys.addAll(getAllKeys(json.getJSONArray(key)));
+ }
+
+ return keys;
+ }
+
+
+ @RequestMapping(value = {"/policyController/getModelServiceVersioneData.htm"},
+ method = {org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+
+ String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
+ String servicename = value.split("-v")[0];
+ Set<String> returnList = getVersionList(servicename);
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+ List<Object> list = new ArrayList<>();
+ PrintWriter out = response.getWriter();
+ String responseString = mapper.writeValueAsString(returnList);
+ JSONObject j = new JSONObject("{dcaeModelVersionData: " + responseString + "}");
+ list.add(j);
+ out.write(list.toString());
+ return null;
+ }
+
+ private Set<String> getVersionList(String name) {
+ MicroServiceModels workingModel;
+ Set<String> list = new HashSet<>();
+ List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
+ for (int i = 0; i < microServiceModelsData.size(); i++) {
+ workingModel = (MicroServiceModels) microServiceModelsData.get(i);
+ if (workingModel.getVersion() != null) {
+ list.add(workingModel.getVersion());
+ } else {
+ list.add("Default");
+ }
+ }
+ return list;
+ }
+
+ private MicroServiceModels getAttributeObject(String name, String version) {
+ MicroServiceModels workingModel = new MicroServiceModels();
+ List<Object> microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name);
+ for (int i = 0; i < microServiceModelsData.size(); i++) {
+ workingModel = (MicroServiceModels) microServiceModelsData.get(i);
+ if (version != null) {
+ if (workingModel.getVersion() != null) {
+ if (workingModel.getVersion().equals(version)) {
+ return workingModel;
+ }
+ } else {
+ return workingModel;
+ }
+ } else {
+ return workingModel;
+ }
+
+ }
+ return workingModel;
+ }
+
+ private MicroserviceHeaderdeFaults getHeaderDefaultsObject(String modelName) {
+ return (MicroserviceHeaderdeFaults) commonClassDao.getEntityItem(MicroserviceHeaderdeFaults.class, "modelName",
+ modelName);
+ }
+
+ @RequestMapping(value = {"/get_DCAEPriorityValues"},
+ method = {org.springframework.web.bind.annotation.RequestMethod.GET},
+ produces = MediaType.APPLICATION_JSON_VALUE)
+ public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response) {
+ try {
+ Map<String, Object> model = new HashMap<>();
+ ObjectMapper mapper = new ObjectMapper();
+ List<String> priorityList = new ArrayList<>();
+ priorityCount = 10;
+ for (int i = 1; i < priorityCount; i++) {
+ priorityList.add(String.valueOf(i));
+ }
+ model.put("priorityDatas", mapper.writeValueAsString(priorityList));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ } catch (Exception e) {
+ LOGGER.error(e);
+ }
+ }
+
+ public void prePopulateDCAEMSPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+ if (policyAdapter.getPolicyData() instanceof PolicyType) {
+ Object policyData = policyAdapter.getPolicyData();
+ PolicyType policy = (PolicyType) policyData;
+ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+ String policyNameValue =
+ policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") + 3);
+ policyAdapter.setPolicyName(policyNameValue);
+ String description = "";
+ try {
+ description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+ } catch (Exception e) {
+ LOGGER.error("Error while collecting the desciption tag in ActionPolicy " + policyNameValue, e);
+ description = policy.getDescription();
+ }
+ policyAdapter.setPolicyDescription(description);
+ // Get the target data under policy.
+ TargetType target = policy.getTarget();
+ if (target != null) {
+ // Under target we have AnyOFType
+ List<AnyOfType> anyOfList = target.getAnyOf();
+ if (anyOfList != null) {
+ Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
+ while (iterAnyOf.hasNext()) {
+ AnyOfType anyOf = iterAnyOf.next();
+ // Under AnyOFType we have AllOFType
+ List<AllOfType> allOfList = anyOf.getAllOf();
+ if (allOfList != null) {
+ Iterator<AllOfType> iterAllOf = allOfList.iterator();
+ while (iterAllOf.hasNext()) {
+ AllOfType allOf = iterAllOf.next();
+ // Under AllOFType we have Match
+ List<MatchType> matchList = allOf.getMatch();
+ if (matchList != null) {
+ Iterator<MatchType> iterMatch = matchList.iterator();
+ while (matchList.size() > 1 && iterMatch.hasNext()) {
+ MatchType match = iterMatch.next();
+ //
+ // Under the match we have attribute value and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ AttributeValueType attributeValue = match.getAttributeValue();
+ String value = (String) attributeValue.getContent().get(0);
+ AttributeDesignatorType designator = match.getAttributeDesignator();
+ String attributeId = designator.getAttributeId();
+ // First match in the target is OnapName, so set that value.
+ if ("ONAPName".equals(attributeId)) {
+ policyAdapter.setOnapName(value);
+ }
+ if ("ConfigName".equals(attributeId)) {
+ policyAdapter.setConfigName(value);
+ }
+ if ("uuid".equals(attributeId)) {
+ policyAdapter.setUuid(value);
+ }
+ if ("location".equals(attributeId)) {
+ policyAdapter.setLocation(value);
+ }
+ if ("RiskType".equals(attributeId)) {
+ policyAdapter.setRiskType(value);
+ }
+ if ("RiskLevel".equals(attributeId)) {
+ policyAdapter.setRiskLevel(value);
+ }
+ if ("guard".equals(attributeId)) {
+ policyAdapter.setGuard(value);
+ }
+ if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
+ PolicyController controller = new PolicyController();
+ String newDate = controller.convertDate(value);
+ policyAdapter.setTtlDate(newDate);
+ }
+ }
+ readFile(policyAdapter, entity);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ public static Map<String, String> convert(String str, String split) {
+ Map<String, String> map = new HashMap<>();
+ for (final String entry : str.split(split)) {
+ String[] parts = entry.split("=");
+ map.put(parts[0], parts[1]);
+ }
+ return map;
+ }
+
+
+ @SuppressWarnings("unchecked")
+ private void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+ String policyScopeName = null;
+ ObjectMapper mapper = new ObjectMapper();
+ try {
+ DCAEMicroServiceObject msBody =
+ mapper.readValue(entity.getConfigurationData().getConfigBody(), DCAEMicroServiceObject.class);
+ policyScopeName = getPolicyScope(msBody.getPolicyScope());
+ policyAdapter.setPolicyScope(policyScopeName);
+
+ policyAdapter.setPriority(msBody.getPriority());
+
+ if (msBody.getVersion() != null) {
+ policyAdapter.setServiceType(msBody.getService());
+ policyAdapter.setVersion(msBody.getVersion());
+ } else {
+ policyAdapter.setServiceType(msBody.getService());
+ }
+ if (msBody.getContent() != null) {
+ LinkedHashMap<String, Object> data = new LinkedHashMap<>();
+ LinkedHashMap<String, ?> map = (LinkedHashMap<String, ?>) msBody.getContent();
+ readRecursivlyJSONContent(map, data);
+ policyAdapter.setRuleData(data);
+ }
+
+ } catch (Exception e) {
+ LOGGER.error(e);
+ }
+
+ }
+
+ @SuppressWarnings({"rawtypes", "unchecked"})
+ public void readRecursivlyJSONContent(LinkedHashMap<String, ?> map, LinkedHashMap<String, Object> data) {
+ for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
+ Object key = iterator.next();
+ Object value = map.get(key);
+ if (value instanceof LinkedHashMap<?, ?>) {
+ LinkedHashMap<String, Object> secondObjec = new LinkedHashMap<>();
+ readRecursivlyJSONContent((LinkedHashMap<String, ?>) value, secondObjec);
+ for (Entry<String, Object> entry : secondObjec.entrySet()) {
+ data.put(key + "." + entry.getKey(), entry.getValue());
+ }
+ } else if (value instanceof ArrayList) {
+ ArrayList<?> jsonArrayVal = (ArrayList<?>) value;
+ for (int i = 0; i < jsonArrayVal.size(); i++) {
+ Object arrayvalue = jsonArrayVal.get(i);
+ if (arrayvalue instanceof LinkedHashMap<?, ?>) {
+ LinkedHashMap<String, Object> newData = new LinkedHashMap<>();
+ readRecursivlyJSONContent((LinkedHashMap<String, ?>) arrayvalue, newData);
+ for (Entry<String, Object> entry : newData.entrySet()) {
+ data.put(key + "@" + i + "." + entry.getKey(), entry.getValue());
+ }
+ } else if (arrayvalue instanceof ArrayList) {
+ ArrayList<?> jsonArrayVal1 = (ArrayList<?>) value;
+ for (int j = 0; j < jsonArrayVal1.size(); j++) {
+ Object arrayvalue1 = jsonArrayVal1.get(i);
+ data.put(key + "@" + j, arrayvalue1.toString());
+ }
+ } else {
+ data.put(key + "@" + i, arrayvalue.toString());
+ }
+ }
+ } else {
+ data.put(key.toString(), value.toString());
+ }
+ }
+ }
+
+ public String getPolicyScope(String value) {
+ List<Object> groupList = commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value);
+ if (groupList != null && !groupList.isEmpty()) {
+ GroupPolicyScopeList pScope = (GroupPolicyScopeList) groupList.get(0);
+ return pScope.getGroupName();
+ }
+ return null;
+ }
+
+ // Convert the map values and set into JSON body
+ public Map<String, String> convertMap(Map<String, String> attributesMap, Map<String, String> attributesRefMap) {
+ Map<String, String> attribute = new HashMap<>();
+ StringBuilder temp;
+ String key;
+ String value;
+ for (Entry<String, String> entry : attributesMap.entrySet()) {
+ key = entry.getKey();
+ value = entry.getValue();
+ attribute.put(key, value);
+ }
+ for (Entry<String, String> entryRef : attributesRefMap.entrySet()) {
+ key = entryRef.getKey();
+ value = entryRef.getValue();
+ attribute.put(key, value);
+ }
+ for (Entry<String, String> entryList : attributesListRefMap.entrySet()) {
+ key = entryList.getKey();
+ value = entryList.getValue();
+ attribute.put(key, value);
+ }
+ for (Entry<String, LinkedList<String>> arrayList : arrayTextList.entrySet()) {
+ key = arrayList.getKey();
+ temp = null;
+ for (Object textList : arrayList.getValue()) {
+ if (temp == null) {
+ temp = new StringBuilder();
+ temp.append("[" + textList);
+ } else {
+ temp.append("," + textList);
+ }
+ }
+ attribute.put(key, temp + "]");
+ }
+
+ return attribute;
+ }
+
+ @RequestMapping(value = {"/ms_dictionary/set_MSModelData"},
+ method = {org.springframework.web.bind.annotation.RequestMethod.POST})
+ public void SetMSModelData(HttpServletRequest request, HttpServletResponse response)
+ throws IOException, FileUploadException {
+ modelList = new ArrayList<>();
+ dirDependencyList = new ArrayList<>();
+ classMap = new LinkedHashMap<>();
+ List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
+ boolean zip = false;
+ boolean yml = false;
+ String errorMsg = "";
+ for (FileItem item : items) {
+ if (item.getName().endsWith(".zip") || item.getName().endsWith(".xmi") || item.getName().endsWith(".yml")) {
+ this.newModel = new MicroServiceModels();
+ try {
+ File file = new File(item.getName());
+ OutputStream outputStream = new FileOutputStream(file);
+ IOUtils.copy(item.getInputStream(), outputStream);
+ outputStream.close();
+ this.newFile = file.toString();
+ this.newModel.setModelName(this.newFile.split("-v")[0]);
+
+ if (this.newFile.contains("-v")) {
+ if (item.getName().endsWith(".zip")) {
+ this.newModel.setVersion(this.newFile.split("-v")[1].replace(".zip", ""));
+ zip = true;
+ } else if (item.getName().endsWith(".yml")) {
+ this.newModel.setVersion(this.newFile.split("-v")[1].replace(".yml", ""));
+ yml = true;
+ } else {
+ this.newModel.setVersion(this.newFile.split("-v")[1].replace(".xmi", ""));
+ }
+ }
+ } catch (Exception e) {
+ LOGGER.error("Upload error : ", e);
+ errorMsg = "Upload error:" + e.getMessage();
+ }
+ }
+
+ }
+
+ if (!errorMsg.isEmpty()) {
+
+ PrintWriter out = response.getWriter();
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ JSONObject j = new JSONObject();
+ j.put("errorMsg", errorMsg);
+ out.write(j.toString());
+ return;
+ }
+
+ List<File> fileList = new ArrayList<>();
+ MSModelUtils msMLUtils = new MSModelUtils();
+ this.directory = "model";
+ if (zip) {
+ extractFolder(this.newFile);
+ fileList = listModelFiles(this.directory);
+ } else if (yml == true) {
+
+ errorMsg = msMLUtils.parseTosca(this.newFile);
+ if (errorMsg != null) {
+ PrintWriter out = response.getWriter();
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+ JSONObject j = new JSONObject();
+ j.put("errorMsg", errorMsg);
+ out.write(j.toString());
+ return;
+ }
+
+ } else {
+ File file = new File(this.newFile);
+ fileList.add(file);
+ }
+ String modelType = "";
+ if (!yml) {
+ modelType = "xmi";
+ // Process Main Model file first
+ classMap = new LinkedHashMap<>();
+ for (File file : fileList) {
+ if (!file.isDirectory() && file.getName().endsWith(".xmi")) {
+ retreiveDependency(file.toString(), true);
+ }
+ }
+
+ modelList = createList();
+
+ cleanUp(this.newFile);
+ cleanUp(directory);
+ } else {
+ modelType = "yml";
+ modelList.add(this.newModel.getModelName());
+ String className = this.newModel.getModelName();
+ MSAttributeObject msAttributes = new MSAttributeObject();
+ msAttributes.setClassName(className);
+
+ LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>();
+ returnAttributeList.put(className, msMLUtils.getAttributeString());
+ msAttributes.setAttribute(returnAttributeList);
+
+ msAttributes.setSubClass(msMLUtils.getRetmap());
+
+ msAttributes.setMatchingSet(msMLUtils.getMatchableValues());
+
+ LinkedHashMap<String, String> returnReferenceList = new LinkedHashMap<>();
+
+ returnReferenceList.put(className, msMLUtils.getReferenceAttributes());
+ msAttributes.setRefAttribute(returnReferenceList);
+
+ if (msMLUtils.getListConstraints() != "") {
+ LinkedHashMap<String, String> enumList = new LinkedHashMap<>();
+ String[] listArray = msMLUtils.getListConstraints().split("#");
+ for (String str : listArray) {
+ String[] strArr = str.split("=");
+ if (strArr.length > 1) {
enumList.put(strArr[0], strArr[1]);
}
}
- msAttributes.setEnumType(enumList);
- }
-
- classMap=new LinkedHashMap<>();
- classMap.put(className, msAttributes);
-
- }
-
- PrintWriter out = response.getWriter();
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
-
- ObjectMapper mapper = new ObjectMapper();
- JSONObject j = new JSONObject();
- j.put("classListDatas", modelList);
- j.put("modelDatas", mapper.writeValueAsString(classMap));
- j.put("modelType", modelType);
- j.put("dataOrderInfo", msMLUtils.getDataOrderInfo());
-
- out.write(j.toString());
- }
-
- /*
- * Unzip file and store in the model directory for processing
- */
- @SuppressWarnings("rawtypes")
- private void extractFolder(String zipFile ) {
- int BUFFER = 2048;
- File file = new File(zipFile);
-
- try (ZipFile zip = new ZipFile(file)) {
- String newPath = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
- this.directory = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
- checkZipDirectory(this.directory);
- new File(newPath).mkdir();
- Enumeration zipFileEntries = zip.entries();
-
- // Process each entry
- while (zipFileEntries.hasMoreElements()){
- // grab a zip file entry
- ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
- String currentEntry = entry.getName();
- File destFile = new File("model" + File.separator + currentEntry);
- File destinationParent = destFile.getParentFile();
-
- destinationParent.mkdirs();
-
- if (!entry.isDirectory()){
- BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
- int currentByte;
- byte[] data = new byte[BUFFER];
- try (FileOutputStream fos = new FileOutputStream(destFile);
- BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) {
- while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
- dest.write(data, 0, currentByte);
- }
- dest.flush();
- } catch (IOException e) {
- LOGGER.error("Failed to write zip contents to {}" + destFile + e);
- //
- // PLD should I throw e?
- //
- throw e;
- }
- }
-
- if (currentEntry.endsWith(".zip")){
- extractFolder(destFile.getAbsolutePath());
- }
- }
- } catch (IOException e) {
- LOGGER.error("Failed to unzip model file " + zipFile, e);
- }
- }
-
- private void retreiveDependency(String workingFile, Boolean modelClass) {
-
- MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
- Map<String, MSAttributeObject> tempMap;
-
- tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
-
- classMap.putAll(tempMap);
- LOGGER.info(tempMap);
-
- return;
-
- }
-
- private List<File> listModelFiles(String directoryName) {
- File fileDirectory = new File(directoryName);
- List<File> resultList = new ArrayList<>();
- File[] fList = fileDirectory.listFiles();
- for (File file : fList) {
- if (file.isFile()) {
- resultList.add(file);
- } else if (file.isDirectory()) {
- dirDependencyList.add(file.getName());
- resultList.addAll(listModelFiles(file.getAbsolutePath()));
- }
- }
- return resultList;
- }
-
+ msAttributes.setEnumType(enumList);
+ }
+
+ classMap = new LinkedHashMap<>();
+ classMap.put(className, msAttributes);
+
+ }
+
+ PrintWriter out = response.getWriter();
+
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ ObjectMapper mapper = new ObjectMapper();
+ JSONObject j = new JSONObject();
+ j.put("classListDatas", modelList);
+ j.put("modelDatas", mapper.writeValueAsString(classMap));
+ j.put("modelType", modelType);
+ j.put("dataOrderInfo", msMLUtils.getDataOrderInfo());
+
+ out.write(j.toString());
+ }
+
+ /*
+ * Unzip file and store in the model directory for processing
+ */
+ @SuppressWarnings("rawtypes")
+ private void extractFolder(String zipFile) {
+ int BUFFER = 2048;
+ File file = new File(zipFile);
+
+ try (ZipFile zip = new ZipFile(file)) {
+ String newPath = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
+ this.directory = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4);
+ checkZipDirectory(this.directory);
+ new File(newPath).mkdir();
+ Enumeration zipFileEntries = zip.entries();
+
+ // Process each entry
+ while (zipFileEntries.hasMoreElements()) {
+ // grab a zip file entry
+ ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
+ String currentEntry = entry.getName();
+ File destFile = new File("model" + File.separator + currentEntry);
+ File destinationParent = destFile.getParentFile();
+
+ destinationParent.mkdirs();
+
+ if (!entry.isDirectory()) {
+ BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
+ int currentByte;
+ byte[] data = new byte[BUFFER];
+ try (FileOutputStream fos = new FileOutputStream(destFile);
+ BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) {
+ while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
+ dest.write(data, 0, currentByte);
+ }
+ dest.flush();
+ } catch (IOException e) {
+ LOGGER.error("Failed to write zip contents to {}" + destFile + e);
+ //
+ // PLD should I throw e?
+ //
+ throw e;
+ }
+ }
+
+ if (currentEntry.endsWith(".zip")) {
+ extractFolder(destFile.getAbsolutePath());
+ }
+ }
+ } catch (IOException e) {
+ LOGGER.error("Failed to unzip model file " + zipFile, e);
+ }
+ }
+
+ private void retreiveDependency(String workingFile, Boolean modelClass) {
+
+ MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
+ Map<String, MSAttributeObject> tempMap;
+
+ tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
+
+ classMap.putAll(tempMap);
+ LOGGER.info(tempMap);
+
+ return;
+
+ }
+
+ private List<File> listModelFiles(String directoryName) {
+ File fileDirectory = new File(directoryName);
+ List<File> resultList = new ArrayList<>();
+ File[] fList = fileDirectory.listFiles();
+ for (File file : fList) {
+ if (file.isFile()) {
+ resultList.add(file);
+ } else if (file.isDirectory()) {
+ dirDependencyList.add(file.getName());
+ resultList.addAll(listModelFiles(file.getAbsolutePath()));
+ }
+ }
+ return resultList;
+ }
+
public void cleanUp(String path) {
- if (path!=null){
+ if (path != null) {
try {
FileUtils.forceDelete(new File(path));
} catch (IOException e) {
- LOGGER.error("Failed to delete folder " + path, e);
- }
+ LOGGER.error("Failed to delete folder " + path, e);
+ }
}
}
-
+
public void checkZipDirectory(String zipDirectory) {
Path path = Paths.get(zipDirectory);
-
+
if (Files.exists(path)) {
cleanUp(zipDirectory);
}
}
-
+
private List<String> createList() {
- List<String> list = new ArrayList<>();
- for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()){
- if (cMap.getValue().isPolicyTempalate()){
+ List<String> list = new ArrayList<>();
+ for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()) {
+ if (cMap.getValue().isPolicyTempalate()) {
list.add(cMap.getKey());
}
-
+
}
-
- if (list.isEmpty()){
- if (classMap.containsKey(this.newModel.getModelName())){
+
+ if (list.isEmpty()) {
+ if (classMap.containsKey(this.newModel.getModelName())) {
list.add(this.newModel.getModelName());
- }else {
+ } else {
list.add("EMPTY");
}
}
return list;
}
- public Map<String, String> getAttributesListRefMap() {
- return attributesListRefMap;
- }
+ public Map<String, String> getAttributesListRefMap() {
+ return attributesListRefMap;
+ }
- public Map<String, LinkedList<String>> getArrayTextList() {
- return arrayTextList;
- }
+ public Map<String, LinkedList<String>> getArrayTextList() {
+ return arrayTextList;
+ }
}
+
class DCAEMicroServiceObject {
- private String service;
- private String location;
- private String uuid;
- private String policyName;
- private String description;
- private String configName;
- private String templateVersion;
- private String version;
- private String priority;
- private String policyScope;
- private String riskType;
- private String riskLevel;
- private String guard = null;
-
- public String getGuard() {
- return guard;
- }
- public void setGuard(String guard) {
- this.guard = guard;
- }
- public String getRiskType() {
- return riskType;
- }
- public void setRiskType(String riskType) {
- this.riskType = riskType;
- }
- public String getRiskLevel() {
- return riskLevel;
- }
- public void setRiskLevel(String riskLevel) {
- this.riskLevel = riskLevel;
- }
- public String getPolicyScope() {
- return policyScope;
- }
- public void setPolicyScope(String policyScope) {
- this.policyScope = policyScope;
- }
-
- public String getPriority() {
- return priority;
- }
- public void setPriority(String priority) {
- this.priority = priority;
- }
- public String getVersion() {
- return version;
- }
- public void setVersion(String version) {
- this.version = version;
- }
- private Object content;
-
-
- public String getPolicyName() {
- return policyName;
- }
- public void setPolicyName(String policyName) {
- this.policyName = policyName;
- }
- public String getDescription() {
- return description;
- }
- public void setDescription(String description) {
- this.description = description;
- }
- public String getConfigName() {
- return configName;
- }
- public void setConfigName(String configName) {
- this.configName = configName;
- }
- public Object getContent() {
- return content;
- }
- public void setContent(Object content) {
- this.content = content;
- }
-
- public String getService() {
- return service;
- }
- public void setService(String service) {
- this.service = service;
- }
- public String getLocation() {
- return location;
- }
- public void setLocation(String location) {
- this.location = location;
- }
-
- public String getUuid() {
- return uuid;
- }
- public void setUuid(String uuid) {
- this.uuid = uuid;
- }
- public String getTemplateVersion() {
- return templateVersion;
- }
- public void setTemplateVersion(String templateVersion) {
- this.templateVersion = templateVersion;
- }
-
-} \ No newline at end of file
+ private String service;
+ private String location;
+ private String uuid;
+ private String policyName;
+ private String description;
+ private String configName;
+ private String templateVersion;
+ private String version;
+ private String priority;
+ private String policyScope;
+ private String riskType;
+ private String riskLevel;
+ private String guard = null;
+
+ public String getGuard() {
+ return guard;
+ }
+
+ public void setGuard(String guard) {
+ this.guard = guard;
+ }
+
+ public String getRiskType() {
+ return riskType;
+ }
+
+ public void setRiskType(String riskType) {
+ this.riskType = riskType;
+ }
+
+ public String getRiskLevel() {
+ return riskLevel;
+ }
+
+ public void setRiskLevel(String riskLevel) {
+ this.riskLevel = riskLevel;
+ }
+
+ public String getPolicyScope() {
+ return policyScope;
+ }
+
+ public void setPolicyScope(String policyScope) {
+ this.policyScope = policyScope;
+ }
+
+ public String getPriority() {
+ return priority;
+ }
+
+ public void setPriority(String priority) {
+ this.priority = priority;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ private Object content;
+
+
+ public String getPolicyName() {
+ return policyName;
+ }
+
+ public void setPolicyName(String policyName) {
+ this.policyName = policyName;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public String getConfigName() {
+ return configName;
+ }
+
+ public void setConfigName(String configName) {
+ this.configName = configName;
+ }
+
+ public Object getContent() {
+ return content;
+ }
+
+ public void setContent(Object content) {
+ this.content = content;
+ }
+
+ public String getService() {
+ return service;
+ }
+
+ public void setService(String service) {
+ this.service = service;
+ }
+
+ public String getLocation() {
+ return location;
+ }
+
+ public void setLocation(String location) {
+ this.location = location;
+ }
+
+ public String getUuid() {
+ return uuid;
+ }
+
+ public void setUuid(String uuid) {
+ this.uuid = uuid;
+ }
+
+ public String getTemplateVersion() {
+ return templateVersion;
+ }
+
+ public void setTemplateVersion(String templateVersion) {
+ this.templateVersion = templateVersion;
+ }
+
+}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java
index 3b4d03de8..3485163e4 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java
@@ -2,8 +2,9 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
+ * Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,10 +24,12 @@ package org.onap.policy.controller;
import com.att.research.xacml.util.XACMLProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
+import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -34,15 +37,17 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
-import java.util.TreeMap;
import javax.annotation.PostConstruct;
-import javax.mail.MessagingException;
import javax.script.SimpleBindings;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
import org.json.JSONObject;
import org.onap.policy.admin.PolicyNotificationMail;
import org.onap.policy.admin.RESTfulPAPEngine;
+import org.onap.policy.common.logging.eelf.MessageCodes;
+import org.onap.policy.common.logging.eelf.PolicyLogger;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.model.PDPGroupContainer;
@@ -57,6 +62,7 @@ import org.onap.policy.rest.jpa.UserInfo;
import org.onap.policy.utils.UserUtils.Pair;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
+import org.onap.policy.xacml.util.XACMLPolicyScanner;
import org.onap.portalsdk.core.controller.RestrictedBaseController;
import org.onap.portalsdk.core.domain.UserApp;
import org.onap.portalsdk.core.web.support.JsonMessage;
@@ -68,7 +74,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
-
@Controller
@RequestMapping("/")
public class PolicyController extends RestrictedBaseController {
@@ -105,6 +110,9 @@ public class PolicyController extends RestrictedBaseController {
private static final String characterEncoding = "UTF-8";
private static final String contentType = "application/json";
private static final String file = "file";
+ private static final String SUPERADMIN = "super-admin";
+ private static final String POLICYGUEST = "Policy Guest";
+ private static final String LOGINID = "loginId";
// Smtp Java Mail Properties
private static String smtpHost = null;
@@ -147,7 +155,6 @@ public class PolicyController extends RestrictedBaseController {
private static boolean jUnit = false;
-
public static boolean isjUnit() {
return jUnit;
}
@@ -175,8 +182,9 @@ public class PolicyController extends RestrictedBaseController {
try {
String fileName;
if (jUnit) {
- fileName = new File(".").getCanonicalPath() + File.separator + "src" + File.separator + "test"
- + File.separator + "resources" + File.separator + "JSONConfig.json";
+ fileName = new File(".").getCanonicalPath() + File.separator + "src"
+ + File.separator + "test" + File.separator + "resources" + File.separator
+ + "JSONConfig.json";
} else {
fileName = "xacml.admin.properties";
}
@@ -227,17 +235,19 @@ public class PolicyController extends RestrictedBaseController {
// Get the Property Values for Dashboard tab Limit
try {
setLogTableLimit(prop.getProperty("xacml.onap.dashboard.logTableLimit"));
- setSystemAlertTableLimit(prop.getProperty("xacml.onap.dashboard.systemAlertTableLimit"));
+ setSystemAlertTableLimit(
+ prop.getProperty("xacml.onap.dashboard.systemAlertTableLimit"));
} catch (Exception e) {
- policyLogger
- .error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Dashboard tab Property fields are missing" + e);
+ policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE
+ + "Dashboard tab Property fields are missing" + e);
setLogTableLimit("5000");
setSystemAlertTableLimit("2000");
}
System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "xacml.admin.properties");
} catch (IOException ex) {
policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE
- + "Exception Occured while reading the Smtp properties from xacml.admin.properties file" + ex);
+ + "Exception Occured while reading the Smtp properties from xacml.admin.properties file"
+ + ex);
}
// Initialize the FunctionDefinition table at Server Start up
@@ -253,7 +263,7 @@ public class PolicyController extends RestrictedBaseController {
/**
* Get FunctionData Type from DB.
- *
+ *
* @return list of FunctionData.
*/
public static Map<Datatype, List<FunctionDefinition>> getFunctionDatatypeMap() {
@@ -267,7 +277,7 @@ public class PolicyController extends RestrictedBaseController {
/**
* Get Function ID.
- *
+ *
* @return Function ID.
*/
public static Map<String, FunctionDefinition> getFunctionIdMap() {
@@ -287,7 +297,8 @@ public class PolicyController extends RestrictedBaseController {
FunctionDefinition value = (FunctionDefinition) functiondefinitions.get(i);
mapID2Function.put(value.getXacmlid(), value);
if (!mapDatatype2Function.containsKey(value.getDatatypeBean())) {
- mapDatatype2Function.put(value.getDatatypeBean(), new ArrayList<FunctionDefinition>());
+ mapDatatype2Function.put(value.getDatatypeBean(),
+ new ArrayList<FunctionDefinition>());
}
mapDatatype2Function.get(value.getDatatypeBean()).add(value);
}
@@ -295,31 +306,32 @@ public class PolicyController extends RestrictedBaseController {
/**
* Get Functional Definition data.
- *
+ *
* @param request HttpServletRequest.
* @param response HttpServletResponse.
*/
@RequestMapping(value = {"/get_FunctionDefinitionDataByName"},
method = {org.springframework.web.bind.annotation.RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
- public void getFunctionDefinitionData(HttpServletRequest request, HttpServletResponse response) {
+ public void getFunctionDefinitionData(HttpServletRequest request,
+ HttpServletResponse response) {
try {
Map<String, Object> model = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
- model.put("functionDefinitionDatas",
- mapper.writeValueAsString(commonClassDao.getDataByColumn(FunctionDefinition.class, "shortname")));
+ model.put("functionDefinitionDatas", mapper.writeValueAsString(
+ commonClassDao.getDataByColumn(FunctionDefinition.class, "shortname")));
JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
JSONObject j = new JSONObject(msg);
response.getWriter().write(j.toString());
} catch (Exception e) {
- policyLogger.error(
- XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while retriving the Function Definition data" + e);
+ policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE
+ + "Error while retriving the Function Definition data" + e);
}
}
/**
* Get PolicyEntity Data from db.
- *
+ *
* @param scope scopeName.
* @param policyName policyName.
* @return policyEntity data.
@@ -332,13 +344,13 @@ public class PolicyController extends RestrictedBaseController {
/**
* Get Policy User Roles from db.
- *
+ *
* @param userId LoginID.
* @return list of Roles.
*/
public List<String> getRolesOfUser(String userId) {
List<String> rolesList = new ArrayList<>();
- List<Object> roles = commonClassDao.getDataById(Roles.class, "loginId", userId);
+ List<Object> roles = commonClassDao.getDataById(Roles.class, LOGINID, userId);
for (Object role : roles) {
rolesList.add(((Roles) role).getRole());
}
@@ -346,12 +358,12 @@ public class PolicyController extends RestrictedBaseController {
}
public List<Object> getRoles(String userId) {
- return commonClassDao.getDataById(Roles.class, "loginId", userId);
+ return commonClassDao.getDataById(Roles.class, LOGINID, userId);
}
/**
* Get List of User Roles.
- *
+ *
* @param request HttpServletRequest.
* @param response HttpServletResponse.
*/
@@ -374,7 +386,7 @@ public class PolicyController extends RestrictedBaseController {
/**
* Policy tabs Model and View.
- *
+ *
* @param request Request input.
* @return view model.
*/
@@ -386,19 +398,20 @@ public class PolicyController extends RestrictedBaseController {
//
// Set the URL for the RESTful PAP Engine
//
- setPapEngine((PAPPolicyEngine) new RESTfulPAPEngine(myRequestUrl));
- new PDPGroupContainer((PAPPolicyEngine) new RESTfulPAPEngine(myRequestUrl));
+ setPapEngine(new RESTfulPAPEngine(myRequestUrl));
+ new PDPGroupContainer(new RESTfulPAPEngine(myRequestUrl));
} catch (Exception e) {
- policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception Occured while loading PAP" + e);
+ policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR
+ + "Exception Occured while loading PAP" + e);
}
Map<String, Object> model = new HashMap<>();
return new ModelAndView("policy_Editor", "model", model);
}
/**
- * Read the role from session.
- *
- * @param request Request input.
+ * Read the role from session for inserting into the database.
+ *
+ * @param request Request input for Role.
*/
public void getUserRoleFromSession(HttpServletRequest request) {
// While user landing on Policy page, fetch the userId and Role from
@@ -415,23 +428,48 @@ public class PolicyController extends RestrictedBaseController {
newRoles.add(userApp.getRole().getName());
}
List<Object> userRoles = getRoles(userId);
- String filteredRole = filterRole(newRoles);
- if (userRoles == null || userRoles.isEmpty()) {
- savePolicyRoles(name, filteredRole, userId);
- } else {
- Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
- roles = pair.u;
- if (!roles.contains(filteredRole)) {
- String query = "delete from Roles where loginid='" + userId + "'";
- commonClassDao.updateQuery(query);
+ List<String> filteredRoles = filterRole(newRoles);
+ if (!filteredRoles.isEmpty()) {
+ cleanUpRoles(filteredRoles, userId);
+ }
+ for (String filteredRole : filteredRoles) {
+ if (userRoles == null || userRoles.isEmpty()) {
savePolicyRoles(name, filteredRole, userId);
+ } else {
+ userRoles = getRoles(userId);
+ Pair<Set<String>, List<String>> pair =
+ org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
+ roles = pair.u;
+ if (!roles.contains(filteredRole)) {
+ savePolicyRoles(name, filteredRole, userId);
+ }
+ }
+ }
+ }
+
+ /**
+ * Build a delete query for cleaning up roles and execute it.
+ *
+ * @param filteredRoles Filtered roles list.
+ * @param userId UserID.
+ */
+ private void cleanUpRoles(List<String> filteredRoles, String userId) {
+ StringBuilder query = new StringBuilder();
+ query.append("delete from Roles where loginid = '" + userId + "'");
+ if (filteredRoles.contains(SUPERADMIN)) {
+ query.append("and not role = '" + SUPERADMIN + "'");
+ } else {
+ for (String filteredRole : filteredRoles) {
+ query.append("and not role = '" + filteredRole + "'");
}
}
+ query.append("and id > 0");
+ commonClassDao.updateQuery(query.toString());
}
/**
* Save the Role to DB.
- *
+ *
* @param name User Name.
* @param filteredRole Role Name.
* @param userId User LoginID.
@@ -450,29 +488,40 @@ public class PolicyController extends RestrictedBaseController {
/**
* Filter the list of roles hierarchy wise.
- *
+ *
* @param newRoles list of roles from request.
* @return
*/
- private String filterRole(List<String> newRoles) {
- Map<Integer, String> roleMap = new TreeMap<>();
- roleMap.put(6, "guest");
+ private List<String> filterRole(List<String> newRoles) {
+ List<String> roles = new ArrayList<>();
+ boolean superCheck = false;
for (String role : newRoles) {
- if ("Policy Super Admin".equalsIgnoreCase(role.trim())
+ if ("Policy Super Guest".equalsIgnoreCase(role.trim())) {
+ superCheck = true;
+ roles.add("super-guest");
+ } else if ("Policy Super Editor".equalsIgnoreCase(role.trim())) {
+ superCheck = true;
+ roles.clear();
+ roles.add("super-editor");
+ } else if ("Policy Super Admin".equalsIgnoreCase(role.trim())
|| "System Administrator".equalsIgnoreCase(role.trim())
|| "Standard User".equalsIgnoreCase(role.trim())) {
- roleMap.put(1, "super-admin");
- } else if ("Policy Super Editor".equalsIgnoreCase(role.trim())) {
- roleMap.put(2, "super-editor");
- } else if ("Policy Super Guest".equalsIgnoreCase(role.trim())) {
- roleMap.put(3, "super-guest");
- } else if ("Policy Admin".equalsIgnoreCase(role.trim())) {
- roleMap.put(4, "admin");
- } else if ("Policy Editor".equalsIgnoreCase(role.trim())) {
- roleMap.put(5, "editor");
+ superCheck = true;
+ roles.clear();
+ roles.add(SUPERADMIN);
+ }
+ if (!roles.contains(SUPERADMIN)
+ || (POLICYGUEST.equalsIgnoreCase(role) && !superCheck)) {
+ if ("Policy Admin".equalsIgnoreCase(role.trim())) {
+ roles.add("admin");
+ } else if ("Policy Editor".equalsIgnoreCase(role.trim())) {
+ roles.add("editor");
+ } else if (POLICYGUEST.equalsIgnoreCase(role.trim())) {
+ roles.add("guest");
+ }
}
}
- return roleMap.entrySet().iterator().next().getValue();
+ return roles;
}
public PAPPolicyEngine getPapEngine() {
@@ -485,18 +534,19 @@ public class PolicyController extends RestrictedBaseController {
/**
* Get UserName based on LoginID.
- *
+ *
* @param createdBy loginID.
* @return name.
*/
public String getUserName(String createdBy) {
String loginId = createdBy;
- List<Object> data = commonClassDao.getDataById(UserInfo.class, "loginId", loginId);
+ List<Object> data = commonClassDao.getDataById(UserInfo.class, LOGINID, loginId);
return data.get(0).toString();
}
/**
* Check if the Policy is Active or not.
+ *
* @param query sql query.
* @return boolean.
*/
@@ -525,40 +575,34 @@ public class PolicyController extends RestrictedBaseController {
}
public PolicyVersion getPolicyEntityFromPolicyVersion(String query) {
- return (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", query);
+ return (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName",
+ query);
}
public List<Object> getDataByQuery(String query, SimpleBindings params) {
return commonClassDao.getDataByQuery(query, params);
}
-
@SuppressWarnings("rawtypes")
public Object getEntityItem(Class className, String columname, String key) {
return commonClassDao.getEntityItem(className, columname, key);
}
-
/**
* Watch Policy Function.
- *
+ *
* @param entity PolicyVersion entity.
* @param policyName updated policy name.
* @param mode type of action rename/delete/import.
*/
public void watchPolicyFunction(PolicyVersion entity, String policyName, String mode) {
PolicyNotificationMail email = new PolicyNotificationMail();
- try {
- email.sendMail(entity, policyName, mode, commonClassDao);
- } catch (MessagingException e) {
- policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR
- + "Excepton Occured while Renaming/Deleting a Policy or Scope" + e);
- }
+ email.sendMail(entity, policyName, mode, commonClassDao);
}
/**
* Switch Version Policy Content.
- *
+ *
* @param pName which is used to find associated versions.
* @return list of available versions based on policy name.
*/
@@ -569,11 +613,14 @@ public class PolicyController extends RestrictedBaseController {
dbCheckName = dbCheckName.replace(".Config_", ":Config_");
} else if (dbCheckName.contains("Action_")) {
dbCheckName = dbCheckName.replace(".Action_", ":Action_");
+ } else if (dbCheckName.contains("Decision_MS_")) {
+ dbCheckName = dbCheckName.replace(".Decision_MS_", ":Decision_MS_");
} else if (dbCheckName.contains("Decision_")) {
dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
}
String[] splitDbCheckName = dbCheckName.split(":");
- String query = "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
+ String query =
+ "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
SimpleBindings params = new SimpleBindings();
params.put("splitDBCheckName1", splitDbCheckName[1] + "%");
params.put("splitDBCheckName0", splitDbCheckName[0]);
@@ -583,13 +630,14 @@ public class PolicyController extends RestrictedBaseController {
PolicyEntity pEntity = (PolicyEntity) entity;
String removeExtension = pEntity.getPolicyName().replace(".xml", "");
String version = removeExtension.substring(removeExtension.lastIndexOf('.') + 1);
- av.add(version);
+ String userName = getUserId(pEntity, "@ModifiedBy:");
+ av.add(version + " | " + pEntity.getModifiedDate() + " | " + userName);
}
if (policyName.contains("/")) {
policyName = policyName.replace("/", File.separator);
}
- PolicyVersion entity =
- (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", policyName);
+ PolicyVersion entity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class,
+ "policyName", policyName);
JSONObject el = new JSONObject();
el.put("activeVersion", entity.getActiveVersion());
el.put("availableVersions", av);
@@ -597,6 +645,58 @@ public class PolicyController extends RestrictedBaseController {
return el;
}
+ public String getUserId(PolicyEntity data, String value) {
+ String userId = "";
+ String uValue = value;
+ String description = getDescription(data);
+ if (description.contains(uValue)) {
+ userId = description.substring(description.indexOf(uValue) + uValue.length(),
+ description.lastIndexOf(uValue));
+ }
+ UserInfo userInfo = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", userId);
+ if (userInfo == null) {
+ return SUPERADMIN;
+ }
+ return userInfo.getUserName();
+ }
+
+ public String getDescription(PolicyEntity data) {
+ InputStream stream =
+ new ByteArrayInputStream(data.getPolicyData().getBytes(StandardCharsets.UTF_8));
+ Object policy = XACMLPolicyScanner.readPolicy(stream);
+ if (policy instanceof PolicySetType) {
+ return ((PolicySetType) policy).getDescription();
+ } else if (policy instanceof PolicyType) {
+ return ((PolicyType) policy).getDescription();
+ } else {
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE
+ + "Expecting a PolicySet/Policy/Rule object. Got: "
+ + policy.getClass().getCanonicalName());
+ return null;
+ }
+ }
+
+ public String[] getUserInfo(PolicyEntity data, List<PolicyVersion> activePolicies) {
+ String policyName = data.getScope().replace(".", File.separator) + File.separator
+ + data.getPolicyName().substring(0, data.getPolicyName().indexOf('.'));
+ PolicyVersion polVersion = activePolicies.stream()
+ .filter(a -> policyName.equals(a.getPolicyName())).findAny().orElse(null);
+ String[] result = new String[2];
+ UserInfo userCreate = null;
+ UserInfo userModify = null;
+ if (polVersion != null) {
+ userCreate = (UserInfo) getEntityItem(UserInfo.class, "userLoginId",
+ polVersion.getCreatedBy());
+ userModify = (UserInfo) getEntityItem(UserInfo.class, "userLoginId",
+ polVersion.getModifiedBy());
+ }
+
+ result[0] = userCreate != null ? userCreate.getUserName() : SUPERADMIN;
+ result[1] = userModify != null ? userModify.getUserName() : SUPERADMIN;
+
+ return result;
+ }
+
public static String getLogTableLimit() {
return logTableLimit;
}
@@ -625,7 +725,8 @@ public class PolicyController extends RestrictedBaseController {
return mapDatatype2Function;
}
- public static void setMapDatatype2Function(Map<Datatype, List<FunctionDefinition>> mapDatatype2Function) {
+ public static void setMapDatatype2Function(
+ Map<Datatype, List<FunctionDefinition>> mapDatatype2Function) {
PolicyController.mapDatatype2Function = mapDatatype2Function;
}
@@ -851,7 +952,7 @@ public class PolicyController extends RestrictedBaseController {
/**
* Set File Size limit.
- *
+ *
* @param uploadSize value.
*/
public static void setFileSizeLimit(String uploadSize) {
@@ -869,7 +970,7 @@ public class PolicyController extends RestrictedBaseController {
/**
* Function to convert date.
- *
+ *
* @param dateTTL input date value.
* @return
*/
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java
index daf3d6c97..b02da1996 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,7 +20,6 @@
package org.onap.policy.controller;
-
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
@@ -54,123 +53,175 @@ import com.fasterxml.jackson.databind.ObjectMapper;
@Controller
@RequestMapping("/")
-public class PolicyRolesController extends RestrictedBaseController{
-
- private static final Logger LOGGER = FlexLogger.getLogger(PolicyRolesController.class);
-
- @Autowired
- CommonClassDao commonClassDao;
-
- public void setCommonClassDao(CommonClassDao commonClassDao) {
- this.commonClassDao = commonClassDao;
- }
-
- List<String> scopelist;
-
- @RequestMapping(value={"/get_RolesData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
- public void getPolicyRolesEntityData(HttpServletRequest request, HttpServletResponse response){
- try{
- Map<String, Object> model = new HashMap<>();
- ObjectMapper mapper = new ObjectMapper();
- model.put("rolesDatas", mapper.writeValueAsString(commonClassDao.getUserRoles()));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
- }
- catch (Exception e){
- LOGGER.error("Exception Occured"+e);
- }
- }
-
- @RequestMapping(value={"/save_NonSuperRolesData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
- public ModelAndView SaveRolesEntityData(HttpServletRequest request, HttpServletResponse response){
- try{
- StringBuilder scopeName = new StringBuilder();
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- String userId = UserUtils.getUserSession(request).getOrgUserId();
- JsonNode root = mapper.readTree(request.getReader());
- ReadScopes adapter = mapper.readValue(root.get("editRoleData").toString(), ReadScopes.class);
- for(int i = 0; i < adapter.getScope().size(); i++){
- if(i == 0){
- scopeName.append(adapter.getScope().get(0));
- }else{
- scopeName.append("," + adapter.getScope().get(i));
- }
- }
- LOGGER.info("****************************************Logging UserID for Roles Function********************************************************");
- LOGGER.info("UserId: " + userId + "Updating the Scope for following user" + adapter.getLoginId() + "ScopeNames" + adapter.getScope());
- LOGGER.info("*********************************************************************************************************************************");
- PolicyRoles roles = new PolicyRoles();
- roles.setId(adapter.getId());
- roles.setLoginId(adapter.getLoginId());
- roles.setRole(adapter.getRole());
- roles.setScope(scopeName.toString());
- commonClassDao.update(roles);
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
-
- PrintWriter out = response.getWriter();
- String responseString = mapper.writeValueAsString(commonClassDao.getUserRoles());
- JSONObject j = new JSONObject("{rolesDatas: " + responseString + "}");
-
- out.write(j.toString());
- }
- catch (Exception e){
- LOGGER.error("Exception Occured"+e);
- }
- return null;
- }
-
- @RequestMapping(value={"/get_PolicyRolesScopeData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
- public void getPolicyScopesEntityData(HttpServletRequest request, HttpServletResponse response){
- try{
- scopelist = new ArrayList<>();
- Map<String, Object> model = new HashMap<>();
- ObjectMapper mapper = new ObjectMapper();
- mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
- List<String> scopesData = commonClassDao.getDataByColumn(PolicyEditorScopes.class, "scopeName");
- model.put("scopeDatas", mapper.writeValueAsString(scopesData));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
- }
- catch (Exception e){
- LOGGER.error("Exception Occured"+e);
- }
- }
+public class PolicyRolesController extends RestrictedBaseController {
+
+ private static final Logger LOGGER = FlexLogger.getLogger(PolicyRolesController.class);
+
+ @Autowired
+ CommonClassDao commonClassDao;
+
+ public void setCommonClassDao(CommonClassDao commonClassDao) {
+ this.commonClassDao = commonClassDao;
+ }
+
+ List<String> scopelist;
+
+ /**
+ * Gets the policy roles entity data.
+ *
+ * @param request the request
+ * @param response the response
+ */
+ @RequestMapping(value = { "/get_RolesData" }, method = {
+ org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE)
+ public void getPolicyRolesEntityData(HttpServletRequest request, HttpServletResponse response) {
+ try {
+ Map<String, Object> model = new HashMap<>();
+ ObjectMapper mapper = new ObjectMapper();
+ model.put("rolesDatas", mapper.writeValueAsString(commonClassDao.getUserRoles()));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ } catch (Exception e) {
+ LOGGER.error("Exception Occured" + e);
+ }
+ }
+
+ /**
+ * Save roles and Mechid entity data.
+ *
+ * @param request the request
+ * @param response the response
+ * @return the model and view
+ */
+ @RequestMapping(value = { "/save_NonSuperRolesData" }, method = {
+ org.springframework.web.bind.annotation.RequestMethod.POST })
+ public ModelAndView SaveRolesEntityData(HttpServletRequest request, HttpServletResponse response) {
+ try {
+ StringBuilder scopeName = new StringBuilder();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ String userId = UserUtils.getUserSession(request).getOrgUserId();
+ JsonNode root = mapper.readTree(request.getReader());
+ ReadScopes adapter = mapper.readValue(root.get("editRoleData").toString(), ReadScopes.class);
+ for (int i = 0; i < adapter.getScope().size(); i++) {
+ if (i == 0) {
+ scopeName.append(adapter.getScope().get(0));
+ } else {
+ scopeName.append("," + adapter.getScope().get(i));
+ }
+ }
+ LOGGER.info(
+ "****************************************Logging UserID for Roles Function********************************************************");
+ LOGGER.info("UserId: " + userId + "Updating the Scope for following user" + adapter.getLoginId()
+ + "ScopeNames" + adapter.getScope());
+ LOGGER.info(
+ "*********************************************************************************************************************************");
+ UserInfo userInfo = new UserInfo();
+ userInfo.setUserLoginId(adapter.getLoginId().getUserName());
+ userInfo.setUserName(adapter.getLoginId().getUserName());
+
+ boolean checkNew = false;
+ if (adapter.getId() == 0 && "mechid".equals(adapter.getRole())) {
+ // Save new mechid scopes entity data.
+ LOGGER.info(
+ "****************************************Logging UserID for New Mechid Function***************************************************");
+ LOGGER.info("UserId:" + userId + "Adding new mechid-scopes for following user" + adapter.getLoginId()
+ + "ScopeNames " + adapter.getScope());
+ LOGGER.info(
+ "*********************************************************************************************************************************");
+ // First add the mechid to userinfo
+ commonClassDao.save(userInfo);
+ checkNew = true;
+ }
+
+ PolicyRoles roles = new PolicyRoles();
+ roles.setId(adapter.getId());
+ roles.setLoginId(adapter.getLoginId());
+ roles.setRole(adapter.getRole());
+ roles.setScope(scopeName.toString());
+ if (checkNew) {
+ roles.setLoginId(userInfo);
+ commonClassDao.save(roles);
+ } else {
+ commonClassDao.update(roles);
+ }
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+ String responseString = mapper.writeValueAsString(commonClassDao.getUserRoles());
+ JSONObject j = new JSONObject("{rolesDatas: " + responseString + "}");
+
+ out.write(j.toString());
+ } catch (Exception e) {
+ LOGGER.error("Exception Occured" + e);
+ }
+ return null;
+ }
+
+ /**
+ * Gets the policy scopes entity data.
+ *
+ * @param request the request
+ * @param response the response
+ */
+ @RequestMapping(value = { "/get_PolicyRolesScopeData" }, method = {
+ org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE)
+ public void getPolicyScopesEntityData(HttpServletRequest request, HttpServletResponse response) {
+ try {
+ scopelist = new ArrayList<>();
+ Map<String, Object> model = new HashMap<>();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
+ List<String> scopesData = commonClassDao.getDataByColumn(PolicyEditorScopes.class, "scopeName");
+ model.put("scopeDatas", mapper.writeValueAsString(scopesData));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+ JSONObject j = new JSONObject(msg);
+ response.getWriter().write(j.toString());
+ } catch (Exception e) {
+ LOGGER.error("Exception Occured" + e);
+ }
+ }
}
-class ReadScopes{
- private int id;
- private UserInfo loginId;
- private String role;
- private List<String> scope;
-
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public UserInfo getLoginId() {
- return loginId;
- }
- public void setLoginId(UserInfo loginId) {
- this.loginId = loginId;
- }
- public String getRole() {
- return role;
- }
- public void setRole(String role) {
- this.role = role;
- }
- public List<String> getScope() {
- return scope;
- }
- public void setScope(List<String> scope) {
- this.scope = scope;
- }
+class ReadScopes {
+ private int id;
+ private UserInfo loginId;
+ private String role;
+ private List<String> scope;
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public UserInfo getLoginId() {
+ return loginId;
+ }
+
+ public void setLoginId(UserInfo loginId) {
+ this.loginId = loginId;
+ }
+
+ public String getRole() {
+ return role;
+ }
+
+ public void setRole(String role) {
+ this.role = role;
+ }
+
+ public List<String> getScope() {
+ return scope;
+ }
+
+ public void setScope(List<String> scope) {
+ this.scope = scope;
+ }
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/UserUtils.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/UserUtils.java
index 1f68ffc0e..40c839676 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/UserUtils.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/UserUtils.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,49 +20,107 @@
package org.onap.policy.utils;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
+import java.util.Map;
import java.util.Set;
import org.onap.policy.model.Roles;
public final class UserUtils {
-
- private UserUtils () {
- // Empty Constructor
- }
-
- public static class Pair<T, U> {
- public final T t;
- public final U u;
-
- public Pair (T t, U u) {
- this.t = t;
- this.u = u;
- }
- }
-
- public static Pair<Set<String>, List<String>> checkRoleAndScope(List<Object> userRoles) {
- Set<String> scopes;
- List<String> roles;
- //Check if the Role and Scope Size are Null get the values from db.
- roles = new ArrayList<>();
- scopes = new HashSet<>();
- for(Object role: userRoles){
- Roles userRole = (Roles) role;
- roles.add(userRole.getRole());
- if(userRole.getScope() != null){
- if(userRole.getScope().contains(",")){
- String[] multipleScopes = userRole.getScope().split(",");
- for(int i =0; i < multipleScopes.length; i++){
- scopes.add(multipleScopes[i]);
- }
- }else{
- scopes.add(userRole.getScope());
- }
- }
- }
- return new Pair<>(scopes, roles);
- }
+
+ private UserUtils() {
+ // Empty Constructor
+ }
+
+ public static class Pair<T, U> {
+ public final T t;
+ public final U u;
+
+ public Pair(T t, U u) {
+ this.t = t;
+ this.u = u;
+ }
+ }
+
+ /**
+ * Check Role and its Scopes.
+ *
+ * @param userRoles list of UserRoles.
+ * @return return role and scope from UserRole Object.
+ */
+ public static Pair<Set<String>, List<String>> checkRoleAndScope(List<Object> userRoles) {
+ Set<String> scopes;
+ List<String> roles;
+ // Check if the Role and Scope Size are Null get the values from db.
+ roles = new ArrayList<>();
+ scopes = new HashSet<>();
+ for (Object role : userRoles) {
+ Roles userRole = (Roles) role;
+ roles.add(userRole.getRole());
+ if (userRole.getScope() != null) {
+ if (userRole.getScope().contains(",")) {
+ String[] multipleScopes = userRole.getScope().split(",");
+ for (int i = 0; i < multipleScopes.length; i++) {
+ scopes.add(trimScope(multipleScopes[i]));
+ }
+ } else {
+ scopes.add(trimScope(userRole.getScope()));
+ }
+ }
+ }
+ return new Pair<>(scopes, roles);
+ }
+
+ /**
+ * Get Role by Scope based on UserRole Object.
+ *
+ * @param userRoles list of UserRoles.
+ * @return return the map<scope, role>.
+ */
+ public static Map<String, String> getRoleByScope(List<Object> userRoles) {
+ Map<String, String> rolesList = new HashMap<>();
+ for (Object role : userRoles) {
+ Roles userRole = (Roles) role;
+ if (!userRole.getRole().startsWith("super-")) {
+ rolesList = addNonSuperUserScopes(userRole, rolesList);
+ } else {
+ rolesList.put("@All@", userRole.getRole());
+ }
+ }
+ return rolesList;
+ }
+
+ /**
+ * Read non super role scopes and add to map.
+ *
+ * @param userRole Role Object.
+ * @param rolesList roleList Object.
+ * @return return the map<scope, role>.
+ */
+ private static Map<String, String> addNonSuperUserScopes(Roles userRole, Map<String, String> rolesList) {
+ if (userRole.getScope() != null && !(userRole.getScope().trim().isEmpty())) {
+ if (userRole.getScope().contains(",")) {
+ String[] multipleScopes = userRole.getScope().split(",");
+ for (int i = 0; i < multipleScopes.length; i++) {
+ rolesList.put(trimScope(multipleScopes[i]), userRole.getRole());
+ }
+ } else {
+ rolesList.put(trimScope(userRole.getScope()), userRole.getRole());
+ }
+ }
+ return rolesList;
+ }
+
+ /**
+ * Trim Scope Value.
+ *
+ * @param scope string scope name.
+ * @return trim scope.
+ */
+ private static String trimScope(String scope) {
+ return scope.replace("[", "").replace("]", "").replace("\"", "").trim();
+ }
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Edit_Roles_Window.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Edit_Roles_Window.html
index 7974d4e3f..6b23e3280 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Edit_Roles_Window.html
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/Edit_Roles_Window.html
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,38 +17,88 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/-->
+ <style>
+ @import "bourbon";
+
+$melon: #F97D75;
+$black: #2E3641;
+
+roleul {
+ list-style: none;
+ padding-left: 0;
+ margin-top: 25px;
+}
+
+roleli {
+ border: 1px solid black;
+ display: inline-block;
+ padding: 5px 10px;
+ margin-right: 5px;
+ margin-bottom: 5px;
+ text-transform: capitalize;
+}
+
+.fa-close {
+ cursor: pointer;
+}
+
+[contenteditable] {
+ &:focus, &:active {
+ outline:0;
+ }
+}
+ </style>
+
+
<script type="text/ng-template" id="edit_Role_popup.html">
<div class="modal" tabindex="-1">
<div class="modal-dialog modal-lg">
- <div class="modal-content">
- <div class="modal-header">
- <h2 class="font-showcase-font-name" style="color : #157bb2">{{label}}</h2>
- </div>
- <div class="modal-body">
- <div class="form-group row">
- <div class="form-group col-sm-6">
- <label><sup><b>*</b></sup>Name:</label><br>
- <input type="text" class="form-control" ng-readonly="true" ng-model="editRole.loginId.userName" maxlength="30" />
- </div>
- </div>
- <div class="form-group row">
- <div class="form-group col-sm-6" >
- <label><sup><b>*</b></sup>Role:</label><br>
- <input type="text" class="form-control" ng-readonly="true" ng-model="editRole.role" maxlength="30" />
- </div>
- </div>
- <div class="form-group row">
- <div class="form-group col-sm-6" >
- <label><sup><b>*</b></sup>Scope:</label><br>
- <select class="form-control" multiple ng-model="editRole.scope" ng-options="option for option in scopeDatas" title="Select the Scopes from the dropdown."></select>
- </div>
- </div>
- </div>
- <div class="modal-footer">
- <button class="btn btn-success" herf="javascript:void(0)" ng-click="saveRole(editRole);" title="OnClick Policy Role is saved.">Save</button>
- <button class="btn btn-default" herf="javascript:void(0)" ng-click="close()" title="OnClick Policy Role Window is closed.">Close</button>
- </div>
- </div>
+ <div class="modal-content">
+ <div class="modal-header">
+ <h2 class="font-showcase-font-name" style="color : #157bb2">{{label}}</h2>
+ </div>
+ <div class="modal-body">
+ <div class="form-group row">
+ <div class="form-group col-sm-6">
+ <label><sup><b>*</b></sup>Name:</label><br>
+ <input type="text" class="form-control" ng-readonly="disableCd" ng-model="editRole.loginId.userName" maxlength="256" />
+ </div>
+ </div>
+ <div class="form-group row">
+ <div class="form-group col-sm-6" >
+ <label><sup><b>*</b></sup>Role:</label><br>
+ <input type="text" class="form-control" ng-readonly="true" ng-model="editRole.role" maxlength="30" />
+ </div>
+ </div>
+ <div class="form-group row">
+ <div class="form-group col-sm-12" >
+ <label><sup><b>*</b></sup>Assigned Scopes:</label><br>
+ <roleul>
+ <roleli ng-model="editRole.scope" ng-repeat="option in activeScopes" class="{'fadeOut' : option}">
+ <span class="fa fa-close" ng-click="deleteScope($index)"></span>
+ <span>{{option}}</span>
+ </roleli>
+ </roleul>
+ </div>
+ </div>
+ <div class="form-group row">
+ <div class="form-group col-sm-12" >
+ <label><sup><b>*</b></sup>Scope: To Multi Select Scopes press ctrl (Windows) and cmd (Mac) and then select.</label><br>
+ <input type="text" class="form-control" ng-model="searchKey" placeholder="Filter Scopes.." title="Enter Scope name."><br>
+ <select class="form-control" multiple style="height: 400px;" ng-model="editRole.scopeList" ng-options="option for option in scopeDatas | filter: searchKey" title="Select the Scopes from the dropdown."></select>
+ </div>
+ </div>
+ <div class="form-group row">
+ <div class="form-group col-sm-12" >
+ <button class="btn btn-primary" ng-click="addScope(editRole.scopeList);" title="On Click Scopes added to Active Scope List">Add Scopes</button>
+ </div>
+ </div>
+ </div>
+ <div class="modal-footer">
+ <button class="btn btn-success" herf="javascript:void(0)" ng-click="saveRole(editRole);" title="OnClick Policy Role is saved.">Save</button>
+ <button class="btn btn-default" herf="javascript:void(0)" ng-click="$close()" title="OnClick Policy Role Window is closed.">Close</button>
+ </div>
+ </div>
</div>
</div>
</script> \ No newline at end of file
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/PolicyAddScopeRoleController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/PolicyAddScopeRoleController.js
index 42760a222..051a9130c 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/PolicyAddScopeRoleController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/PolicyAddScopeRoleController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,12 +18,28 @@
* ============LICENSE_END=========================================================
*/
app.controller('editRoleController' , function ($scope, PolicyAppService, $modalInstance, message){
- if(message.editRoleData!=null){
+ if (message.editRoleData != null) {
$scope.label='Edit Role'
$scope.disableCd=true;
+ } else {
+ $scope.label='Add Role'
+ $scope.disableCd=false;
+ message.editRoleData = {
+ role : "mechid"
+ }
}
+
$scope.editRole = message.editRoleData;
+ $scope.activeScopes = [];
+ if (message.editRoleData != null && message.editRoleData.scope != null) {
+ if (message.editRoleData.scope.constructor === Array) {
+ $scope.activeScopes = message.editRoleData.scope;
+ } else {
+ $scope.activeScopes = message.editRoleData.scope.split(',');
+ }
+ }
+
PolicyAppService.getData('get_PolicyRolesScopeData').then(function (data) {
var j = data;
$scope.data = JSON.parse(j.data);
@@ -36,6 +52,7 @@ app.controller('editRoleController' , function ($scope, PolicyAppService, $moda
$scope.saveRole = function(editRoleData) {
var uuu = "save_NonSuperRolesData.htm";
+ editRoleData.scope = $scope.activeScopes;
var postData={editRoleData: editRoleData};
$.ajax({
type : 'POST',
@@ -55,7 +72,39 @@ app.controller('editRoleController' , function ($scope, PolicyAppService, $moda
});
};
- $scope.close = function() {
- $modalInstance.close();
+
+ $scope.createMechidScope = function(editRoleData) {
+ var uuu = "save_NewMechidScopesData";
+ editRoleData.scope = $scope.activeScopes;
+ var postData={editRoleData: editRoleData};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.rolesDatas=data.rolesDatas;});
+ console.log($scope.rolesDatas);
+ $modalInstance.close({rolesDatas:$scope.rolesDatas});
+ },
+ error : function(data) {
+ alert("Error while Creating Mechid scopes.");
+ }
+ });
+ };
+
+
+
+ $scope.addScope = function(scopes) {
+ for (var i = 0; i < scopes.length; i++) {
+ if ($.inArray(scopes[i], $scope.activeScopes) === -1) {
+ $scope.activeScopes.push(scopes[i]);
+ }
+ }
+ };
+ $scope.deleteScope = function(index) {
+ $scope.activeScopes.splice(index, 1);
};
}); \ No newline at end of file
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/PolicyRolesController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/PolicyRolesController.js
index ddd6b232c..ed1b8bd23 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/PolicyRolesController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/PolicyRolesController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,23 +19,23 @@
*/
app.controller('policyRolesController', function ($scope, PolicyAppService, modalService, $modal, Notification){
$( "#dialog" ).hide();
-
+
$scope.isDisabled = true;
+
+ PolicyAppService.getData('get_LockDownData').then(function(data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.lockdowndata = JSON.parse($scope.data.lockdowndata);
+ if ($scope.lockdowndata[0].lockdown == true) {
+ $scope.isDisabled = true;
+ } else {
+ $scope.isDisabled = false;
+ }
+ console.log($scope.data);
+ }, function(error) {
+ console.log("failed");
+ });
- PolicyAppService.getData('get_LockDownData').then(function(data){
- var j = data;
- $scope.data = JSON.parse(j.data);
- $scope.lockdowndata = JSON.parse($scope.data.lockdowndata);
- if($scope.lockdowndata[0].lockdown == true){
- $scope.isDisabled = true;
- }else{
- $scope.isDisabled = false;
- }
- console.log($scope.data);
- },function(error){
- console.log("failed");
- });
-
$scope.scopeDatas = [];
PolicyAppService.getData('get_RolesData').then(function (data) {
var j = data;
@@ -51,7 +51,8 @@ app.controller('policyRolesController', function ($scope, PolicyAppService, moda
data : 'rolesDatas',
enableFiltering: true,
columnDefs: [{
- field: 'id', enableFiltering: false,
+ field: 'id', enableFiltering: false, headerCellTemplate: '' +
+ '<button id=\'New\' ng-click="grid.appScope.editRolesWindow(null)" class="btn btn-success">' + 'Create</button>',
cellTemplate:
'<button type="button" class="btn btn-primary" ng-click="grid.appScope.editRolesWindow(row.entity)"><i class="fa fa-pencil-square-o"></i></button>' , width: '4%'
},
@@ -63,30 +64,30 @@ app.controller('policyRolesController', function ($scope, PolicyAppService, moda
$scope.editRoleName = null;
-
+
$scope.editRolesWindow = function(editRoleData) {
- if($scope.lockdowndata[0].lockdown == true){
- Notification.error("Policy Application has been Locked")
- }else{
- $scope.editRoleName = editRoleData;
- var modalInstance = $modal.open({
- backdrop: 'static', keyboard: false,
- templateUrl : 'edit_Role_popup.html',
- controller: 'editRoleController',
- resolve: {
- message: function () {
- var message = {
- editRoleData: $scope.editRoleName
- };
- return message;
- }
- }
- });
- modalInstance.result.then(function(response){
- console.log('response', response);
- });
- }
-
+ if ($scope.lockdowndata[0].lockdown == true) {
+ Notification.error("Policy Application has been Locked")
+ } else {
+ $scope.editRoleName = editRoleData;
+ var modalInstance = $modal.open({
+ backdrop: 'static', keyboard: false,
+ templateUrl : 'edit_Role_popup.html',
+ controller: 'editRoleController',
+ resolve: {
+ message: function () {
+ var message = {
+ editRoleData: $scope.editRoleName
+ };
+ return message;
+ }
+ }
+ });
+ modalInstance.result.then(function(response) {
+ console.log('response', response);
+ $scope.rolesDatas = response.rolesDatas;
+ });
+ }
};
}); \ No newline at end of file
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policyManager.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policyManager.js
index 7568030cf..0aec30c1d 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policyManager.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policyManager.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,7 +20,7 @@
app.controller('PolicyManagerController', [
'$scope', '$q', '$window', '$cookies', 'policyManagerConfig', 'item', 'policyNavigator', 'policyUploader', 'Notification','PolicyAppService',
function($scope, $q, $Window, $cookies, policyManagerConfig, Item, PolicyNavigator, PolicyUploader, Notification, PolicyAppService ) {
-
+
$scope.isDisabled = true;
$scope.superAdminId = false;
$scope.exportPolicyId = false;
@@ -35,109 +35,75 @@ app.controller('PolicyManagerController', [
$scope.describePolicyId = false;
$scope.viewPolicyId = false;
$scope.deletePolicyId = false;
- PolicyAppService.getData('get_LockDownData').then(function(data){
- var j = data;
- $scope.data = JSON.parse(j.data);
- $scope.lockdowndata = JSON.parse($scope.data.lockdowndata);
- if($scope.lockdowndata[0].lockdown == true){
- $scope.isDisabled = true;
- }else{
- $scope.isDisabled = false;
- }
- console.log($scope.data);
- },function(error){
- console.log("failed");
+ PolicyAppService.getData('get_LockDownData').then(function(data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.lockdowndata = JSON.parse($scope.data.lockdowndata);
+ if ($scope.lockdowndata[0].lockdown == true) {
+ $scope.isDisabled = true;
+ } else {
+ $scope.isDisabled = false;
+ }
+ console.log($scope.data);
+ }, function(error) {
+ console.log("failed");
});
-
- PolicyAppService.getData('getDictionary/get_DescriptiveScopeByName').then(function(data){
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.descriptiveScopeDictionaryDatas = JSON.parse($scope.data.descriptiveScopeDictionaryDatas);
+
+ PolicyAppService.getData('getDictionary/get_DescriptiveScopeByName').then(function(data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ console.log($scope.data);
+ $scope.descriptiveScopeDictionaryDatas = JSON.parse($scope.data.descriptiveScopeDictionaryDatas);
}, function (error) {
- console.log("failed");
+ console.log("failed");
});
- PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function(data){
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
+ PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function(data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ console.log($scope.data);
+ $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
}, function (error) {
console.log("failed");
});
- PolicyAppService.getData('getDictionary/get_VSCLActionDataByName').then(function(data){
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.vsclActionDictionaryDatas = JSON.parse($scope.data.vsclActionDictionaryDatas);
+ PolicyAppService.getData('getDictionary/get_VSCLActionDataByName').then(function(data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ console.log($scope.data);
+ $scope.vsclActionDictionaryDatas = JSON.parse($scope.data.vsclActionDictionaryDatas);
}, function (error) {
- console.log("failed");
+ console.log("failed");
});
- PolicyAppService.getData('getDictionary/get_VNFTypeDataByName').then(function(data){
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.vnfTypeDictionaryDatas = JSON.parse($scope.data.vnfTypeDictionaryDatas);
+ PolicyAppService.getData('getDictionary/get_VNFTypeDataByName').then(function(data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ console.log($scope.data);
+ $scope.vnfTypeDictionaryDatas = JSON.parse($scope.data.vnfTypeDictionaryDatas);
}, function (error) {
- console.log("failed");
+ console.log("failed");
});
-
+
PolicyAppService.getData('get_UserRolesData').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.userRolesDatas = JSON.parse($scope.data.userRolesDatas);
- console.log($scope.userRolesDatas);
- if($scope.userRolesDatas[0] == 'super-admin'){
- $scope.superAdminId = true;
- $scope.exportPolicyId = true;
- $scope.importPolicyId = true;
- $scope.createScopeId = true;
- $scope.deleteScopeId = true;
- $scope.renameId = true;
- $scope.createPolicyId = true;
- $scope.cloneId = true;
- $scope.editPolicyId = true;
- $scope.switchVersionId = true;
- $scope.describePolicyId = true;
- $scope.viewPolicyId = true;
- $scope.deletePolicyId = true;
- }else if($scope.userRolesDatas[0] == 'super-editor' || $scope.userRolesDatas[0] == 'editor'){
- $scope.exportPolicyId = true;
- $scope.importPolicyId = true;
- $scope.cloneId = true;
- $scope.editPolicyId = true;
- $scope.createPolicyId = true;
- $scope.cloneId = true;
- $scope.editPolicyId = true;
- $scope.switchVersionId = true;
- $scope.describePolicyId = true;
- $scope.viewPolicyId = true;
- $scope.deletePolicyId = true;
- }else if($scope.userRolesDatas[0] == 'super-guest' || $scope.userRolesDatas[0] == 'guest'){
- $scope.describePolicyId = true;
- $scope.viewPolicyId = true;
- }else if($scope.userRolesDatas[0] == 'admin'){
- $scope.exportPolicyId = true;
- $scope.importPolicyId = true;
- $scope.createScopeId = true;
- $scope.renameId = true;
- $scope.createPolicyId = true;
- $scope.cloneId = true;
- $scope.editPolicyId = true;
- $scope.switchVersionId = true;
- $scope.describePolicyId = true;
- $scope.viewPolicyId = true;
- $scope.deletePolicyId = true;
- }
- }, function (error) {
- console.log("failed");
- });
-
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ console.log($scope.data);
+ $scope.userRolesDatas = JSON.parse($scope.data.userRolesDatas);
+ console.log($scope.userRolesDatas);
+ if ($scope.userRolesDatas[0] == 'super-admin') {
+ $scope.superAdminId = true;
+ $scope.exportPolicyId = true;
+ $scope.importPolicyId = true;
+ } else if ($scope.userRolesDatas[0] == 'super-editor' || $scope.userRolesDatas[0] == 'editor' || $scope.userRolesDatas[0] == 'admin') {
+ $scope.exportPolicyId = true;
+ $scope.importPolicyId = true;
+ }
+ }, function (error) {
+ console.log("failed");
+ });
+
$scope.config = policyManagerConfig;
$scope.reverse = false;
$scope.predicate = ['model.type', 'model.name'];
@@ -160,6 +126,49 @@ app.controller('PolicyManagerController', [
item = item instanceof Item ? item : new Item();
item.revert();
$scope.temp = item;
+ $scope.createScopeId = false;
+ $scope.deleteScopeId = false;
+ $scope.renameId = false;
+ $scope.createPolicyId = false;
+ $scope.cloneId = false;
+ $scope.editPolicyId = false;
+ $scope.switchVersionId = false;
+ $scope.describePolicyId = false;
+ $scope.viewPolicyId = false;
+ $scope.deletePolicyId = false;
+ if ($scope.temp.model.roleType == 'super-admin') {
+ $scope.createScopeId = true;
+ $scope.deleteScopeId = true;
+ $scope.renameId = true;
+ $scope.createPolicyId = true;
+ $scope.cloneId = true;
+ $scope.editPolicyId = true;
+ $scope.switchVersionId = true;
+ $scope.describePolicyId = true;
+ $scope.viewPolicyId = true;
+ $scope.deletePolicyId = true;
+ } else if ($scope.temp.model.roleType == 'super-editor' || $scope.temp.model.roleType == 'editor') {
+ $scope.cloneId = true;
+ $scope.editPolicyId = true;
+ $scope.createPolicyId = true;
+ $scope.switchVersionId = true;
+ $scope.describePolicyId = true;
+ $scope.viewPolicyId = true;
+ $scope.deletePolicyId = true;
+ } else if ($scope.temp.model.roleType == 'super-guest' || $scope.temp.model.roleType == 'guest') {
+ $scope.describePolicyId = true;
+ $scope.viewPolicyId = true;
+ } else if ($scope.temp.model.roleType == 'admin') {
+ $scope.createScopeId = true;
+ $scope.renameId = true;
+ $scope.createPolicyId = true;
+ $scope.cloneId = true;
+ $scope.editPolicyId = true;
+ $scope.switchVersionId = true;
+ $scope.describePolicyId = true;
+ $scope.viewPolicyId = true;
+ $scope.deletePolicyId = true;
+ }
};
$scope.smartClick = function(item) {
@@ -186,10 +195,10 @@ app.controller('PolicyManagerController', [
return currentPath.indexOf(path) !== -1;
};
- $scope.watchPolicy = function(item){
+ $scope.watchPolicy = function(item) {
var uuu = "watchPolicy";
var data = {name : item.model.name,
- path : item.model.path};
+ path : item.model.path};
var postData={watchData: data};
$.ajax({
type : 'POST',
@@ -197,32 +206,31 @@ app.controller('PolicyManagerController', [
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
+ success : function(data) {
+ $scope.$apply(function() {
$scope.watchData=data.watchData;});
Notification.success($scope.watchData);
console.log($scope.watchData);
},
- error : function(data){
+ error : function(data) {
alert("Error while saving.");
}
});
};
-
-
- $scope.refresh = function(){
- $scope.policyNavigator.refresh();
+
+ $scope.refresh = function() {
+ $scope.policyNavigator.refresh();
};
-
- $scope.switchVersion = function(item){
- if ($scope.policyNavigator.fileNameExists(item.tempModel.content.activeVersion)) {
+
+ $scope.switchVersion = function(item) {
+ if ($scope.policyNavigator.fileNameExists(item.tempModel.content.activeVersion)) {
item.error = 'Invalid filename or already exists, specify another name';
return false;
}
- item.getSwitchVersionContent().then(function(){
- $scope.policyNavigator.refresh();
- $scope.modal('switchVersion', true);
- });
+ item.getSwitchVersionContent().then(function(){
+ $scope.policyNavigator.refresh();
+ $scope.modal('switchVersion', true);
+ });
};
$scope.copy = function(item) {
@@ -250,7 +258,7 @@ app.controller('PolicyManagerController', [
$scope.modal('deletePolicy', true);
});
};
-
+
$scope.rename = function(item) {
var samePath = item.tempModel.path.join() === item.model.path.join();
if (samePath && $scope.policyNavigator.fileNameExists(item.tempModel.name)) {
@@ -262,7 +270,7 @@ app.controller('PolicyManagerController', [
$scope.modal('rename', true);
});
};
-
+
$scope.move = function(item) {
var samePath = item.tempModel.path.join() === item.model.path.join();
if (samePath && $scope.policyNavigator.fileNameExists(item.tempModel.name)) {
@@ -291,22 +299,22 @@ app.controller('PolicyManagerController', [
};
$scope.subScopeFolder = function(item) {
- var name = item.tempModel.name +"\\" + item.tempModel.subScopename && item.tempModel.name.trim() + "\\"+item.tempModel.subScopename.trim() ;
- item.tempModel.type = 'dir';
- item.tempModel.path = $scope.policyNavigator.currentPath;
- if (name && !$scope.policyNavigator.fileNameExists(name)) {
- item.getScopeContent().then(function() {
- $scope.policyNavigator.refresh();
- $scope.modal('addSubScope', true);
- });
- } else {
- item.error = 'Invalid filename or already exists, specify another name';
- return false;
- }
+ var name = item.tempModel.name +"\\" + item.tempModel.subScopename && item.tempModel.name.trim() + "\\"+item.tempModel.subScopename.trim() ;
+ item.tempModel.type = 'dir';
+ item.tempModel.path = $scope.policyNavigator.currentPath;
+ if (name && !$scope.policyNavigator.fileNameExists(name)) {
+ item.getScopeContent().then(function() {
+ $scope.policyNavigator.refresh();
+ $scope.modal('addSubScope', true);
+ });
+ } else {
+ item.error = 'Invalid filename or already exists, specify another name';
+ return false;
+ }
};
-
- $scope.closefunction = function(fianlPath){
- $scope.policyNavigator.policyrefresh(fianlPath);
+
+ $scope.closefunction = function(fianlPath) {
+ $scope.policyNavigator.policyrefresh(fianlPath);
};
$scope.uploadFiles = function() {
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/entities/item.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/entities/item.js
index 0e095a841..26cdf67c3 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/entities/item.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/entities/item.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -30,6 +30,7 @@ angular.module('abs').factory('item', ['$http', '$q', 'policyManagerConfig', fun
version: model && model.version || '',
createdBy: model && model.createdBy || '',
modifiedBy: model && model.modifiedBy || '',
+ roleType: model && model.roleType || '',
content: model && model.content || '',
recursive: false,
sizeKb: function() {
@@ -84,7 +85,7 @@ angular.module('abs').factory('item', ['$http', '$q', 'policyManagerConfig', fun
this.update();
return deferred.resolve(data);
};
-
+
Item.prototype.createFolder = function() {
var self = this;
var deferred = $q.defer();
@@ -139,11 +140,11 @@ angular.module('abs').factory('item', ['$http', '$q', 'policyManagerConfig', fun
self.inprocess = true;
self.error = '';
$http.post(policyManagerConfig.renameUrl, data).success(function(data) {
- if(data.result.error != undefined){
- var value = data.result.error;
- value = value.replace("rename" , "move");
- data.result.error = value;
- }
+ if(data.result.error != undefined){
+ var value = data.result.error;
+ value = value.replace("rename" , "move");
+ data.result.error = value;
+ }
self.deferredHandler(data, deferred);
}).error(function(data) {
self.deferredHandler(data, deferred, 'Error Occured While Moving');
@@ -152,7 +153,7 @@ angular.module('abs').factory('item', ['$http', '$q', 'policyManagerConfig', fun
});
return deferred.promise;
};
-
+
Item.prototype.copy = function() {
var self = this;
var deferred = $q.defer();
@@ -249,7 +250,7 @@ angular.module('abs').factory('item', ['$http', '$q', 'policyManagerConfig', fun
});
return deferred.promise;
};
-
+
Item.prototype.getDescribePolicyContent = function() {
var self = this;
var deferred = $q.defer();
@@ -263,7 +264,7 @@ angular.module('abs').factory('item', ['$http', '$q', 'policyManagerConfig', fun
$http.post(policyManagerConfig.describePolicyUrl, data).success(function(data) {
self.tempModel.content = self.model.content = data.html;
var describeTemplate = self.tempModel.content;
-
+
self.deferredHandler(data, deferred);
}).error(function(data) {
self.deferredHandler(data, deferred, 'Error Occured While retrieving the Policy Data to Describe');
@@ -315,7 +316,7 @@ angular.module('abs').factory('item', ['$http', '$q', 'policyManagerConfig', fun
});
return deferred.promise;
};
-
+
Item.prototype.removePolicy = function() {
var self = this;
var deferred = $q.defer();
diff --git a/packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties b/packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties
index 315fb4d67..8835fe45d 100644
--- a/packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties
+++ b/packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties
@@ -2,7 +2,7 @@
# ============LICENSE_START=======================================================
# ONAP Policy Engine
# ================================================================================
-# Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+# Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
# ================================================================================
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -164,3 +164,5 @@ gui_url=https://${{AAF_HOST}}:8095/AAF_NS.gui.2.1
# Decision Response settings.
# can be either PERMIT or DENY.
decision.indeterminate.response=${{DECISION_INDETERMINATE_RESPONSE}}
+
+msToscaModel.home=${{REST_PDP_WEBAPPS}} \ No newline at end of file