aboutsummaryrefslogtreecommitdiffstats
path: root/POLICY-SDK-APP/src/main
diff options
context:
space:
mode:
Diffstat (limited to 'POLICY-SDK-APP/src/main')
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPdpProperties.java (renamed from POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java)58
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java49
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java442
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java145
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java158
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java20
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java190
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java377
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/conf/HibernateSession.java67
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java250
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java71
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java117
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java289
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java117
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java255
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java151
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java711
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java1726
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateOptimizationController.java383
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java203
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java182
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java528
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntries.java44
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java732
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java165
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java167
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java169
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java109
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java70
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/dao/SystemLogDbDao.java12
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java662
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/SystemLogDbDaoImpl.java126
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java80
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/model/Roles.java131
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/utils/UserUtils.java25
-rw-r--r--POLICY-SDK-APP/src/main/webapp/WEB-INF/conf/system.properties4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/dist/js/bootstrap-modalmanager.min.js341
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/AutoPushController.js135
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/AutoPushTabController/RemovePDPGroupPoliciesController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/PolicyAddScopeRoleController.js6
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dashboardCRUDController.js185
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSControllerDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSDependencyDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSParamDictController.js5
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLPepOptionsDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLServiceDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLSiteDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVarbindDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVnfTypeDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVsclActionDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DecisionRainyDayDictController.js14
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DecisionSettingsDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DescriptiveSearchDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/EnforcerDictController.js22
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWActionListDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWAddressGroupDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWParentListDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWPortListDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWPrefixListDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWProtocolListDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWSecurityZoneDictController.js72
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWServiceGroupDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWServiceListDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTagListDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTagPickerListDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTermListDictController.js28
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWZoneDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSConfigNameDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSDcaeUUIDDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSDictionaryController.js2
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSHeaderDefaultValuesDictController.js195
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSLocationDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/ModelAttributeDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSClosedLoopDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSGroupPolicyScopeDictController.js156
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSResourceDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSServiceDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSTypeDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/RiskTypeDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/SafePolicyWarningDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/actionPolicyDictController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/attributeDictController.js7
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/onapNameEditorController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/BRMSParamDictGridController.js6
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLPepOptionsDictGridController.js6
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLServiceDictGridController.js6
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLSiteDictGridController.js6
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVarbindDictGridController.js4
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVnfTypeDictGridController.js6
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVsclActionDictGridController.js6
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/MSHeaderDefaultValuesDictGridController.js27
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/attributeDictGridController.js6
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/onapNameDictGridController.js8
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/policyAdminTabController.js84
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/main/modalPopupController.js22
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/main/policyEditor.html529
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ActionPolicyController.js15
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSParamPolicyController.js233
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSRawPolicyController.js218
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BaseConfigPolicyController.js6
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopFaultController.js1521
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopPMController.js6
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DCAEMicroServicePolicyController.js3126
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DecisionPolicyController.js848
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/FirewallPolicyController.js270
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/OptimizationPolicyController.js2370
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policyManager.js576
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policySearchManager.js330
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/entities/item.js5
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/service/modalService.js12
110 files changed, 10172 insertions, 10369 deletions
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/CheckPdpProperties.java
index 26b9798ac..925344191 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/CheckPdpProperties.java
@@ -22,8 +22,8 @@
package org.onap.policy.admin;
-
import com.att.research.xacml.util.XACMLProperties;
+
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -39,9 +39,10 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
+
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
-import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.utils.PeCryptoUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
@@ -50,20 +51,20 @@ import org.onap.policy.xacml.api.XACMLErrorConstants;
* 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.
+ * <p>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.
+ * <p>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 {
+public class CheckPdpProperties {
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 static final Logger LOGGER = FlexLogger.getLogger(CheckPdpProperties.class);
- private CheckPDP() {
- //default constructor
+ private CheckPdpProperties() {
+ // default constructor
}
public static Map<String, String> getPdpMap() {
@@ -76,7 +77,13 @@ public class CheckPDP {
pdpMap = null;
}
- public static boolean validateID(String id) {
+ /**
+ * validateId - validates that the ID is in the properties.
+ *
+ * @param id Input ID
+ * @return true it is in the properties
+ */
+ public static boolean validateId(String id) {
// ReadFile
try {
readFile();
@@ -94,7 +101,7 @@ public class CheckPDP {
private static void readFile() {
String pdpFile;
try {
- pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE);
+ pdpFile = XACMLProperties.getProperty(XacmlRestProperties.PROP_PDP_IDFILE);
} catch (Exception e) {
LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot read the PDP ID File" + e);
return;
@@ -104,10 +111,9 @@ public class CheckPDP {
} 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());
- CheckPDP.reset();
+ LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path : "
+ + pdpPath.toString());
+ CheckPdpProperties.reset();
return;
}
readProps();
@@ -134,18 +140,18 @@ public class CheckPDP {
List<String> sorted = new ArrayList(unsorted);
Collections.sort(sorted);
for (String propKey : sorted) {
- loadPDPProperties(propKey, pdpProp);
+ loadPdpProperties(propKey, pdpProp);
}
} catch (IOException e) {
LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
}
if (pdpMap == null || pdpMap.isEmpty()) {
LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Proceed without PDP_URLs");
- CheckPDP.reset();
+ CheckPdpProperties.reset();
}
}
- 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) {
@@ -156,14 +162,14 @@ public class CheckPDP {
int pdpCount = 0;
while (pdpCount < pdpDefault.size()) {
String pdpVal = pdpDefault.get(pdpCount);
- readPDPParam(pdpVal);
+ readPdpParam(pdpVal);
pdpCount++;
}
}
}
}
- private static void readPDPParam(String pdpVal) {
+ private static void readPdpParam(String pdpVal) {
if (pdpVal.contains(",")) {
List<String> pdpValues = new ArrayList<>(Arrays.asList(pdpVal.split("\\s*,\\s*")));
if (pdpValues.size() == 3) {
@@ -173,7 +179,7 @@ public class CheckPDP {
Base64.Encoder encoder = Base64.getEncoder();
// 0 - PDPURL
pdpMap.put(pdpValues.get(0),
- encoder.encodeToString((userID + ":" + pass).getBytes(StandardCharsets.UTF_8)));
+ encoder.encodeToString((userID + ":" + pass).getBytes(StandardCharsets.UTF_8)));
} else {
LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpValues);
}
@@ -182,6 +188,13 @@ public class CheckPDP {
}
}
+ /**
+ * getEncoding reads in the PDP properties and returns an encoding
+ * for the given pdp.
+ *
+ * @param pdpID Input PDP Id
+ * @return String encoding
+ */
public static String getEncoding(String pdpID) {
try {
readFile();
@@ -196,8 +209,7 @@ public class CheckPDP {
LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
}
return encoding;
- } else {
- return null;
}
+ 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 6aa40dacf..343a19f1a 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
@@ -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.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
* Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
@@ -22,6 +22,8 @@
package org.onap.policy.admin;
+import com.att.research.xacml.util.XACMLProperties;
+
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.controller.ActionPolicyController;
@@ -37,12 +39,16 @@ import org.onap.policy.controller.DecisionPolicyController;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
import org.onap.policy.rest.jpa.PolicyEntity;
-import com.att.research.xacml.util.XACMLProperties;
-
public class PolicyAdapter {
private static final Logger LOGGER = FlexLogger.getLogger(PolicyAdapter.class);
+ /**
+ * configure.
+ *
+ * @param policyAdapter PolicyRestAdapter object
+ * @param entity PolicyEntity object
+ */
public void configure(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
String policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf('_'));
String configPolicyName = getConfigPolicyName(policyAdapter);
@@ -63,28 +69,25 @@ public class PolicyAdapter {
}
private String getConfigPolicyName(PolicyRestAdapter policyAdapter) {
- String configPolicyName = null;
if (policyAdapter.getPolicyName().startsWith("Config_PM")) {
- configPolicyName = "ClosedLoop_PM";
+ return "ClosedLoop_PM";
} else if (policyAdapter.getPolicyName().startsWith("Config_Fault")) {
- configPolicyName = "ClosedLoop_Fault";
+ return "ClosedLoop_Fault";
} else if (policyAdapter.getPolicyName().startsWith("Config_FW")) {
- configPolicyName = "Firewall Config";
+ return "Firewall Config";
} else if (policyAdapter.getPolicyName().startsWith("Config_BRMS_Raw")) {
- configPolicyName = "BRMS_Raw";
+ return "BRMS_Raw";
} else if (policyAdapter.getPolicyName().startsWith("Config_BRMS_Param")) {
- configPolicyName = "BRMS_Param";
+ return "BRMS_Param";
} else if (policyAdapter.getPolicyName().startsWith("Config_MS")) {
- configPolicyName = "Micro Service";
+ return "Micro Service";
} else if (policyAdapter.getPolicyName().startsWith("Config_OOF")) {
- configPolicyName = "Optimization";
- } else if (policyAdapter.getPolicyName().startsWith("Action") || policyAdapter.getPolicyName()
- .startsWith("Decision")) {
- // No configPolicyName is applicable
- } else {
- configPolicyName = "Base";
+ return "Optimization";
+ } else if (policyAdapter.getPolicyName().startsWith("Action")
+ || policyAdapter.getPolicyName().startsWith("Decision")) {
+ return null;
}
- return configPolicyName;
+ return "Base";
}
private void prePopulatePolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
@@ -107,12 +110,18 @@ public class PolicyAdapter {
}
}
+ /**
+ * getInstance.
+ *
+ * @return Returns a PolicyAdapter instance
+ */
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) {
+ } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
+ | IllegalArgumentException e) {
LOGGER.error("Exception Occurred" + e);
}
return null;
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 513fc5795..a23a0e821 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,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
* Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
@@ -63,6 +63,7 @@ import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
+import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.elasticsearch.common.Strings;
import org.json.JSONArray;
@@ -73,8 +74,8 @@ import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.components.HumanPolicyComponent;
import org.onap.policy.controller.PolicyController;
import org.onap.policy.controller.PolicyExportAndImportController;
-import org.onap.policy.rest.XACMLRest;
-import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRest;
+import org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
import org.onap.policy.rest.jpa.ActionBodyEntity;
import org.onap.policy.rest.jpa.ConfigurationDataEntity;
@@ -87,11 +88,16 @@ import org.onap.policy.utils.PolicyUtils;
import org.onap.policy.utils.UserUtils.Pair;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.policy.xacml.util.XACMLPolicyScanner;
+import org.onap.portalsdk.core.domain.User;
import org.onap.portalsdk.core.web.support.UserUtils;
-
-@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 long serialVersionUID = -8453502699403909016L;
@@ -126,11 +132,13 @@ public class PolicyManagerServlet extends HttpServlet {
private static final String BACKSLASH = "\\";
private static final String ESCAPE_BACKSLASH = "\\\\";
private static final String BACKSLASH_8TIMES = "\\\\\\\\";
- private static final String DELETE_POLICY_VERSION_WHERE_POLICY_NAME = "delete from PolicyVersion where policy_name ='";
+ private static final String DELETE_POLICY_VERSION_WHERE_POLICY_NAME =
+ "delete from PolicyVersion where policy_name ='";
private static final String UPDATE_POLICY_VERSION_SET_ACTIVE_VERSION = "update PolicyVersion set active_version='";
private static final String SPLIT_1 = "split_1";
private static final String SPLIT_0 = "split_0";
- private static final String FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME = "from PolicyEditorScopes where SCOPENAME like :scopeName";
+ private static final String FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME =
+ "from PolicyEditorScopes where SCOPENAME like :scopeName";
private static final String SCOPE_NAME = "scopeName";
private static final String SUCCESS = "success";
private static final String SUB_SCOPENAME = "subScopename";
@@ -141,8 +149,18 @@ public class PolicyManagerServlet extends HttpServlet {
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;
@@ -173,17 +191,17 @@ public class PolicyManagerServlet extends HttpServlet {
//
// Common initialization
//
- XACMLRest.xacmlInit(servletConfig);
+ XacmlRest.xacmlInit(servletConfig);
// init aes key from prop or env
- PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY));
+ PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XacmlRestProperties.PROP_AES_KEY));
//
// Initialize ClosedLoop JSON
//
- PolicyManagerServlet.initializeJSONLoad();
+ PolicyManagerServlet.initializeJsonLoad();
}
- private static void initializeJSONLoad() {
- Path closedLoopJsonLocation = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP));
+ private static void initializeJsonLoad() {
+ Path closedLoopJsonLocation = Paths.get(XACMLProperties.getProperty(XacmlRestProperties.PROP_ADMIN_CLOSEDLOOP));
String location = closedLoopJsonLocation.toString();
if (!location.endsWith("json")) {
LOGGER.warn("JSONConfig file does not end with extension .json");
@@ -208,7 +226,7 @@ public class PolicyManagerServlet extends HttpServlet {
LOGGER.debug("doPost");
try {
// if request contains multipart-form-data
- if (ServletFileUpload.isMultipartContent(request)) {
+ if (isMultipartContent(request)) {
uploadFile(request, response);
}
// all other post request has json params in body
@@ -224,10 +242,14 @@ public class PolicyManagerServlet extends HttpServlet {
}
}
+ protected boolean isMultipartContent(HttpServletRequest request) {
+ return ServletFileUpload.isMultipartContent(request);
+ }
+
// Set Error Message for Exception
- private void setError(Exception t, HttpServletResponse response) throws IOException {
+ private void setError(Exception exception, HttpServletResponse response) throws IOException {
try {
- JSONObject responseJsonObject = error(t.getMessage());
+ JSONObject responseJsonObject = error(exception.getMessage());
response.setContentType(CONTENTTYPE);
PrintWriter out = response.getWriter();
out.print(responseJsonObject);
@@ -242,20 +264,24 @@ public class PolicyManagerServlet extends HttpServlet {
private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException {
try {
Map<String, InputStream> files = new HashMap<>();
-
+ String resp = null;
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
// Process form file field (input type="file").
files.put(item.getName(), item.getInputStream());
- processFormFile(request, item);
+ resp = processFormFile(request, item, response);
}
}
- JSONObject responseJsonObject;
- responseJsonObject = this.success();
response.setContentType(CONTENTTYPE);
PrintWriter out = response.getWriter();
+ JSONObject responseJsonObject;
+ if (!StringUtils.isBlank(resp)) {
+ responseJsonObject = this.error("Import Issue " + resp);
+ } else {
+ responseJsonObject = this.success();
+ }
out.print(responseJsonObject);
out.flush();
} catch (Exception e) {
@@ -264,23 +290,35 @@ public class PolicyManagerServlet extends HttpServlet {
}
}
- private void processFormFile(HttpServletRequest request, FileItem item) {
+ private String processFormFile(HttpServletRequest request, FileItem item, HttpServletResponse response) {
String newFile;
- if (item.getName().endsWith(".xls") && item.getSize() <= PolicyController.getFileSizeLimit()) {
+ String outPutResp = null;
+ if (item.getName().endsWith(".xls") && item.getSize() <= getFileSizeLimit()) {
File file = new File(item.getName());
try (OutputStream outputStream = new FileOutputStream(file)) {
IOUtils.copy(item.getInputStream(), outputStream);
newFile = file.toString();
PolicyExportAndImportController importController = new PolicyExportAndImportController();
- importController.importRepositoryFile(newFile, request);
+ return importController.importRepositoryFile(newFile, request);
} catch (Exception e) {
LOGGER.error("Upload error : " + e);
}
} else if (!item.getName().endsWith(".xls")) {
- LOGGER.error("Non .xls filetype uploaded: " + item.getName());
+ outPutResp = "Non .xls filetype uploaded: " + item.getName();
+ LOGGER.error(outPutResp);
} else { // uploaded file size is greater than allowed
- LOGGER.error("Upload file size limit exceeded! File size (Bytes) is: " + item.getSize());
+ outPutResp = "Upload file size limit exceeded! File size (Bytes) is: " + item.getSize();
+ LOGGER.error(outPutResp);
}
+ return outPutResp;
+ }
+
+ protected long copyStream(InputStream inputStream, OutputStream outputStream) throws IOException {
+ return IOUtils.copy(inputStream, outputStream);
+ }
+
+ protected long getFileSizeLimit() {
+ return PolicyController.getFileSizeLimit();
}
// File Operation Functionality
@@ -299,17 +337,17 @@ public class PolicyManagerServlet extends HttpServlet {
return;
}
try {
- JSONObject jObj = new JSONObject(sb.toString());
- JSONObject params = jObj.getJSONObject("params");
+ JSONObject jsonObject = new JSONObject(sb.toString());
+ JSONObject params = jsonObject.getJSONObject("params");
Mode mode = Mode.valueOf(params.getString("mode"));
- String userId = UserUtils.getUserSession(request).getOrgUserId();
+ String userId = getUserSession(request).getOrgUserId();
LOGGER.info(
- "****************************************Logging UserID while doing actions on Editor tab*******************************************");
+ "********************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);
@@ -318,6 +356,10 @@ public class PolicyManagerServlet extends HttpServlet {
setResponse(response, responseJsonObject);
}
+ protected User getUserSession(HttpServletRequest request) {
+ return UserUtils.getUserSession(request);
+ }
+
private void setResponse(HttpServletResponse response, JSONObject responseJsonObject) {
response.setContentType(CONTENTTYPE);
try (PrintWriter out = response.getWriter()) {
@@ -371,7 +413,6 @@ public class PolicyManagerServlet extends HttpServlet {
}
private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) {
- List<Object> policyData = new ArrayList<>();
JSONArray policyList = null;
if (params.has("policyList")) {
policyList = (JSONArray) params.get("policyList");
@@ -379,9 +420,9 @@ public class PolicyManagerServlet extends HttpServlet {
PolicyController controller = getPolicyControllerInstance();
List<JSONObject> resultList = new ArrayList<>();
try {
- if (!lookupPolicyData(request, policyData, policyList, controller, resultList))
+ if (!lookupPolicyData(request, new ArrayList<>(), 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);
@@ -392,13 +433,11 @@ public class PolicyManagerServlet extends HttpServlet {
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();
+ String userId = 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;
+ Pair<Set<String>, List<String>> pair = checkRoleAndScope(userRoles);
+ List<String> roles = pair.second;
+ Set<String> scopes = pair.first;
if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)) {
if (scopes.isEmpty()) {
return false;
@@ -415,12 +454,16 @@ public class PolicyManagerServlet extends HttpServlet {
parsePolicyList(resultList, controller, policyName, version);
}
} else {
- getPolicyDataForSUPERRoles(policyData, controller, resultList, roles, scopes);
+ getPolicyDataForSuperRoles(policyData, controller, resultList, roles, scopes);
}
return true;
}
- private void getPolicyDataForSUPERRoles(List<Object> policyData, PolicyController controller,
+ protected Pair<Set<String>, List<String>> checkRoleAndScope(List<Object> userRoles) {
+ return org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
+ }
+
+ 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);
@@ -448,8 +491,8 @@ public class PolicyManagerServlet extends HttpServlet {
}
private void updateResultList(List<Object> policyData, List<JSONObject> resultList) {
- for (Object aPolicyData : policyData) {
- PolicyVersion policy = (PolicyVersion) aPolicyData;
+ for (Object data : policyData) {
+ PolicyVersion policy = (PolicyVersion) data;
JSONObject el = new JSONObject();
el.put(NAME, policy.getPolicyName().replace(File.separator, FORWARD_SLASH));
el.put(DATE, policy.getModifiedDate());
@@ -467,7 +510,8 @@ public class PolicyManagerServlet extends HttpServlet {
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";
+ String policyVersionQuery =
+ "From PolicyVersion where policy_name = :policyName and active_version = :version and id >0";
SimpleBindings pvParams = new SimpleBindings();
pvParams.put("policyName", policyName);
pvParams.put(VERSION, version);
@@ -489,8 +533,8 @@ public class PolicyManagerServlet extends HttpServlet {
private void addScope(Set<String> scopes, String scope) {
List<Object> scopesList = queryPolicyEditorScopes(scope);
if (!scopesList.isEmpty()) {
- for (Object aScopesList : scopesList) {
- PolicyEditorScopes tempScope = (PolicyEditorScopes) aScopesList;
+ for (Object scopeItem : scopesList) {
+ PolicyEditorScopes tempScope = (PolicyEditorScopes) scopeItem;
scopes.add(tempScope.getScopeName());
}
}
@@ -501,7 +545,7 @@ public class PolicyManagerServlet extends HttpServlet {
String path = params.getString("path");
String userId = null;
try {
- userId = UserUtils.getUserSession(request).getOrgUserId();
+ userId = getUserSession(request).getOrgUserId();
} catch (Exception e) {
LOGGER.error("Exception Occured while reading userid from cookie" + e);
}
@@ -524,11 +568,11 @@ public class PolicyManagerServlet extends HttpServlet {
return error("The Version shouldn't be greater than Highest Value");
}
activePolicy = policyName + "." + activeVersion + ".xml";
- String[] splitDBCheckName = modifyPolicyName(activePolicy);
+ String[] splitDbCheckName = modifyPolicyName(activePolicy);
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]);
+ 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()) {
@@ -541,8 +585,8 @@ public class PolicyManagerServlet extends HttpServlet {
if (policyName.contains(BACKSLASH)) {
policyName = policyName.replace(File.separator, BACKSLASH);
}
- policyName = splitDBCheckName[0].replace(".", File.separator) + File.separator + policyName;
- String watchPolicyName = policyName;
+ policyName = splitDbCheckName[0].replace(".", File.separator) + File.separator + policyName;
+ final String watchPolicyName = policyName;
if (policyName.contains(FORWARD_SLASH)) {
policyName = policyName.replace(FORWARD_SLASH, File.separator);
}
@@ -564,7 +608,6 @@ public class PolicyManagerServlet extends HttpServlet {
// Describe Policy
private JSONObject describePolicy(JSONObject params) throws ServletException {
- JSONObject object;
String path = params.getString("path");
String policyName;
if (path.startsWith(FORWARD_SLASH)) {
@@ -582,13 +625,12 @@ public class PolicyManagerServlet extends HttpServlet {
} else if (path.contains(DECISION2)) {
path = path.replace(DECISION, DECISION1);
}
- PolicyController controller = getPolicyControllerInstance();
String[] split = path.split(":");
String query = "FROM PolicyEntity where policyName = :split_1 and scope = :split_0";
SimpleBindings peParams = new SimpleBindings();
peParams.put(SPLIT_1, split[1]);
peParams.put(SPLIT_0, split[0]);
- List<Object> queryData = getDataByQueryFromController(controller, query, peParams);
+ List<Object> queryData = getDataByQueryFromController(getPolicyControllerInstance(), query, peParams);
if (queryData.isEmpty()) {
return error("Error Occured while Describing the Policy - query is empty");
}
@@ -606,7 +648,7 @@ public class PolicyManagerServlet extends HttpServlet {
} catch (IOException e) {
LOGGER.error("Exception Occured while Describing the Policy" + e);
}
- object = HumanPolicyComponent.DescribePolicy(temp);
+ JSONObject object = HumanPolicyComponent.DescribePolicy(temp);
try {
Files.delete(temp.toPath());
} catch (IOException e) {
@@ -626,14 +668,13 @@ 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
String testUserID = getTestUserId();
- 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;
+ String userId = testUserID != null ? testUserID : getUserSession(request).getOrgUserId();
+ List<Object> userRoles = getPolicyControllerInstance().getRoles(userId);
+ Pair<Set<String>, List<String>> pair = checkRoleAndScope(userRoles);
+ List<String> roles = pair.second;
+ Set<String> scopes = pair.first;
Map<String, String> roleByScope = org.onap.policy.utils.UserUtils.getRoleByScope(userRoles);
List<JSONObject> resultList = new ArrayList<>();
@@ -672,39 +713,37 @@ public class PolicyManagerServlet extends HttpServlet {
Map<String, String> roleByScope) {
if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) {
List<Object> scopesList = queryPolicyEditorScopes(null);
- 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());
- el.put(SIZE, "");
- 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);
- });
+ 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());
+ el.put(SIZE, "");
+ 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);
+ });
}
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());
- el.put(SIZE, "");
- el.put(TYPE, "dir");
- el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName());
- el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName());
- if ((resultList).stream().noneMatch(item -> item.get("name").equals(scopeById.getScopeName()))) {
- el.put(ROLETYPE, roleByScope.get(scopeById.getScopeName()));
- resultList.add(el);
- }
- });
+ 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());
+ el.put(SIZE, "");
+ el.put(TYPE, "dir");
+ el.put(CREATED_BY, scopeById.getUserCreatedBy().getUserName());
+ el.put(MODIFIED_BY, scopeById.getUserModifiedBy().getUserName());
+ if ((resultList).stream()
+ .noneMatch(item -> item.get("name").equals(scopeById.getScopeName()))) {
+ el.put(ROLETYPE, roleByScope.get(scopeById.getScopeName()));
+ resultList.add(el);
+ }
+ });
}
}
@@ -724,7 +763,6 @@ public class PolicyManagerServlet extends HttpServlet {
// 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)) {
scopeName = scopeName.replace(FORWARD_SLASH, File.separator);
@@ -737,20 +775,20 @@ public class PolicyManagerServlet extends HttpServlet {
SimpleBindings params = new SimpleBindings();
params.put(SCOPE_NAME, scopeName + "%");
- List<Object> activePolicies = getDataByQueryFromController(controller, query, params);
- List<Object> scopesList = getDataByQueryFromController(controller,
- FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME, params);
+ List<Object> activePolicies = getDataByQueryFromController(getPolicyControllerInstance(), query, params);
+ List<Object> scopesList = getDataByQueryFromController(getPolicyControllerInstance(),
+ FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME, params);
for (Object list : scopesList) {
scopeName = checkScope(resultList, scopeName, (PolicyEditorScopes) list, roleByScope);
}
for (Object list : activePolicies) {
PolicyVersion policy = (PolicyVersion) list;
- String scopeNameValue = policy.getPolicyName().substring(0,
- policy.getPolicyName().lastIndexOf(File.separator));
+ 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;
+ scopeName.contains(ESCAPE_BACKSLASH) ? scopeName.replace(ESCAPE_BACKSLASH, File.separator)
+ : scopeName;
if (!scopeNameValue.equals(scopeNameCheck)) {
continue;
}
@@ -762,8 +800,8 @@ public class PolicyManagerServlet extends HttpServlet {
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);
+ 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)) {
@@ -781,7 +819,7 @@ public class PolicyManagerServlet extends HttpServlet {
}
private List<Object> getDataByQueryFromController(final PolicyController controller, final String query,
- final SimpleBindings params) {
+ final SimpleBindings params) {
final List<Object> activePolicies;
if (PolicyController.isjUnit()) {
activePolicies = controller.getDataByQuery(query, null);
@@ -828,8 +866,8 @@ public class PolicyManagerServlet extends HttpServlet {
}
private String getUserName(String loginId) {
- PolicyController controller = getPolicyControllerInstance();
- UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
+ UserInfo userInfo = (UserInfo) getPolicyControllerInstance().getEntityItem(UserInfo.class, "userLoginId",
+ loginId);
if (userInfo == null) {
return SUPERADMIN;
}
@@ -848,9 +886,9 @@ public class PolicyManagerServlet extends HttpServlet {
private JSONObject handlePolicyRename(JSONObject params, HttpServletRequest request) throws ServletException {
boolean isActive = false;
- List<String> policyActiveInPDP = new ArrayList<>();
- Set<String> scopeOfPolicyActiveInPDP = new HashSet<>();
- String userId = UserUtils.getUserSession(request).getOrgUserId();
+ List<String> policyActiveInPdp = new ArrayList<>();
+ Set<String> scopeOfPolicyActiveInPdp = new HashSet<>();
+ String userId = getUserSession(request).getOrgUserId();
String oldPath = params.getString("path");
String newPath = params.getString("newPath");
oldPath = oldPath.substring(oldPath.indexOf('/') + 1);
@@ -858,8 +896,8 @@ public class PolicyManagerServlet extends HttpServlet {
String checkValidation;
if (oldPath.endsWith(".xml")) {
checkValidation = newPath.replace(".xml", "");
- checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1,
- checkValidation.lastIndexOf('.'));
+ 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.");
@@ -888,7 +926,8 @@ public class PolicyManagerServlet extends HttpServlet {
SimpleBindings pvParams = new SimpleBindings();
pvParams.put(SCOPE_NAME, scopeName + "%");
List<Object> activePolicies = controller.getDataByQuery(query, pvParams);
- List<Object> scopesList = controller.getDataByQuery(FROM_POLICY_EDITOR_SCOPES_WHERE_SCOPENAME_LIKE_SCOPE_NAME, pvParams);
+ 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) + "."
@@ -897,19 +936,19 @@ public class PolicyManagerServlet extends HttpServlet {
JSONObject result = policyRename(policyOldPath, policyNewPath, userId);
if (!(Boolean) (result.getJSONObject("result").get(SUCCESS))) {
isActive = true;
- policyActiveInPDP.add(policyOldPath);
+ policyActiveInPdp.add(policyOldPath);
String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf('/'));
- scopeOfPolicyActiveInPDP.add(scope.replace(FORWARD_SLASH, File.separator));
+ scopeOfPolicyActiveInPdp.add(scope.replace(FORWARD_SLASH, File.separator));
}
}
- boolean rename = activePolicies.size() != policyActiveInPDP.size();
- if (policyActiveInPDP.isEmpty()) {
+ boolean rename = activePolicies.size() != policyActiveInPdp.size();
+ if (policyActiveInPdp.isEmpty()) {
renameScope(scopesList, scopeName, newScopeName, controller);
} else if (rename) {
renameScope(scopesList, scopeName, newScopeName, controller);
UserInfo userInfo = new UserInfo();
userInfo.setUserLoginId(userId);
- scopeOfPolicyActiveInPDP.forEach(scope -> {
+ scopeOfPolicyActiveInPdp.forEach(scope -> {
PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes();
editorScopeEntity.setScopeName(scope.replace(BACKSLASH, BACKSLASH_8TIMES));
editorScopeEntity.setUserCreatedBy(userInfo);
@@ -919,7 +958,7 @@ public class PolicyManagerServlet extends HttpServlet {
}
if (isActive) {
return error("The Following policies rename failed. Since they are active in PDP Groups"
- + policyActiveInPDP);
+ + policyActiveInPdp);
}
}
return success();
@@ -955,10 +994,11 @@ public class PolicyManagerServlet extends HttpServlet {
String newpolicyName = newPath.replace("/", ".");
String[] newPolicySplit = modifyPolicyName(newPath);
- String[] oldPolicySplit = modifyPolicyName(oldPath);
+ final String[] oldPolicySplit = modifyPolicyName(oldPath);
// Check PolicyEntity table with newPolicy Name
- String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
+ 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]);
@@ -969,15 +1009,15 @@ public class PolicyManagerServlet extends HttpServlet {
// Query the Policy Entity with oldPolicy Name
String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf('.'));
- String oldPolicyEntityQuery = "FROM PolicyEntity where policyName like :policyEntityCheck and scope = "
- + ":oldPolicySplit_0";
+ String oldPolicyEntityQuery =
+ "FROM PolicyEntity where policyName like :policyEntityCheck and scope = " + ":oldPolicySplit_0";
SimpleBindings params = new SimpleBindings();
params.put("policyEntityCheck", policyEntityCheck + "%");
params.put("oldPolicySplit_0", oldPolicySplit[0]);
List<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.");
+ "Policy rename failed due to policy not able to retrieve from database. Contact super-admin.");
}
StringBuilder groupQuery = new StringBuilder();
@@ -1042,10 +1082,10 @@ public class PolicyManagerServlet extends HttpServlet {
String oldPolicyNameWithoutExtension = removeOldPolicyExtension;
String newPolicyNameWithoutExtension = removeNewPolicyExtension;
if (removeOldPolicyExtension.endsWith(".xml")) {
- oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0,
- oldPolicyNameWithoutExtension.indexOf('.'));
- newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0,
- newPolicyNameWithoutExtension.indexOf('.'));
+ oldPolicyNameWithoutExtension =
+ oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf('.'));
+ newPolicyNameWithoutExtension =
+ newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf('.'));
}
entity.setPolicyName(
entity.getPolicyName().replace(oldPolicyNameWithoutExtension, newPolicyNameWithoutExtension));
@@ -1065,8 +1105,8 @@ public class PolicyManagerServlet extends HttpServlet {
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 renameFile =
+ new File(PolicyController.getConfigHome() + File.separator + newConfigurationName);
file.renameTo(renameFile);
}
} else if (newPolicyName.contains(ACTION2)) {
@@ -1078,17 +1118,17 @@ public class PolicyManagerServlet extends HttpServlet {
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 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);
+ restController.notifyOtherPapsToUpdateConfigurations("rename", newConfigurationName, oldConfigurationName);
+ PolicyVersion versionEntity =
+ (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldPolicyName);
versionEntity.setPolicyName(policyName);
versionEntity.setModifiedBy(userId);
controller.updateData(versionEntity);
@@ -1136,8 +1176,8 @@ public class PolicyManagerServlet extends HttpServlet {
.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
cloneEntity.setConfigurationData(configEntiy);
newConfigurationName = configEntiy.getConfigurationName();
- try (FileWriter fw = new FileWriter(
- PolicyController.getConfigHome() + File.separator + newConfigurationName);
+ try (FileWriter fw =
+ new FileWriter(PolicyController.getConfigHome() + File.separator + newConfigurationName);
BufferedWriter bw = new BufferedWriter(fw)) {
bw.write(configEntiy.getConfigBody());
} catch (IOException e) {
@@ -1158,8 +1198,8 @@ public class PolicyManagerServlet extends HttpServlet {
"actionBodyName", queryEntityName);
cloneEntity.setActionBodyEntity(actionEntiy);
newConfigurationName = actionEntiy.getActionBodyName();
- try (FileWriter fw = new FileWriter(
- PolicyController.getActionHome() + File.separator + newConfigurationName);
+ try (FileWriter fw =
+ new FileWriter(PolicyController.getActionHome() + File.separator + newConfigurationName);
BufferedWriter bw = new BufferedWriter(fw)) {
bw.write(actionEntiy.getActionBody());
} catch (IOException e) {
@@ -1175,13 +1215,13 @@ public class PolicyManagerServlet extends HttpServlet {
// Notify others paps regarding clone policy.
PolicyRestController restController = new PolicyRestController();
- restController.notifyOtherPAPSToUpdateConfigurations("clonePolicy", newConfigurationName, null);
+ restController.notifyOtherPapsToUpdateConfigurations("clonePolicy", newConfigurationName, null);
}
// Clone the Policy
private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException {
try {
- String userId = UserUtils.getUserSession(request).getOrgUserId();
+ String userId = getUserSession(request).getOrgUserId();
String oldPath = params.getString("path");
String newPath = params.getString("newPath");
oldPath = oldPath.substring(oldPath.indexOf('/') + 1);
@@ -1194,8 +1234,6 @@ public class PolicyManagerServlet extends HttpServlet {
String newPolicyName = newPath.replace(FORWARD_SLASH, ".");
- String originalPolicyName = oldPath.replace(FORWARD_SLASH, ".");
-
String newPolicyCheck = newPolicyName;
if (newPolicyCheck.contains(CONFIG2)) {
newPolicyCheck = newPolicyCheck.replace(CONFIG, CONFIG1);
@@ -1210,13 +1248,15 @@ public class PolicyManagerServlet extends HttpServlet {
String[] newPolicySplit = newPolicyCheck.split(":");
String checkValidation = newPolicySplit[1].replace(".xml", "");
- checkValidation = checkValidation.substring(checkValidation.indexOf('_') + 1,
- checkValidation.lastIndexOf('.'));
+ 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(originalPolicyName);
+ String originalPolicyName = oldPath.replace(FORWARD_SLASH, ".");
+
+ final String[] oldPolicySplit = modifyPolicyName(originalPolicyName);
PolicyController controller = getPolicyControllerInstance();
@@ -1224,7 +1264,8 @@ public class PolicyManagerServlet extends HttpServlet {
boolean success = false;
// Check PolicyEntity table with newPolicy Name
- String policyEntityquery = "FROM PolicyEntity where policyName = :newPolicySplit_1 and scope = :newPolicySplit_0";
+ 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]);
@@ -1272,7 +1313,7 @@ public class PolicyManagerServlet extends HttpServlet {
PolicyEntity policyEntity = null;
String policyNamewithoutExtension;
try {
- String userId = UserUtils.getUserSession(request).getOrgUserId();
+ String userId = getUserSession(request).getOrgUserId();
String deleteVersion = "";
String path = params.getString("path");
LOGGER.debug("delete {}" + path);
@@ -1307,8 +1348,8 @@ public class PolicyManagerServlet extends HttpServlet {
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()) {
@@ -1316,7 +1357,7 @@ public class PolicyManagerServlet extends HttpServlet {
activePolicyName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
} else {
deleteEntityFromEsAndPolicyEntityTable(controller, restController, policyEntity,
- policyNamewithoutExtension);
+ policyNamewithoutExtension);
}
}
}
@@ -1327,15 +1368,15 @@ public class PolicyManagerServlet extends HttpServlet {
controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll");
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 ='"
+ 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";
controller.executeQuery(policyVersionQuery);
return error(
- "Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "
+ "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
@@ -1344,12 +1385,13 @@ public class PolicyManagerServlet extends HttpServlet {
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, ".");
- query = "FROM PolicyEntity where policyName = :currentVersionPolicyName and scope = :currentVersionScope";
+ 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();
peParams.put("currentVersionPolicyName", currentVersionPolicyName);
@@ -1363,7 +1405,8 @@ public class PolicyManagerServlet extends HttpServlet {
return success();
}
- String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId and policyid > 0";
+ String groupEntityquery =
+ "from PolicyGroupEntity where policyid = :policyEntityId and policyid > 0";
SimpleBindings geParams = new SimpleBindings();
geParams.put("policyEntityId", policyEntity.getPolicyId());
List<Object> groupobject = controller.getDataByQuery(groupEntityquery, geParams);
@@ -1374,7 +1417,7 @@ public class PolicyManagerServlet extends HttpServlet {
// Delete the entity from Elastic Search Database
deleteEntityFromEsAndPolicyEntityTable(controller, restController, policyEntity,
- policyNamewithoutExtension);
+ policyNamewithoutExtension);
if (version > 1) {
int highestVersion = 0;
@@ -1414,7 +1457,7 @@ public class PolicyManagerServlet extends HttpServlet {
}
}
} else {
- List<String> activePoliciesInPDP = new ArrayList<>();
+ 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;
@@ -1429,7 +1472,7 @@ public class PolicyManagerServlet extends HttpServlet {
List<Object> groupobject = controller.getDataByQuery(groupEntityQuery, geParams);
if (!groupobject.isEmpty()) {
pdpCheck = true;
- activePoliciesInPDP.add(policyEntity.getScope() + "." + policyEntity.getPolicyName());
+ activePoliciesInPdp.add(policyEntity.getScope() + "." + policyEntity.getPolicyName());
} else {
// Delete the entity from Elastic Search Database
String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName();
@@ -1441,13 +1484,13 @@ public class PolicyManagerServlet extends HttpServlet {
Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator
+ policyEntity.getConfigurationData().getConfigurationName()));
controller.deleteData(policyEntity.getConfigurationData());
- restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null,
+ 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,
+ restController.notifyOtherPapsToUpdateConfigurations(DELETE, null,
policyEntity.getActionBodyEntity().getActionBodyName());
}
}
@@ -1464,22 +1507,22 @@ public class PolicyManagerServlet extends HttpServlet {
controller.watchPolicyFunction(entity, path, "DeleteScope");
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('.'))
+ 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);
+ 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);
+ + activePoliciesInPdp);
} else {
String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"
+ path.replace(BACKSLASH, ESCAPE_BACKSLASH) + PERCENT_AND_ID_GT_0;
@@ -1495,8 +1538,8 @@ public class PolicyManagerServlet extends HttpServlet {
}
private void deleteEntityFromEsAndPolicyEntityTable(final PolicyController controller,
- final PolicyRestController restController, final PolicyEntity policyEntity,
- final String policyNamewithoutExtension) throws IOException {
+ 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);
@@ -1504,16 +1547,16 @@ public class PolicyManagerServlet extends HttpServlet {
controller.deleteData(policyEntity);
if (policyNamewithoutExtension.contains(CONFIG2)) {
Files.deleteIfExists(Paths.get(PolicyController.getConfigHome() + File.separator
- + policyEntity.getConfigurationData().getConfigurationName()));
+ + policyEntity.getConfigurationData().getConfigurationName()));
controller.deleteData(policyEntity.getConfigurationData());
- restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null,
- policyEntity.getConfigurationData().getConfigurationName());
+ restController.notifyOtherPapsToUpdateConfigurations(DELETE, null,
+ policyEntity.getConfigurationData().getConfigurationName());
} else if (policyNamewithoutExtension.contains(ACTION2)) {
Files.deleteIfExists(Paths.get(PolicyController.getActionHome() + File.separator
- + policyEntity.getActionBodyEntity().getActionBodyName()));
+ + policyEntity.getActionBodyEntity().getActionBodyName()));
controller.deleteData(policyEntity.getActionBodyEntity());
- restController.notifyOtherPAPSToUpdateConfigurations(DELETE, null,
- policyEntity.getActionBodyEntity().getActionBodyName());
+ restController.notifyOtherPapsToUpdateConfigurations(DELETE, null,
+ policyEntity.getActionBodyEntity().getActionBodyName());
}
}
@@ -1521,8 +1564,7 @@ public class PolicyManagerServlet extends HttpServlet {
private JSONObject editFile(JSONObject params) throws ServletException {
// get content
try {
- PolicyController controller = getPolicyControllerInstance();
- String mode = params.getString("mode");
+ final String mode = params.getString("mode");
String path = params.getString("path");
LOGGER.debug("editFile path: {}" + path);
@@ -1538,7 +1580,7 @@ public class PolicyManagerServlet extends HttpServlet {
SimpleBindings peParams = new SimpleBindings();
peParams.put(SPLIT_1, split[1]);
peParams.put(SPLIT_0, split[0]);
- List<Object> queryData = getDataByQueryFromController(controller, query, peParams);
+ List<Object> queryData = getDataByQueryFromController(getPolicyControllerInstance(), query, peParams);
PolicyEntity entity = (PolicyEntity) queryData.get(0);
InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8));
@@ -1577,11 +1619,10 @@ public class PolicyManagerServlet extends HttpServlet {
// Add Scopes
private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
- PolicyController controller = getPolicyControllerInstance();
try {
String name = getNameFromParams(params);
String validateName =
- name.contains(File.separator) ? name.substring(name.lastIndexOf(File.separator) + 1) : name;
+ name.contains(File.separator) ? name.substring(name.lastIndexOf(File.separator) + 1) : name;
if (!name.isEmpty()) {
String validate = PolicyUtils.policySpecialCharValidator(validateName);
if (!validate.contains(SUCCESS)) {
@@ -1591,19 +1632,20 @@ public class PolicyManagerServlet extends HttpServlet {
if (name.startsWith(File.separator)) {
name = name.substring(1);
}
- PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class,
- SCOPE_NAME, name);
+ PolicyEditorScopes entity =
+ (PolicyEditorScopes) getPolicyControllerInstance().getEntityItem(
+ PolicyEditorScopes.class, SCOPE_NAME, name);
if (entity != null) {
return error("Scope Already Exists");
}
- String userId = UserUtils.getUserSession(request).getOrgUserId();
+ String userId = 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);
+ getPolicyControllerInstance().saveData(newScope);
}
return success();
} catch (Exception e) {
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 1fccfda78..34a95d98b 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
@@ -2,16 +2,16 @@
* ============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.
* 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.
@@ -48,20 +48,26 @@ import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
/**
- * Send policy notification mail depending on the mode for every policy being watched
+ * Send policy notification mail depending on the mode for every policy being watched.
*/
@Configurable
-public class PolicyNotificationMail{
+public class PolicyNotificationMail {
private static final String POLICY_WATCHING_MESSAGE = "The Policy Which you are watching in ";
- private static final String EMAIL_MESSAGE_POSTSCRIPT = "Policy Notification System (please don't respond to this email)";
+ private static final String EMAIL_MESSAGE_POSTSCRIPT =
+ "Policy Notification System (please don't respond to this email)";
private static final String ACTIVE_VERSION = "Active Version : ";
private static final String SCOPE_POLICY_NAME = "Scope + Policy Name : ";
private static final String DELETED_TIME = "Deleted Time : ";
private static final String DELETED_BY = "Deleted By : ";
- private static Logger policyLogger = FlexLogger.getLogger(PolicyNotificationMail.class);
+ private static Logger policyLogger = FlexLogger.getLogger(PolicyNotificationMail.class);
+ /**
+ * javaMailSenderImpl.
+ *
+ * @return JavaMailSenderImpl object
+ */
@Bean
- public JavaMailSenderImpl javaMailSenderImpl(){
+ public JavaMailSenderImpl javaMailSenderImpl() {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost(PolicyController.getSmtpHost());
mailSender.setPort(Integer.parseInt(PolicyController.getSmtpPort()));
@@ -79,51 +85,71 @@ public class PolicyNotificationMail{
* Depending on the mode of operation on the policy, compose the subject and message.
* Invoke another internal method to actual send the mail. If the watch list is empty , then
* this method returns without sending notification mail
+ *
* @param entityItem Database item from which policy name could be extracted
* @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
*/
- public void sendMail(PolicyVersion entityItem, String policyName, String mode, CommonClassDao policyNotificationDao) {
+ public void sendMail(PolicyVersion entityItem, String policyName, String mode,
+ CommonClassDao policyNotificationDao) {
String subject = "";
String message = "";
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
- if("EditPolicy".equalsIgnoreCase(mode)){
- subject = "Policy has been Updated : "+entityItem.getPolicyName();
- message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been Updated" + '\n' + '\n' + '\n'+ SCOPE_POLICY_NAME + policyName + '\n' + ACTIVE_VERSION +entityItem.getActiveVersion()
- + '\n' + '\n' + "Modified By : " +entityItem.getModifiedBy() + '\n' + "Modified Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT;
+ if ("EditPolicy".equalsIgnoreCase(mode)) {
+ subject = "Policy has been Updated : " + entityItem.getPolicyName();
+ message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been Updated" + '\n'
+ + '\n' + '\n' + SCOPE_POLICY_NAME + policyName + '\n' + ACTIVE_VERSION
+ + entityItem.getActiveVersion() + '\n' + '\n' + "Modified By : " + entityItem.getModifiedBy() + '\n'
+ + "Modified Time : " + dateFormat.format(date) + '\n' + '\n' + '\n' + '\n'
+ + EMAIL_MESSAGE_POSTSCRIPT;
}
- if("Rename".equalsIgnoreCase(mode)){
- subject = "Policy has been Renamed : "+entityItem.getPolicyName();
- message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been Renamed" + '\n' + '\n' + '\n'+ SCOPE_POLICY_NAME + policyName + '\n' + ACTIVE_VERSION +entityItem.getActiveVersion()
- + '\n' + '\n' + "Renamed By : " +entityItem.getModifiedBy() + '\n' + "Renamed Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT;
+ if ("Rename".equalsIgnoreCase(mode)) {
+ subject = "Policy has been Renamed : " + entityItem.getPolicyName();
+ message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been Renamed" + '\n'
+ + '\n' + '\n' + SCOPE_POLICY_NAME + policyName + '\n' + ACTIVE_VERSION
+ + entityItem.getActiveVersion() + '\n' + '\n' + "Renamed By : " + entityItem.getModifiedBy() + '\n'
+ + "Renamed Time : " + dateFormat.format(date) + '\n' + '\n' + '\n' + '\n'
+ + EMAIL_MESSAGE_POSTSCRIPT;
}
- if("DeleteAll".equalsIgnoreCase(mode)){
- subject = "Policy has been Deleted : "+entityItem.getPolicyName();
- message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been Deleted with All Versions" + '\n' + '\n' + '\n'+ SCOPE_POLICY_NAME + policyName + '\n'
- + '\n' + '\n' + DELETED_BY +entityItem.getModifiedBy() + '\n' + DELETED_TIME +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT;
+ if ("DeleteAll".equalsIgnoreCase(mode)) {
+ subject = "Policy has been Deleted : " + entityItem.getPolicyName();
+ message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName()
+ + " has been Deleted with All Versions" + '\n' + '\n' + '\n' + SCOPE_POLICY_NAME + policyName + '\n'
+ + '\n' + '\n' + DELETED_BY + entityItem.getModifiedBy() + '\n' + DELETED_TIME
+ + dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT;
}
- if("DeleteOne".equalsIgnoreCase(mode)){
- subject = "Policy has been Deleted : "+entityItem.getPolicyName();
- message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been Deleted" + '\n' + '\n' + '\n'+ SCOPE_POLICY_NAME + policyName + '\n' +"Policy Version : " +entityItem.getActiveVersion()
- + '\n' + '\n' + DELETED_BY +entityItem.getModifiedBy() + '\n' + DELETED_TIME +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT;
+ if ("DeleteOne".equalsIgnoreCase(mode)) {
+ subject = "Policy has been Deleted : " + entityItem.getPolicyName();
+ message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been Deleted" + '\n'
+ + '\n' + '\n' + SCOPE_POLICY_NAME + policyName + '\n' + "Policy Version : "
+ + entityItem.getActiveVersion() + '\n' + '\n' + DELETED_BY + entityItem.getModifiedBy() + '\n'
+ + DELETED_TIME + dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT;
}
- if("DeleteScope".equalsIgnoreCase(mode)){
- subject = "Scope has been Deleted : "+entityItem.getPolicyName();
- message = "The Scope Which you are watching in " + PolicyController.getSmtpApplicationName() + " has been Deleted" + '\n' + '\n' + '\n'+ "Scope + Scope Name : " + policyName + '\n'
- + '\n' + '\n' + DELETED_BY +entityItem.getModifiedBy() + '\n' + DELETED_TIME +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT;
+ if ("DeleteScope".equalsIgnoreCase(mode)) {
+ subject = "Scope has been Deleted : " + entityItem.getPolicyName();
+ message = "The Scope Which you are watching in " + PolicyController.getSmtpApplicationName()
+ + " has been Deleted" + '\n' + '\n' + '\n' + "Scope + Scope Name : " + policyName + '\n' + '\n'
+ + '\n' + DELETED_BY + entityItem.getModifiedBy() + '\n' + DELETED_TIME + dateFormat.format(date)
+ + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT;
}
- if("SwitchVersion".equalsIgnoreCase(mode)){
- subject = "Policy has been SwitchedVersion : "+entityItem.getPolicyName();
- message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been SwitchedVersion" + '\n' + '\n' + '\n'+ SCOPE_POLICY_NAME + policyName + '\n' + ACTIVE_VERSION +entityItem.getActiveVersion()
- + '\n' + '\n' + "Switched By : " +entityItem.getModifiedBy() + '\n' + "Switched Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT;
+ if ("SwitchVersion".equalsIgnoreCase(mode)) {
+ subject = "Policy has been SwitchedVersion : " + entityItem.getPolicyName();
+ message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been SwitchedVersion"
+ + '\n' + '\n' + '\n' + SCOPE_POLICY_NAME + policyName + '\n' + ACTIVE_VERSION
+ + entityItem.getActiveVersion() + '\n' + '\n' + "Switched By : " + entityItem.getModifiedBy() + '\n'
+ + "Switched Time : " + dateFormat.format(date) + '\n' + '\n' + '\n' + '\n'
+ + EMAIL_MESSAGE_POSTSCRIPT;
}
- if("Move".equalsIgnoreCase(mode)){
- subject = "Policy has been Moved to Other Scope : "+entityItem.getPolicyName();
- message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName() + " has been Moved to Other Scope" + '\n' + '\n' + '\n'+ SCOPE_POLICY_NAME + policyName + '\n' + ACTIVE_VERSION +entityItem.getActiveVersion()
- + '\n' + '\n' + "Moved By : " +entityItem.getModifiedBy() + '\n' + "Moved Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT;
+ if ("Move".equalsIgnoreCase(mode)) {
+ subject = "Policy has been Moved to Other Scope : " + entityItem.getPolicyName();
+ message = POLICY_WATCHING_MESSAGE + PolicyController.getSmtpApplicationName()
+ + " has been Moved to Other Scope" + '\n' + '\n' + '\n' + SCOPE_POLICY_NAME + policyName + '\n'
+ + ACTIVE_VERSION + entityItem.getActiveVersion() + '\n' + '\n' + "Moved By : "
+ + entityItem.getModifiedBy() + '\n' + "Moved Time : " + dateFormat.format(date) + '\n' + '\n'
+ + '\n' + '\n' + EMAIL_MESSAGE_POSTSCRIPT;
}
String checkPolicyName = findCheckPolicyName(policyName);
@@ -147,7 +173,7 @@ public class PolicyNotificationMail{
if (watchList == null || watchList.isEmpty()) {
policyLogger
- .debug("List of policy being watched is either null or empty, hence return without sending mail");
+ .debug("List of policy being watched is either null or empty, hence return without sending mail");
watchList = new ArrayList<>();
}
return watchList;
@@ -155,11 +181,11 @@ public class PolicyNotificationMail{
private String findPolicyFileName(PolicyVersion entityItem) {
String policyFileName = entityItem.getPolicyName();
- if(policyFileName.contains("/")){
+ if (policyFileName.contains("/")) {
policyFileName = policyFileName.substring(0, policyFileName.indexOf('/'));
policyFileName = policyFileName.replace("/", File.separator);
}
- if(policyFileName.contains("\\")){
+ if (policyFileName.contains("\\")) {
policyFileName = policyFileName.substring(0, policyFileName.indexOf('\\'));
policyFileName = policyFileName.replace("\\", "\\\\");
}
@@ -170,7 +196,7 @@ public class PolicyNotificationMail{
private String findCheckPolicyName(String policyName) {
String checkPolicyName = policyName;
- if(checkPolicyName.endsWith(".xml") || checkPolicyName.contains(".")){
+ if (checkPolicyName.endsWith(".xml") || checkPolicyName.contains(".")) {
checkPolicyName = checkPolicyName.substring(0, checkPolicyName.indexOf('.'));
}
return checkPolicyName;
@@ -178,29 +204,31 @@ public class PolicyNotificationMail{
/**
* For every policy being watched and when the policy name is one of the Config_, Action_ or Decision_,
- * send the notification
- * @param mode
- * @param policyNotificationDao
- * @param subject
- * @param message
- * @param checkPolicyName
- * @param watchList
+ * send the notification.
+ *
+ * @param mode String for the mode
+ * @param policyNotificationDao CommonClassDao
+ * @param subject String subject
+ * @param message String message
+ * @param checkPolicyName String check policy name
+ * @param watchList List of watch objects
*/
- private void composeAndSendMail(String mode, CommonClassDao policyNotificationDao, String subject, String message, String checkPolicyName, List<Object> watchList) {
+ private void composeAndSendMail(String mode, CommonClassDao policyNotificationDao, String subject, String message,
+ String checkPolicyName, List<Object> watchList) {
String from = PolicyController.getSmtpUsername();
String to;
- for(Object watch : watchList){
+ for (Object watch : watchList) {
WatchPolicyNotificationTable list = (WatchPolicyNotificationTable) watch;
String watchPolicyName = list.getPolicyName();
- //this conditino check for specific stringin policy name being watched and
- //also if the policy being checked is different from the watched ones,
- //then there is no need to send mail, hence continue with next policy in the loop
- if((watchPolicyName.contains("Config_") || watchPolicyName.contains("Action_") || watchPolicyName.contains("Decision_"))
- && !watchPolicyName.equals(checkPolicyName)){
+ // this condition check for specific stringin policy name being watched and
+ // also if the policy being checked is different from the watched ones,
+ // then there is no need to send mail, hence continue with next policy in the loop
+ if ((watchPolicyName.contains("Config_") || watchPolicyName.contains("Action_")
+ || watchPolicyName.contains("Decision_")) && !watchPolicyName.equals(checkPolicyName)) {
continue;
}
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext()) {
- to = list.getLoginIds()+"@"+PolicyController.getSmtpEmailExtension();
+ to = list.getLoginIds() + "@" + PolicyController.getSmtpEmailExtension();
to = to.trim();
ctx.register(PolicyNotificationMail.class);
ctx.refresh();
@@ -212,11 +240,12 @@ public class PolicyNotificationMail{
mailMsg.setSubject(subject);
mailMsg.setText(message);
mailSender.send(mimeMessage);
- if("Rename".equalsIgnoreCase(mode) || mode.contains("Delete") || mode.contains("Move")){
+ if ("Rename".equalsIgnoreCase(mode) || mode.contains("Delete") || mode.contains("Move")) {
policyNotificationDao.delete(watch);
}
} catch (Exception e) {
- policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Exception Occured in Policy Notification" +e);
+ policyLogger
+ .error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception Occured in Policy Notification" + e);
}
}
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 03dbccfd9..76bb04945 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
@@ -27,6 +27,7 @@ import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
+
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
@@ -39,8 +40,10 @@ import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
+
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@@ -53,7 +56,7 @@ import org.onap.policy.controller.CreateDcaeMicroServiceController;
import org.onap.policy.controller.CreateFirewallController;
import org.onap.policy.controller.CreateOptimizationController;
import org.onap.policy.controller.PolicyController;
-import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
import org.onap.policy.rest.dao.CommonClassDao;
import org.onap.policy.rest.jpa.PolicyVersion;
@@ -121,29 +124,32 @@ public class PolicyRestController extends RestrictedBaseController {
PolicyRestController.commonClassDao = commonClassDao;
}
-
-
+ /**
+ * policyCreationController.
+ *
+ * @param request Request
+ * @param response Response
+ */
@RequestMapping(value = {"/policycreation/save_policy"}, method = {RequestMethod.POST})
public void policyCreationController(HttpServletRequest request, HttpServletResponse response) {
- String userId = UserUtils.getUserSession(request).getOrgUserId();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
- updateAndSendToPAP(request, response, userId, mapper);
+ updateAndSendToPap(request, response, UserUtils.getUserSession(request).getOrgUserId(), mapper);
} catch (Exception e) {
policyLogger.error("Exception Occured while saving policy", e);
}
}
- private void updateAndSendToPAP(HttpServletRequest request, HttpServletResponse response, String userId,
+ 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**************************************************");
+ "********************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);
@@ -164,17 +170,16 @@ public class PolicyRestController extends RestrictedBaseController {
policyData.setUserId(userId);
String result;
- String body = PolicyUtils.objectToJsonString(policyData);
- String uri = request.getRequestURI();
- ResponseEntity<?> responseEntity = sendToPAP(body, uri, HttpMethod.POST);
+ ResponseEntity<?> responseEntity = sendToPap(PolicyUtils.objectToJsonString(policyData),
+ request.getRequestURI(), HttpMethod.POST);
if (responseEntity != null && responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)) {
result = "PolicyExists";
} else if (responseEntity != null) {
result = responseEntity.getBody().toString();
String policyName = responseEntity.getHeaders().get(POLICY_NAME).get(0);
if (policyData.isEditPolicy() && SUCCESS.equalsIgnoreCase(result)) {
- PolicyNotificationMail email = new PolicyNotificationMail();
- String mode = "EditPolicy";
+ final PolicyNotificationMail email = new PolicyNotificationMail();
+ final String mode = "EditPolicy";
String watchPolicyName = policyName.replace(XML, "");
String version = watchPolicyName.substring(watchPolicyName.lastIndexOf('.') + 1);
watchPolicyName =
@@ -197,8 +202,8 @@ public class PolicyRestController extends RestrictedBaseController {
PrintWriter out = response.getWriter();
String responseString = mapper.writeValueAsString(result);
- JSONObject j = new JSONObject("{policyData: " + responseString + "}");
- out.write(j.toString());
+ JSONObject json = new JSONObject("{policyData: " + responseString + "}");
+ out.write(json.toString());
}
private void modifyPolicyData(JsonNode root, PolicyRestAdapter policyData) {
@@ -227,13 +232,12 @@ public class PolicyRestController extends RestrictedBaseController {
}
}
-
- private ResponseEntity<?> sendToPAP(String body, String requestURI, HttpMethod method) {
+ private ResponseEntity<?> sendToPap(String body, String requestUri, HttpMethod method) {
String papUrl = PolicyController.getPapUrl();
- String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
- String papPass = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
- Base64.Encoder encoder = Base64.getEncoder();
- String encoding = encoder.encodeToString((papID + ":" + papPass).getBytes(StandardCharsets.UTF_8));
+ String papPass = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_PASS));
+ String encoding = Base64.getEncoder().encodeToString(
+ (XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_USERID)
+ + ":" + papPass).getBytes(StandardCharsets.UTF_8));
HttpHeaders headers = new HttpHeaders();
headers.set(AUTHORIZATION, BASIC + encoding);
headers.set(CONTENT_TYPE, PolicyController.getContenttype());
@@ -242,7 +246,7 @@ public class PolicyRestController extends RestrictedBaseController {
HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
ResponseEntity<?> result = null;
HttpClientErrorException exception = null;
- String uri = requestURI;
+ String uri = requestUri;
if (uri.startsWith("/")) {
uri = uri.substring(uri.indexOf('/') + 1);
}
@@ -279,27 +283,24 @@ public class PolicyRestController extends RestrictedBaseController {
return result;
}
- private String callPAP(HttpServletRequest request, String method, String uriValue) {
- String uri = uriValue;
- String papUrl = PolicyController.getPapUrl();
- String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
- PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY));
- String papPass = PeCryptoUtils.decrypt((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)));
+ private String callPap(HttpServletRequest request, String method, String uriValue) {
+ PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XacmlRestProperties.PROP_AES_KEY));
+ String papPass = PeCryptoUtils.decrypt((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((XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_USERID)
+ + ":" + papPass).getBytes(StandardCharsets.UTF_8));
HttpHeaders headers = new HttpHeaders();
headers.set(AUTHORIZATION, BASIC + encoding);
headers.set(CONTENT_TYPE, PolicyController.getContenttype());
-
HttpURLConnection connection = null;
- List<FileItem> items;
FileItem item = null;
File file = null;
+ String uri = uriValue;
if (uri.contains(IMPORT_DICTIONARY)) {
try {
- items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
+ List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
item = items.get(0);
file = new File(item.getName());
String newFile = file.toString();
@@ -310,7 +311,7 @@ public class PolicyRestController extends RestrictedBaseController {
}
try {
- URL url = new URL(papUrl + uri);
+ URL url = new URL(PolicyController.getPapUrl() + uri);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method);
connection.setUseCaches(false);
@@ -324,7 +325,7 @@ public class PolicyRestController extends RestrictedBaseController {
return doConnect(connection);
}
- checkURI(request, uri, connection, item);
+ checkUri(request, uri, connection, item);
return doConnect(connection);
} catch (Exception e) {
@@ -351,9 +352,8 @@ public class PolicyRestController extends RestrictedBaseController {
return null;
}
- private void checkURI(HttpServletRequest request, String uri, HttpURLConnection connection, FileItem item)
+ 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());
ObjectMapper mapper = new ObjectMapper();
@@ -380,7 +380,7 @@ public class PolicyRestController extends RestrictedBaseController {
IOUtils.copy(request.getInputStream(), os);
}
} else {
- boundary = "===" + System.currentTimeMillis() + "===";
+ String boundary = "===" + System.currentTimeMillis() + "===";
connection.setRequestProperty(CONTENT_TYPE, "multipart/form-data; boundary=" + boundary);
try (OutputStream os = connection.getOutputStream()) {
if (item != null) {
@@ -402,8 +402,7 @@ public class PolicyRestController extends RestrictedBaseController {
private String doConnect(final HttpURLConnection connection) throws IOException {
connection.connect();
- int responseCode = connection.getResponseCode();
- if (responseCode == 200) {
+ if (connection.getResponseCode() == 200) {
// get the response content into a String
String responseJson = null;
// read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
@@ -425,11 +424,17 @@ public class PolicyRestController extends RestrictedBaseController {
return null;
}
+ /**
+ * getDictionaryController.
+ *
+ * @param request Request
+ * @param response Response
+ */
@RequestMapping(value = {"/getDictionary/*"}, method = {RequestMethod.GET})
public void getDictionaryController(HttpServletRequest request, HttpServletResponse response) {
- String uri = request.getRequestURI().replace("/getDictionary", "");
String body;
- ResponseEntity<?> responseEntity = sendToPAP(null, uri, HttpMethod.GET);
+ ResponseEntity<?> responseEntity = sendToPap(null, request.getRequestURI().replace("/getDictionary", ""),
+ HttpMethod.GET);
if (responseEntity != null) {
body = responseEntity.getBody().toString();
} else {
@@ -442,6 +447,13 @@ public class PolicyRestController extends RestrictedBaseController {
}
}
+ /**
+ * saveDictionaryController.
+ *
+ * @param request Request
+ * @param response Response
+ * @throws IOException IO Exception
+ */
@RequestMapping(value = {"/saveDictionary/*/*"}, method = {RequestMethod.POST})
public void saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
String userId = "";
@@ -456,12 +468,12 @@ public class PolicyRestController extends RestrictedBaseController {
}
policyLogger.info(
- "****************************************Logging UserID while Saving Dictionary*****************************************************");
+ "********************Logging UserID while Saving Dictionary**************************************");
policyLogger.info(USER_ID + userId);
policyLogger.info(
- "***********************************************************************************************************************************");
+ "************************************************************************************************");
- String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
+ String body = callPap(request, "POST", uri.replaceFirst("/", "").trim());
if (body != null && !body.isEmpty()) {
response.getWriter().write(body);
} else {
@@ -469,6 +481,13 @@ public class PolicyRestController extends RestrictedBaseController {
}
}
+ /**
+ * deletetDictionaryController.
+ *
+ * @param request Request
+ * @param response Response
+ * @throws IOException IO Exception
+ */
@RequestMapping(value = {"/deleteDictionary/*/*"}, method = {RequestMethod.POST})
public void deletetDictionaryController(HttpServletRequest request, HttpServletResponse response)
throws IOException {
@@ -480,12 +499,12 @@ public class PolicyRestController extends RestrictedBaseController {
String userId = UserUtils.getUserSession(request).getOrgUserId();
policyLogger.info(
- "****************************************Logging UserID while Deleting Dictionary*****************************************************");
+ "**********************Logging UserID while Deleting Dictionary*************************************");
policyLogger.info(USER_ID + userId);
policyLogger.info(
- "*************************************************************************************************************************************");
+ "***************************************************************************************************");
- String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
+ String body = callPap(request, "POST", uri.replaceFirst("/", "").trim());
if (body != null && !body.isEmpty()) {
response.getWriter().write(body);
} else {
@@ -493,6 +512,14 @@ public class PolicyRestController extends RestrictedBaseController {
}
}
+ /**
+ * searchDictionaryController.
+ *
+ * @param request Request
+ * @param response Response
+ * @return ModelAndView object
+ * @throws IOException IO Exception
+ */
@RequestMapping(value = {"/searchDictionary"}, method = {RequestMethod.POST})
public ModelAndView searchDictionaryController(HttpServletRequest request, HttpServletResponse response)
throws IOException {
@@ -503,14 +530,13 @@ public class PolicyRestController extends RestrictedBaseController {
}
uri = ONAP + uri.substring(uri.indexOf('/'));
try {
- String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
+ String body = callPap(request, "POST", uri.replaceFirst("/", "").trim());
if (body.contains("CouldNotConnectException")) {
List<String> data = new ArrayList<>();
data.add("Elastic Search Server is down");
resultList = data;
} else {
- JSONObject json = new JSONObject(body);
- resultList = json.get("policyresult");
+ resultList = new JSONObject(body).get("policyresult");
}
} catch (Exception e) {
policyLogger.error(
@@ -522,12 +548,18 @@ public class PolicyRestController extends RestrictedBaseController {
response.setCharacterEncoding(PolicyController.getCharacterencoding());
response.setContentType(PolicyController.getContenttype());
- PrintWriter out = response.getWriter();
- JSONObject j = new JSONObject("{result: " + resultList + "}");
- out.write(j.toString());
+ response.getWriter().write(new JSONObject("{result: " + resultList + "}").toString());
return null;
}
+ /**
+ * searchPolicy.
+ *
+ * @param request request
+ * @param response response
+ * @return ModelAndView object
+ * @throws IOException IO exception
+ */
@RequestMapping(value = {"/searchPolicy"}, method = {RequestMethod.POST})
public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException {
Object resultList;
@@ -536,7 +568,7 @@ public class PolicyRestController extends RestrictedBaseController {
uri = uri.substring(uri.indexOf('/') + 1);
}
uri = ONAP + uri.substring(uri.indexOf('/'));
- String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
+ String body = callPap(request, "POST", uri.replaceFirst("/", "").trim());
JSONObject json = new JSONObject(body);
try {
@@ -554,21 +586,27 @@ public class PolicyRestController extends RestrictedBaseController {
response.setContentType("application / json");
request.setCharacterEncoding(UTF_8);
- PrintWriter out = response.getWriter();
- JSONObject j = new JSONObject("{result: " + resultList + "}");
- out.write(j.toString());
+ response.getWriter().write(new JSONObject("{result: " + resultList + "}").toString());
return null;
}
public void deleteElasticData(String fileName) {
String uri = "searchPolicy?action=delete&policyName='" + fileName + "'";
- callPAP(null, "POST", uri.trim());
+ callPap(null, "POST", uri.trim());
}
- public String notifyOtherPAPSToUpdateConfigurations(String mode, String newName, String oldName) {
+ /**
+ * notifyOtherPAPSToUpdateConfigurations.
+ *
+ * @param mode Mode
+ * @param newName New Name
+ * @param oldName Old Name
+ * @return String
+ */
+ public String notifyOtherPapsToUpdateConfigurations(String mode, String newName, String oldName) {
String uri =
"onap/notifyOtherPAPs?action=" + mode + "&newPolicyName=" + newName + "&oldPolicyName=" + oldName + "";
- return callPAP(null, "POST", uri.trim());
+ return callPap(null, "POST", uri.trim());
}
}
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 7e0aef2e9..9cf647954 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
@@ -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.
* Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -18,8 +18,11 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.admin;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.util.HashMap;
import java.util.Map;
@@ -36,25 +39,26 @@ import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
@Controller
@RequestMapping("/")
public class PolicyUserInfoController extends RestrictedBaseController {
private static final Logger LOGGER = FlexLogger.getLogger(PolicyUserInfoController.class);
+ /**
+ * getPolicyUserInfo - fills the HTTP response with user information.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
@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());
+ response.getWriter().write(new JSONObject(new JsonMessage(
+ new ObjectMapper().writeValueAsString(model))).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 a500c1dbe..d89dd2784 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
@@ -29,6 +29,7 @@ import com.att.research.xacml.util.XACMLProperties;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
+
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@@ -37,6 +38,7 @@ import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
+import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
@@ -45,10 +47,12 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
+
import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang.StringUtils;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
-import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
import org.onap.policy.utils.PeCryptoUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
@@ -64,7 +68,7 @@ import org.onap.policy.xacml.std.pap.StdPDPStatus;
/**
* Implementation of the PAPEngine interface that communicates with a PAP engine in a remote servlet through a RESTful
- * interface
+ * interface.
*
*
*/
@@ -72,25 +76,29 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
private static final Logger LOGGER = FlexLogger.getLogger(RESTfulPAPEngine.class);
private static final String GROUP_ID = "groupId=";
+ private static final String UNABLE_MSG = "Unable to PUT policy '";
+ private static final String EXCEPTION_MSG = "', e:";
+ private static final String ERROR_MSG = "error";
+ private static final String PDPID_MSG = "pdpId=";
//
// URL of the PAP Servlet that this Admin Console talks to
//
- private String papServletURLString;
+ private String papServletUrlString;
/**
- * Set up link with PAP Servlet and get our initial set of Groups
+ * Set up link with PAP Servlet and get our initial set of Groups.
*
* @throws PAPException When failing to register with PAP
*/
- public RESTfulPAPEngine(String myURLString) throws PAPException {
+ public RESTfulPAPEngine(String myUrlString) throws PAPException {
//
// Get our URL to the PAP servlet
//
- this.papServletURLString = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
- if (this.papServletURLString == null || this.papServletURLString.length() == 0) {
- String message =
- "The property 'POLICYENGINE_ADMIN_ACTIVE' was not set during installation. Admin Console cannot call PAP.";
+ this.papServletUrlString = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URL);
+ if (StringUtils.isBlank(this.papServletUrlString)) {
+ String message = "The property 'POLICYENGINE_ADMIN_ACTIVE' was not set during installation. "
+ + "Admin Console cannot call PAP.";
LOGGER.error(message);
throw new PAPException(message);
}
@@ -98,14 +106,14 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
//
// register this Admin Console with the PAP Servlet to get updates
//
- Object newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString);
- if (newURL != null) {
+ Object newUrl = sendToPap("PUT", null, null, null, "adminConsoleURL=" + myUrlString);
+ if (newUrl != null) {
// assume this was a re-direct and try again
- LOGGER.warn("Redirecting to '" + newURL + "'");
- this.papServletURLString = (String) newURL;
- newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString);
- if (newURL != null) {
- LOGGER.error("Failed to redirect to " + this.papServletURLString);
+ LOGGER.warn("Redirecting to '" + newUrl + "'");
+ this.papServletUrlString = (String) newUrl;
+ newUrl = sendToPap("PUT", null, null, null, "adminConsoleURL=" + myUrlString);
+ if (newUrl != null) {
+ LOGGER.error("Failed to redirect to " + this.papServletUrlString);
throw new PAPException("Failed to register with PAP");
}
}
@@ -117,25 +125,25 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
@Override
public OnapPDPGroup getDefaultGroup() throws PAPException {
- return (OnapPDPGroup) sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID, "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, GROUP_ID + 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, GROUP_ID);
+ 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, GROUP_ID + id);
+ return (OnapPDPGroup) sendToPap("GET", null, null, StdPDPGroup.class, GROUP_ID + id);
}
@Override
@@ -149,17 +157,10 @@ 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, GROUP_ID, "groupName=" + escapedName,
+ this.sendToPap("POST", null, null, null, GROUP_ID, "groupName=" + escapedName,
"groupDescription=" + escapedDescription);
}
- /**
- * Update the configuration on the PAP for a single Group.
- *
- * @param group
- * @return
- * @throws PAPException
- */
@Override
public void updateGroup(OnapPDPGroup group) throws PAPException {
try {
@@ -175,9 +176,9 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
// 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, GROUP_ID + group.getId());
+ sendToPap("PUT", group, null, null, GROUP_ID + group.getId());
} catch (Exception e) {
- String message = "Unable to PUT policy '" + group.getId() + "', e:" + e;
+ String message = UNABLE_MSG + group.getId() + EXCEPTION_MSG + e;
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
throw new PAPException(message);
}
@@ -192,9 +193,9 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
@Override
public void updateGroup(OnapPDPGroup group, String userName) throws PAPException {
try {
- sendToPAP("PUT", group, null, null, GROUP_ID + group.getId(), "userId=" + userName);
+ sendToPap("PUT", group, null, null, GROUP_ID + group.getId(), "userId=" + userName);
} catch (Exception e) {
- String message = "Unable to PUT policy '" + group.getId() + "', e:" + e;
+ String message = UNABLE_MSG + group.getId() + EXCEPTION_MSG + e;
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
throw new PAPException(message);
}
@@ -206,7 +207,7 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
if (newGroup != null) {
moveToGroupString = "movePDPsToGroupId=" + newGroup.getId();
}
- sendToPAP("DELETE", null, null, null, GROUP_ID + group.getId(), moveToGroupString);
+ sendToPap("DELETE", null, null, null, GROUP_ID + group.getId(), moveToGroupString);
}
@Override
@@ -215,56 +216,61 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
}
public OnapPDPGroup getPDPGroup(String pdpId) throws PAPException {
- return (OnapPDPGroup) sendToPAP("GET", null, null, StdPDPGroup.class, GROUP_ID, "pdpId=" + pdpId,
+ return (OnapPDPGroup) sendToPap("GET", null, null, StdPDPGroup.class, GROUP_ID, PDPID_MSG + pdpId,
"getPDPGroup=");
}
@Override
public OnapPDP getPDP(String pdpId) throws PAPException {
- return (OnapPDP) sendToPAP("GET", null, null, StdPDP.class, GROUP_ID, "pdpId=" + pdpId);
+ return (OnapPDP) sendToPap("GET", null, null, StdPDP.class, GROUP_ID, PDPID_MSG + 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, GROUP_ID + group.getId(), "pdpId=" + id);
+ StdPDP newPdp = new StdPDP(id, name, description, jmxport);
+ sendToPap("PUT", newPdp, null, null, GROUP_ID + group.getId(), PDPID_MSG + id);
}
@Override
public void movePDP(OnapPDP pdp, OnapPDPGroup newGroup) throws PAPException {
- sendToPAP("POST", null, null, null, GROUP_ID + newGroup.getId(), "pdpId=" + pdp.getId());
+ sendToPap("POST", null, null, null, GROUP_ID + newGroup.getId(), PDPID_MSG + pdp.getId());
}
@Override
public void updatePDP(OnapPDP pdp) throws PAPException {
OnapPDPGroup group = getPDPGroup(pdp);
- sendToPAP("PUT", pdp, null, null, GROUP_ID + group.getId(), "pdpId=" + pdp.getId());
+ sendToPap("PUT", pdp, null, null, GROUP_ID + group.getId(), PDPID_MSG + pdp.getId());
}
@Override
public void removePDP(OnapPDP pdp) throws PAPException {
OnapPDPGroup group = getPDPGroup(pdp);
- sendToPAP("DELETE", null, null, null, GROUP_ID + group.getId(), "pdpId=" + pdp.getId());
+ sendToPap("DELETE", null, null, null, GROUP_ID + group.getId(), PDPID_MSG + pdp.getId());
}
- // Validate the Policy Data
+ /**
+ * validatePolicyRequest Creates a pap policy and then send to pap.
+ *
+ * @param policyAdapter Input Adapter
+ * @param policyType Type of Policy
+ * @return true if validated
+ * @throws PAPException exception if invalid
+ */
public boolean validatePolicyRequest(PolicyRestAdapter policyAdapter, String policyType) throws PAPException {
- StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getConfigBodyData(),
+ StdPAPPolicy newPapPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getConfigBodyData(),
policyAdapter.getConfigType(), "Base");
// send JSON object to PAP
- return (Boolean) sendToPAP("PUT", newPAPPolicy, null, null, "operation=validate", "apiflag=admin",
+ return (Boolean) sendToPap("PUT", newPapPolicy, null, null, "operation=validate", "apiflag=admin",
"policyType=" + policyType);
}
-
-
@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);
+ copyFile(id, group, policy, null);
// adjust the local copy of the group to include the new policy
PDPPolicy pdpPolicy = new StdPDPPolicy(id, isRoot, name);
@@ -278,32 +284,31 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
* Copy a single Policy file from the input stream to the PAP Servlet. Either this works (silently) or it throws an
* exception.
*
- * @param policyId
- * @param group
- * @param policy
- * @return
- * @throws PAPException
+ * @param policyId ID of policy
+ * @param group PDP Group
+ * @param policy Input stream of policy
+ * @throws PAPException exception
*/
- public void copyFile(String policyId, OnapPDPGroup group, InputStream policy) throws PAPException {
+ public void copyFile(String policyId, OnapPDPGroup group, InputStream policy, String usrId) throws PAPException {
// send the policy file to the PAP Servlet
try {
- sendToPAP("POST", policy, null, null, GROUP_ID + group.getId(), "policyId=" + policyId);
+ sendToPap("POST", policy, null, null, GROUP_ID + group.getId(), "policyId=" + policyId, "userId=" + usrId );
} catch (Exception e) {
- String message = "Unable to PUT policy '" + policyId + "', e:" + e;
+ String message = UNABLE_MSG + policyId + EXCEPTION_MSG + e;
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
throw new PAPException(message);
}
}
@Override
- public void copyPolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException {
+ public void copyPolicy(PDPPolicy policy, OnapPDPGroup group, String userId) throws PAPException {
if (policy == null || group == null) {
throw new PAPException("Null input policy=" + policy + " group=" + group);
}
try (InputStream is = new FileInputStream(new File(policy.getLocation()))) {
- copyFile(policy.getId(), group, is);
+ copyFile(policy.getId(), group, is, userId);
} catch (Exception e) {
- String message = "Unable to PUT policy '" + policy.getId() + "', e:" + e;
+ String message = UNABLE_MSG + policy.getId() + EXCEPTION_MSG + e;
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
throw new PAPException(message);
}
@@ -318,13 +323,13 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
* Special operation - Similar to the normal PAP operations but this one contacts the PDP directly to get detailed
* status info.
*
- * @param pdp
- * @return
- * @throws PAPException
+ * @param pdp PDP to get status
+ * @return PDPStatus object
+ * @throws PAPException Exception
*/
@Override
public PDPStatus getStatus(OnapPDP pdp) throws PAPException {
- return (StdPDPStatus) sendToPAP("GET", pdp, null, StdPDPStatus.class);
+ return (StdPDPStatus) sendToPap("GET", pdp, null, StdPDPStatus.class);
}
//
@@ -334,57 +339,56 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
/**
* Send a request to the PAP Servlet and get the response.
*
- * The content is either an InputStream to be copied to the Request OutputStream OR it is an object that is to be
+ * <p>The content is either an InputStream to be copied to the Request OutputStream OR it is an object that is to be
* encoded into JSON and pushed into the Request OutputStream.
*
- * The Request parameters may be encoded in multiple "name=value" sets, or parameters may be combined by the caller.
+ * <p>The Request parameters may be encoded in multiple "name=value" sets, or parameters may be
+ * combined by the caller.
*
- * @param method
+ * @param method method
* @param content - EITHER an InputStream OR an Object to be encoded in JSON
- * @param collectionTypeClass
- * @param responseContentClass
- * @param parameters
- * @return
- * @throws PAPException
+ * @param collectionTypeClass Collection
+ * @param responseContentClass Response Content
+ * @param parameters List of parameters
+ * @return Object
+ * @throws PAPException exception
*/
@SuppressWarnings({"rawtypes", "unchecked"})
- private Object sendToPAP(String method, Object content, Class collectionTypeClass, Class responseContentClass,
+ private Object sendToPap(String method, Object content, Class collectionTypeClass, Class responseContentClass,
String... parameters) throws PAPException {
HttpURLConnection connection = null;
- String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
+ String papID = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_USERID);
LOGGER.info("User Id is " + papID);
- PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY));
+ PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XacmlRestProperties.PROP_AES_KEY));
String papPass = PeCryptoUtils
- .decrypt(PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)));
+ .decrypt(PeCryptoUtils.decrypt(XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_PASS)));
Base64.Encoder encoder = Base64.getEncoder();
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;
+ String fullUrl = papServletUrlString;
if (parameters != null && parameters.length > 0) {
StringBuilder queryString = new StringBuilder();
Arrays.stream(parameters).map(p -> "&" + p).forEach(queryString::append);
- fullURL += "?" + queryString.substring(1);
+ 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) {
// Adjust the url and properties appropriately
String pdpID = ((OnapPDP) contentObj).getId();
- fullURL = pdpID + "?type=Status";
+ fullUrl = pdpID + "?type=Status";
contentObj = null;
- if (CheckPDP.validateID(pdpID)) {
- encoding = CheckPDP.getEncoding(pdpID);
+ if (CheckPdpProperties.validateId(pdpID)) {
+ encoding = CheckPdpProperties.getEncoding(pdpID);
}
}
- URL url = new URL(fullURL);
-
//
// Open up the connection
//
- connection = (HttpURLConnection) url.openConnection();
+ connection = (HttpURLConnection) makeConnection(fullUrl);
//
// Setup our method and headers
//
@@ -434,9 +438,9 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
String finalPolicyPath = connection.getHeaderField("finalPolicyPath");
successMap.put("success", finalPolicyPath);
return successMap;
- } else if ("error".equalsIgnoreCase(isSuccess)) {
+ } else if (ERROR_MSG.equalsIgnoreCase(isSuccess)) {
LOGGER.info("There was an error while creating the policy!");
- successMap.put("error", "error");
+ successMap.put(ERROR_MSG, ERROR_MSG);
return successMap;
} else {
// get the response content into a String
@@ -457,19 +461,19 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
}
} else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) {
// redirection
- String newURL = connection.getHeaderField("Location");
- if (newURL == null) {
+ 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());
}
- int qIndex = newURL.indexOf('?');
- if (qIndex > 0) {
- newURL = newURL.substring(0, qIndex);
+ int qindex = newUrl.indexOf('?');
+ if (qindex > 0) {
+ newUrl = newUrl.substring(0, qindex);
}
- LOGGER.info("Redirect seen. Redirecting " + fullURL + " to " + newURL);
- return newURL;
+ LOGGER.info("Redirect seen. Redirecting " + fullUrl + " to " + newUrl);
+ return newUrl;
} else {
LOGGER.warn("Unexpected response code: " + connection.getResponseCode() + " message: "
+ connection.getResponseMessage());
@@ -527,4 +531,10 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
LOGGER.info("JSON response from PAP: " + json);
return json;
}
+
+ // these may be overridden by junit tests
+
+ protected URLConnection makeConnection(String fullUrl) throws IOException {
+ return new URL(fullUrl).openConnection();
+ }
}
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 b116af6ef..f2c3a5d7a 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
@@ -2,15 +2,15 @@
* ============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.
* 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,7 +39,9 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+
import javax.xml.bind.JAXBElement;
+
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
@@ -57,6 +59,7 @@ 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 oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType;
+
import org.apache.commons.io.FilenameUtils;
import org.json.JSONObject;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
@@ -95,7 +98,6 @@ public class HumanPolicyComponent {
public static final String EMPTY_STRING = "";
private static final String ENTER = "ENTER";
-
private static HtmlProcessor htmlProcessor;
private static File policyFile;
@@ -104,9 +106,16 @@ public class HumanPolicyComponent {
// Default Constructor
}
+ /**
+ * DescribePolicy.
+ *
+ * @param policyFile File
+ * @return JSONObject
+ */
public static JSONObject DescribePolicy(final File policyFile) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace(ENTER);
+ }
HumanPolicyComponent.policyFile = policyFile;
return humanPolicyLayout();
@@ -114,8 +123,9 @@ public class HumanPolicyComponent {
}
private static JSONObject humanPolicyLayout() {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace(ENTER);
+ }
try {
String html = processPolicy();
@@ -135,8 +145,9 @@ public class HumanPolicyComponent {
}
try (FileInputStream pIS = new FileInputStream(policyFile)) {
Object policy = XACMLPolicyScanner.readPolicy(pIS);
- if (policy == null)
+ if (policy == null) {
throw new IllegalArgumentException("Policy File " + policyFile.getName() + " cannot be unmarshalled");
+ }
HumanPolicyComponent.htmlProcessor = new HtmlProcessor(HumanPolicyComponent.policyFile, policy);
@@ -144,8 +155,9 @@ public class HumanPolicyComponent {
XACMLPolicyScanner xacmlScanner = new XACMLPolicyScanner(policyPath, htmlProcessor);
xacmlScanner.scan();
String html = htmlProcessor.html();
- if (LOGGER.isDebugEnabled())
+ if (LOGGER.isDebugEnabled()) {
LOGGER.debug(policyPath + System.lineSeparator() + html);
+ }
return html;
@@ -165,6 +177,7 @@ class HtmlProcessor extends SimpleCallback {
private static final String ENTER = "ENTER";
private static Map<String, String> function2human;
+
static {
function2human = new HashMap<>();
function2human.put(HumanPolicyComponent.FUNCTION_STRING_EQUAL, "equal");
@@ -175,6 +188,7 @@ class HtmlProcessor extends SimpleCallback {
}
private static Map<String, String> combiningAlgo2human;
+
static {
combiningAlgo2human = new HashMap<>();
combiningAlgo2human.put("deny-overrides", "to deny if any $placeholder$ below evaluates to <i>deny</i>");
@@ -203,8 +217,9 @@ class HtmlProcessor extends SimpleCallback {
private final Object rootPolicyObject;
public HtmlProcessor(File policyFile, Object policyObject) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace(ENTER);
+ }
if (policyFile == null) {
LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Null Policy File");
@@ -259,6 +274,8 @@ class HtmlProcessor extends SimpleCallback {
}
/**
+ * getAttributeIdentifiersMap.
+ *
* @return the attributeIdentifiersMap
*/
public Map<String, AttributeIdentifiers> getAttributeIdentifiersMap() {
@@ -267,8 +284,9 @@ class HtmlProcessor extends SimpleCallback {
@Override
public void onFinishScan(Object root) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace(ENTER);
+ }
if (rootPolicyObject instanceof PolicySetType) {
htmlOut.println("</dl>");
@@ -306,43 +324,52 @@ class HtmlProcessor extends SimpleCallback {
@Override
public CallbackResult onPreVisitPolicySet(PolicySetType parent, PolicySetType policySet) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Version: " + policySet.getVersion());
+ }
- if (parent != null && LOGGER.isTraceEnabled())
+ if (parent != null && LOGGER.isTraceEnabled()) {
LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + "Parent PolicySet: " + parent.getPolicySetId()
+ " Version: " + parent.getVersion());
+ }
String description = policySet.getDescription();
- if (description != null && LOGGER.isTraceEnabled())
+ if (description != null && LOGGER.isTraceEnabled()) {
LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Description: " + policySet.getDescription());
+ }
- if (parent == null) // root
+ if (parent == null) { // root
policySet(policySet, "dl");
- else
+ } else {
policySet(policySet, "li");
+ }
- if (!policySet.getPolicySetOrPolicyOrPolicySetIdReference().isEmpty())
+ if (!policySet.getPolicySetOrPolicyOrPolicySetIdReference().isEmpty()) {
htmlOut.println("<ol>");
+ }
return super.onPreVisitPolicySet(parent, policySet);
}
@Override
public CallbackResult onPostVisitPolicySet(PolicySetType parent, PolicySetType policySet) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Version: " + policySet.getVersion());
+ }
- if (parent != null && LOGGER.isTraceEnabled())
+ if (parent != null && LOGGER.isTraceEnabled()) {
LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + "Parent PolicySet: " + parent.getPolicySetId()
+ " Version: " + parent.getVersion());
+ }
String description = policySet.getDescription();
- if (description != null && LOGGER.isTraceEnabled())
+ if (description != null && LOGGER.isTraceEnabled()) {
LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Description: " + policySet.getDescription());
+ }
- if (!policySet.getPolicySetOrPolicyOrPolicySetIdReference().isEmpty())
+ if (!policySet.getPolicySetOrPolicyOrPolicySetIdReference().isEmpty()) {
htmlOut.println("</ol>");
+ }
htmlOut.println("<p></p>");
@@ -350,23 +377,25 @@ class HtmlProcessor extends SimpleCallback {
}
public void policySet(PolicySetType policySet, String htmlListElement) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace("PolicySet: " + policySet.getPolicySetId());
+ }
String combiningAlgorithm = "-";
String id = "-";
String version = "-";
-
- if (policySet.getPolicyCombiningAlgId() != null)
+ if (policySet.getPolicyCombiningAlgId() != null) {
combiningAlgorithm = extractLastIdentifier(policySet.getPolicyCombiningAlgId(), ":");
+ }
- if (policySet.getPolicySetId() != null)
+ if (policySet.getPolicySetId() != null) {
id = extractLastIdentifier(policySet.getPolicySetId(), ":");
+ }
- if (policySet.getVersion() != null)
+ if (policySet.getVersion() != null) {
version = policySet.getVersion();
-
+ }
htmlOut.println("<" + htmlListElement + "><b>Policy Set ID</b>: <i>" + id + "</i> (v" + version + ") " + "</"
+ htmlListElement + ">");
@@ -378,8 +407,7 @@ class HtmlProcessor extends SimpleCallback {
htmlOut.print("<p>");
htmlOut.print("This policy set applies to requests with attributes ");
- List<AnyOfType> anyOf_s = policySet.getTarget().getAnyOf();
- target(anyOf_s);
+ target(policySet.getTarget().getAnyOf());
htmlOut.println(".</p>");
}
@@ -398,58 +426,68 @@ class HtmlProcessor extends SimpleCallback {
@Override
public CallbackResult onPreVisitPolicy(PolicySetType parent, PolicyType policy) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace("PolicySet: " + policy.getPolicyId() + " Version: " + policy.getVersion());
+ }
- if (parent != null && LOGGER.isTraceEnabled())
+ if (parent != null && LOGGER.isTraceEnabled()) {
LOGGER.trace("PolicySet: " + policy.getPolicyId() + "Parent PolicySet: " + parent.getPolicySetId()
+ " Version: " + parent.getVersion());
+ }
String description = policy.getDescription();
- if (description != null && LOGGER.isTraceEnabled())
+ if (description != null && LOGGER.isTraceEnabled()) {
LOGGER.trace("PolicySet: " + policy.getPolicyId() + " Description: " + policy.getDescription());
+ }
policy(policy);
- if (!policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().isEmpty())
+ if (!policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().isEmpty()) {
htmlOut.println("<ol type=\"i\">");
+ }
return super.onPreVisitPolicy(parent, policy);
}
@Override
public CallbackResult onPostVisitPolicy(PolicySetType parent, PolicyType policy) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace("PolicySet: " + policy.getPolicyId() + " Version: " + policy.getVersion());
+ }
- if (parent != null && LOGGER.isTraceEnabled())
+ if (parent != null && LOGGER.isTraceEnabled()) {
LOGGER.trace("PolicySet: " + policy.getPolicyId() + "Parent PolicySet: " + parent.getPolicySetId()
+ " Version: " + parent.getVersion());
+ }
- if (!policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().isEmpty())
+ if (!policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().isEmpty()) {
htmlOut.println("</ol>");
+ }
htmlOut.println("<p></p>");
return super.onPostVisitPolicy(parent, policy);
}
public void policy(PolicyType policy) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Policy: " + policy.getPolicyId());
+ }
String combiningAlgorithm = "-";
String id = "-";
String version = "-";
-
- if (policy.getRuleCombiningAlgId() != null)
+ if (policy.getRuleCombiningAlgId() != null) {
combiningAlgorithm = extractLastIdentifier(policy.getRuleCombiningAlgId(), ":");
+ }
- if (policy.getPolicyId() != null)
+ if (policy.getPolicyId() != null) {
id = extractLastIdentifier(policy.getPolicyId(), ":");
+ }
- if (policy.getVersion() != null)
+ if (policy.getVersion() != null) {
version = policy.getVersion();
+ }
htmlOut.println("<li><b>Policy ID</b>: <i>" + id + "</i> (v" + version + ") " + "</li>");
@@ -460,8 +498,7 @@ class HtmlProcessor extends SimpleCallback {
htmlOut.print("<p>");
htmlOut.print("This policy applies to requests with attributes ");
- List<AnyOfType> anyOf_s = policy.getTarget().getAnyOf();
- target(anyOf_s);
+ target(policy.getTarget().getAnyOf());
htmlOut.println(".</p>");
}
@@ -477,14 +514,15 @@ class HtmlProcessor extends SimpleCallback {
}
}
-
@Override
public CallbackResult onPreVisitRule(PolicyType parent, RuleType rule) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Rule: " + rule.getRuleId());
+ }
- if (parent != null && LOGGER.isTraceEnabled())
+ if (parent != null && LOGGER.isTraceEnabled()) {
LOGGER.trace("Parent Policy: " + parent.getPolicyId() + " Version: " + parent.getVersion());
+ }
String description = rule.getDescription();
if (description != null && LOGGER.isTraceEnabled()) {
@@ -498,23 +536,21 @@ class HtmlProcessor extends SimpleCallback {
@Override
public CallbackResult onPostVisitRule(PolicyType parent, RuleType rule) {
- if (LOGGER.isTraceEnabled())
- LOGGER.trace("Rule: " + rule.getRuleId());
- if (parent != null && LOGGER.isTraceEnabled())
+ if (parent != null && LOGGER.isTraceEnabled()) {
LOGGER.trace("Parent Policy: " + parent.getPolicyId() + " Version: " + parent.getVersion());
+ }
return super.onPostVisitRule(parent, rule);
}
public void rule(RuleType rule) {
- if (LOGGER.isTraceEnabled())
- LOGGER.trace("Rule: " + rule.getRuleId());
String id = "-";
- if (rule.getRuleId() != null)
+ if (rule.getRuleId() != null) {
id = extractLastIdentifier(rule.getRuleId(), ":");
+ }
htmlOut.println("<li><b>Rule ID</b>: <i>" + id + "</i></li>");
@@ -526,9 +562,8 @@ class HtmlProcessor extends SimpleCallback {
if (rule.getTarget() == null || rule.getTarget().getAnyOf() == null || rule.getTarget().getAnyOf().isEmpty()) {
htmlOut.print(" for all requests");
} else {
- List<AnyOfType> anyOf_s = rule.getTarget().getAnyOf();
htmlOut.print(" for requests with attributes ");
- target(anyOf_s);
+ target(rule.getTarget().getAnyOf());
}
if (rule.getCondition() != null) {
@@ -540,8 +575,9 @@ class HtmlProcessor extends SimpleCallback {
if (rule.getAdviceExpressions() != null) {
advice(rule.getAdviceExpressions());
- if (rule.getObligationExpressions() != null)
+ if (rule.getObligationExpressions() != null) {
htmlOut.println(" and ");
+ }
}
if (rule.getObligationExpressions() != null) {
@@ -552,8 +588,9 @@ class HtmlProcessor extends SimpleCallback {
}
private void advice(AdviceExpressionsType adviceExpressions) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace(ENTER);
+ }
List<AdviceExpressionType> ae = adviceExpressions.getAdviceExpression();
for (AdviceExpressionType expression : ae) {
@@ -569,8 +606,9 @@ class HtmlProcessor extends SimpleCallback {
}
private void obligation(ObligationExpressionsType obligationExpressions) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace(ENTER);
+ }
List<ObligationExpressionType> oe = obligationExpressions.getObligationExpression();
for (ObligationExpressionType expression : oe) {
@@ -586,11 +624,14 @@ class HtmlProcessor extends SimpleCallback {
}
/**
- * @param assignments
+ * processAttributeAssignments.
+ *
+ * @param assignments List of AttributeAssignmentExpressionType
*/
private void processAttributeAssignments(List<AttributeAssignmentExpressionType> assignments) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace(ENTER);
+ }
for (AttributeAssignmentExpressionType assignment : assignments) {
String succintIdentifier = extractLastIdentifier(assignment.getCategory(), ":") + ":"
@@ -620,8 +661,9 @@ class HtmlProcessor extends SimpleCallback {
for (Object c : avt.getContent()) {
countContent++;
htmlOut.print("<i>" + c + "</i>");
- if (countContent < numContent)
+ if (countContent < numContent) {
htmlOut.print(" or ");
+ }
}
htmlOut.println("</li>");
} else if (assignmentObject instanceof AttributeDesignatorType
@@ -634,118 +676,118 @@ class HtmlProcessor extends SimpleCallback {
}
/**
- *
- * @param anyOfList
+ * target.
+ *
+ * @param anyOfList List of AnyOfType's
*/
public void target(List<AnyOfType> anyOfList) {
- if (LOGGER.isTraceEnabled())
+ if (LOGGER.isTraceEnabled()) {
LOGGER.trace(ENTER);
+ }
- if (anyOfList != null) {
- Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
- StringBuilder targetInHuman = new StringBuilder();
- while (iterAnyOf.hasNext()) {
- AnyOfType anyOf = iterAnyOf.next();
- List<AllOfType> allOfList = anyOf.getAllOf();
- if (allOfList != null) {
- Iterator<AllOfType> iterAllOf = allOfList.iterator();
- while (iterAllOf.hasNext()) {
- AllOfType allOf = iterAllOf.next();
- List<MatchType> matchList = allOf.getMatch();
- if (matchList != null) {
- Iterator<MatchType> iterMatch = matchList.iterator();
- if (matchList.size() > 1)
- targetInHuman.append("(");
- while (iterMatch.hasNext()) {
- MatchType match = iterMatch.next();
- //
- // Finally down to the actual attribute
- //
- StdAttribute attribute = null;
- AttributeValueType value = match.getAttributeValue();
- String attributeDataType;
- if (match.getAttributeDesignator() != null && value != null) {
- AttributeDesignatorType designator = match.getAttributeDesignator();
- attribute = new StdAttribute(new IdentifierImpl(designator.getCategory()),
- new IdentifierImpl(designator.getAttributeId()),
- new StdAttributeValue<List<?>>(new IdentifierImpl(value.getDataType()),
- value.getContent()),
- designator.getIssuer(), false);
- attributeDataType = designator.getDataType();
- } else if (match.getAttributeSelector() != null && value != null) {
- AttributeSelectorType selector = match.getAttributeSelector();
- attribute = new StdAttribute(new IdentifierImpl(selector.getCategory()),
- new IdentifierImpl(selector.getContextSelectorId()),
- new StdAttributeValue<List<?>>(new IdentifierImpl(value.getDataType()),
- value.getContent()),
- null, false);
- attributeDataType = selector.getDataType();
- } else {
- LOGGER.warn("NULL designator/selector or value for match.");
- attributeDataType = "NA";
- }
+ if (anyOfList == null) {
+ return;
+ }
+ Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
+ StringBuilder targetInHuman = new StringBuilder();
+ while (iterAnyOf.hasNext()) {
+ AnyOfType anyOf = iterAnyOf.next();
+ List<AllOfType> allOfList = anyOf.getAllOf();
+ Iterator<AllOfType> iterAllOf = allOfList.iterator();
+ while (iterAllOf.hasNext()) {
+ AllOfType allOf = iterAllOf.next();
+ List<MatchType> matchList = allOf.getMatch();
+ Iterator<MatchType> iterMatch = matchList.iterator();
+ if (matchList.size() > 1) {
+ targetInHuman.append("(");
+ }
+ while (iterMatch.hasNext()) {
+ MatchType match = iterMatch.next();
+ //
+ // Finally down to the actual attribute
+ //
+ StdAttribute attribute = null;
+ AttributeValueType value = match.getAttributeValue();
+ String attributeDataType;
+ if (match.getAttributeDesignator() != null && value != null) {
+ AttributeDesignatorType designator = match.getAttributeDesignator();
+ attribute = new StdAttribute(new IdentifierImpl(designator.getCategory()),
+ new IdentifierImpl(designator.getAttributeId()),
+ new StdAttributeValue<List<?>>(new IdentifierImpl(value.getDataType()),
+ value.getContent()),
+ designator.getIssuer(), false);
+ attributeDataType = designator.getDataType();
+ } else if (match.getAttributeSelector() != null && value != null) {
+ AttributeSelectorType selector = match.getAttributeSelector();
+ attribute = new StdAttribute(new IdentifierImpl(selector.getCategory()),
+ new IdentifierImpl(selector.getContextSelectorId()),
+ new StdAttributeValue<List<?>>(new IdentifierImpl(value.getDataType()),
+ value.getContent()),
+ null, false);
+ attributeDataType = selector.getDataType();
+ } else {
+ LOGGER.warn("NULL designator/selector or value for match.");
+ attributeDataType = "NA";
+ }
- String functionName = getHumanFunction(match.getMatchId());
- if (attribute != null) {
- String succintIdentifier = extractLastIdentifier(
- attribute.getCategory().stringValue(), ":") + ":"
- + extractLastIdentifier(attribute.getAttributeId().stringValue(), ":");
- AttributeIdentifiers ai =
- new AttributeIdentifiers(attribute.getCategory().stringValue(),
- attributeDataType, attribute.getAttributeId().stringValue());
- this.attributeIdentifiersMap.put(succintIdentifier, ai);
-
- targetInHuman.append("<i><a href=\"#" + succintIdentifier + "\">"
- + succintIdentifier + "</a></i> " + functionName + " ");
-
- int numAttributes = attribute.getValues().size();
- int count = 0;
- for (AttributeValue<?> v : attribute.getValues()) {
- count++;
- if (v.getValue() instanceof Collection<?>) {
- Collection<?> value_s = (Collection<?>) v.getValue();
- int numValues = value_s.size();
- int countValues = 0;
- for (Object o : value_s) {
- countValues++;
- targetInHuman.append(" <I>" + o + "</I>");
- if (countValues < numValues) {
- targetInHuman.append(", or");
- }
- }
- } else {
- targetInHuman.append(" <I>" + v.getValue() + "</I>");
- if (count < numAttributes) {
- targetInHuman.append(", or ");
- }
- }
+ String functionName = getHumanFunction(match.getMatchId());
+ if (attribute != null) {
+ String succintIdentifier = extractLastIdentifier(
+ attribute.getCategory().stringValue(), ":") + ":"
+ + extractLastIdentifier(attribute.getAttributeId().stringValue(), ":");
+ AttributeIdentifiers ai =
+ new AttributeIdentifiers(attribute.getCategory().stringValue(),
+ attributeDataType, attribute.getAttributeId().stringValue());
+ this.attributeIdentifiersMap.put(succintIdentifier, ai);
+
+ targetInHuman.append("<i><a href=\"#" + succintIdentifier + "\">"
+ + succintIdentifier + "</a></i> " + functionName + " ");
+
+ int numAttributes = attribute.getValues().size();
+ int count = 0;
+ for (AttributeValue<?> v : attribute.getValues()) {
+ count++;
+ if (v.getValue() instanceof Collection<?>) {
+ Collection<?> collectionValues = (Collection<?>) v.getValue();
+ int numValues = collectionValues.size();
+ int countValues = 0;
+ for (Object o : collectionValues) {
+ countValues++;
+ targetInHuman.append(" <I>" + o + "</I>");
+ if (countValues < numValues) {
+ targetInHuman.append(", or");
}
}
-
- if (iterMatch.hasNext()) {
- targetInHuman.append(" and ");
+ } else {
+ targetInHuman.append(" <I>" + v.getValue() + "</I>");
+ if (count < numAttributes) {
+ targetInHuman.append(", or ");
}
- } // end iterMatch
- if (matchList.size() > 1) {
- targetInHuman.append(")");
}
}
- if (iterAllOf.hasNext()) {
- targetInHuman.append(" or ");
- }
- } // end iterAllOf
- }
- if (iterAnyOf.hasNext()) {
- targetInHuman = new StringBuilder();
- targetInHuman.append("(" + targetInHuman + ")" + " or ");
- } else {
- if (anyOfList.size() > 1) {
- targetInHuman.append(")");
}
+
+ if (iterMatch.hasNext()) {
+ targetInHuman.append(" and ");
+ }
+ } // end iterMatch
+ if (matchList.size() > 1) {
+ targetInHuman.append(")");
}
- } // end iterAnyOf
- htmlOut.println(targetInHuman);
+ }
+ if (iterAllOf.hasNext()) {
+ targetInHuman.append(" or ");
+ }
+ } // end iterAllOf
+ if (iterAnyOf.hasNext()) {
+ targetInHuman = new StringBuilder();
+ targetInHuman.append("(" + targetInHuman + ")" + " or ");
+ } else {
+ if (anyOfList.size() > 1) {
+ targetInHuman.append(")");
+ }
}
+ htmlOut.println(targetInHuman);
}
private String getHumanFunction(String matchId) {
@@ -815,12 +857,12 @@ class HtmlProcessor extends SimpleCallback {
} else {
StringBuilder forResult = new StringBuilder();
for (JAXBElement<?> e : exps) {
- Object v = e.getValue();
+ Object theValue = e.getValue();
if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("one-and-only children: " + v);
+ LOGGER.debug("one-and-only children: " + theValue);
}
- if (v != null) {
- forResult.append(stringifyExpression(v));
+ if (theValue != null) {
+ forResult.append(stringifyExpression(theValue));
}
}
return forResult.toString();
@@ -840,8 +882,8 @@ class HtmlProcessor extends SimpleCallback {
}
StringBuilder applySubresult = new StringBuilder();
for (JAXBElement<?> e : apply.getExpression()) {
- Object v = e.getValue();
- if (v != null) {
+ Object theValue = e.getValue();
+ if (theValue != null) {
applySubresult.append(this.stringifyExpression(e.getValue()));
}
}
@@ -906,11 +948,12 @@ class HtmlProcessor extends SimpleCallback {
if (expression instanceof AttributeValueType) {
AttributeValueType avt = (AttributeValueType) expression;
List<Object> content = avt.getContent();
- StringBuilder value_s = new StringBuilder();
+ StringBuilder stringValue = new StringBuilder(" ");
for (Object o : content) {
- value_s.append(" " + o.toString());
+ stringValue.append(" ");
+ stringValue.append(o.toString());
}
- return " " + value_s.toString();
+ return stringValue.toString();
}
if (expression instanceof VariableReferenceType) {
//
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/conf/HibernateSession.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/conf/HibernateSession.java
index 0e1be9349..ef6b98803 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/conf/HibernateSession.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/conf/HibernateSession.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.
@@ -32,44 +32,43 @@ import org.hibernate.cfg.Configuration;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.controller.PolicyController;
-import org.onap.policy.rest.jpa.SystemLogDB;
+import org.onap.policy.rest.jpa.SystemLogDb;
@SuppressWarnings("deprecation")
-public class HibernateSession{
+public class HibernateSession {
- private static final Logger LOGGER = FlexLogger.getLogger(HibernateSession.class);
-
- private static SessionFactory logSessionFactory;
-
- static {
- try {
- Properties prop= new Properties();
- prop.setProperty("hibernate.connection.url", PolicyController.getLogdbUrl());
- prop.setProperty("hibernate.connection.username", PolicyController.getLogdbUserName());
- prop.setProperty("hibernate.connection.password", PolicyController.getLogdbPassword());
- prop.setProperty("dialect", PolicyController.getLogdbDialect());
- prop.setProperty("hibernate.connection.driver_class", PolicyController.getLogdbDriver());
- prop.setProperty("show_sql", "false");
- logSessionFactory = new Configuration().addPackage("org.onap.policy.*").addProperties(prop)
- .addAnnotatedClass(SystemLogDB.class).buildSessionFactory();
- } catch (Exception ex) {
- LOGGER.error("Exception Occured while creating Log database Hibernate session"+ex);
- }
- }
+ private static final Logger LOGGER = FlexLogger.getLogger(HibernateSession.class);
- private HibernateSession(){
- /**
- empty implementation
- */
- }
+ private static SessionFactory logSessionFactory;
- public static Session getSession(){
- return logSessionFactory.openSession();
- }
-
- public static void setSession(SessionFactory logSessionFactory1){
- logSessionFactory = logSessionFactory1;
- }
+ static {
+ try {
+ Properties prop = new Properties();
+ prop.setProperty("hibernate.connection.url", PolicyController.getLogdbUrl());
+ prop.setProperty("hibernate.connection.username", PolicyController.getLogdbUserName());
+ prop.setProperty("hibernate.connection.password", PolicyController.getLogdbPassword());
+ prop.setProperty("dialect", PolicyController.getLogdbDialect());
+ prop.setProperty("hibernate.connection.driver_class", PolicyController.getLogdbDriver());
+ prop.setProperty("show_sql", "false");
+ logSessionFactory = new Configuration().addPackage("org.onap.policy.*").addProperties(prop)
+ .addAnnotatedClass(SystemLogDb.class).buildSessionFactory();
+ } catch (Exception ex) {
+ LOGGER.error("Exception Occured while creating Log database Hibernate session" + ex);
+ }
+ }
+ private HibernateSession() {
+ /**
+ * empty implementation
+ */
+ }
+
+ public static Session getSession() {
+ return logSessionFactory.openSession();
+ }
+
+ public static void setSession(SessionFactory logSessionFactory1) {
+ logSessionFactory = logSessionFactory1;
+ }
}
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 578258403..666923b43 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
@@ -2,15 +2,15 @@
* ============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.
* 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.
@@ -27,32 +27,28 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
-
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.portalsdk.core.controller.RestrictedBaseController;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
-
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.ApplyType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
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.ConditionType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
+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.portalsdk.core.controller.RestrictedBaseController;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
@Controller
-@RequestMapping({ "/" })
+@RequestMapping({"/"})
public class ActionPolicyController extends RestrictedBaseController {
private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicyController.class);
private static final String PERFORMER_ATTRIBUTE_ID = "performer";
@@ -66,41 +62,47 @@ public class ActionPolicyController extends RestrictedBaseController {
// Default Constructor
}
+ /**
+ * prePopulateActionPolicyData.
+ *
+ * @param policyAdapter PolicyRestAdapter
+ */
public void prePopulateActionPolicyData(PolicyRestAdapter policyAdapter) {
ruleAlgorithmList = new ArrayList<>();
performer.put("PDP", "PDPAction");
performer.put("PEP", "PEPAction");
- if (policyAdapter.getPolicyData() instanceof PolicyType) {
- PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
+ if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+ return;
+ }
+ PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
- // 1. Set policy-name, policy-filename and description to Policy Adapter
- setPolicyAdapterPolicyNameAndDesc(policyAdapter, policy);
+ // 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) {
- return;
- }
+ // 2a. Get the target data under policy for Action.
+ TargetType target = policy.getTarget();
+ if (target == null) {
+ return;
+ }
- // 2b. Set attributes to Policy Adapter
- setPolicyAdapterAttributes(policyAdapter, target.getAnyOf());
+ // 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)) {
+ continue;
+ }
+ // 3. Set rule-algorithm choices to Policy Adapter
+ setPolicyAdapterRuleAlgorithmschoices(policyAdapter, (RuleType) o);
- // 4a. Get the Obligation data under the rule for Form elements.
- ObligationExpressionsType obligations = ((RuleType) o).getObligationExpressions();
+ // 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);
- }
+ // 4b. Set action attribute-value and action-performer to Policy Adapter
+ setPolicyAdapterActionData(policyAdapter, obligations);
}
}
@@ -109,22 +111,23 @@ public class ActionPolicyController extends RestrictedBaseController {
return;
}
// Under the obligationExpressions we have obligationExpression.
- List<ObligationExpressionType> obligationList = obligations.getObligationExpression();
- if (obligationList == null) {
- return;
- }
- for (ObligationExpressionType obligation : obligationList) {
+ // NOTE: getObligationExpression() will never return NULL.
+ //
+ for (ObligationExpressionType obligation : obligations.getObligationExpression()) {
policyAdapter.setActionAttributeValue(obligation.getObligationId());
// Under the obligationExpression we have attributeAssignmentExpression.
- List<AttributeAssignmentExpressionType> attributeAssignmentExpressionList = obligation
- .getAttributeAssignmentExpression();
- if (attributeAssignmentExpressionList == null) {
- continue;
- }
- for (AttributeAssignmentExpressionType attributeAssignmentExpression : attributeAssignmentExpressionList) {
+ //
+ // NOTE: obligation.getAttributeAssignmentExpression() will NEVER be null
+ // It will always return a list.
+ //
+ for (AttributeAssignmentExpressionType attributeAssignmentExpression :
+ obligation.getAttributeAssignmentExpression()) {
+ //
+ //
+ //
String attributeID = attributeAssignmentExpression.getAttributeId();
- AttributeValueType attributeValue = (AttributeValueType) attributeAssignmentExpression
- .getExpression().getValue();
+ AttributeValueType attributeValue =
+ (AttributeValueType) attributeAssignmentExpression.getExpression().getValue();
if (!attributeID.equals(PERFORMER_ATTRIBUTE_ID)) {
continue;
}
@@ -139,8 +142,8 @@ public class ActionPolicyController extends RestrictedBaseController {
private void setPolicyAdapterPolicyNameAndDesc(PolicyRestAdapter policyAdapter, PolicyType policy) {
policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
- String policyNameValue = policyAdapter.getPolicyName()
- .substring(policyAdapter.getPolicyName().indexOf('_') + 1);
+ String policyNameValue =
+ policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf('_') + 1);
policyAdapter.setPolicyName(policyNameValue);
String description;
try {
@@ -152,11 +155,10 @@ public class ActionPolicyController extends RestrictedBaseController {
policyAdapter.setPolicyDescription(description);
}
- private void setPolicyAdapterRuleAlgorithmschoices(PolicyRestAdapter policyAdapter, RuleType o) {
- ConditionType condition = o.getCondition();
- if (condition != null) {
+ private void setPolicyAdapterRuleAlgorithmschoices(PolicyRestAdapter policyAdapter, RuleType ruleType) {
+ if (ruleType.getCondition() != null) {
int index = 0;
- ApplyType actionApply = (ApplyType) condition.getExpression().getValue();
+ ApplyType actionApply = (ApplyType) ruleType.getCondition().getExpression().getValue();
ruleAlgorithmTracker = new LinkedList<>();
// Populating Rule Algorithms starting from compound.
prePopulateCompoundRuleAlgorithm(index, actionApply);
@@ -166,36 +168,43 @@ public class ActionPolicyController extends RestrictedBaseController {
private void setPolicyAdapterAttributes(PolicyRestAdapter policyAdapter, List<AnyOfType> anyOfList) {
List<Object> attributeList = new ArrayList<>();
- if (anyOfList == null) {
- return;
- }
+ //
+ // NOTE: If using xacml3 code and doing a getAnyOf(), the anyOfList will
+ // NEVER be null as that code will create it if it is null.
+ //
+ // Remove the null check as its impossible to cover it.
+ //
// under target we have AnyOFType
for (AnyOfType anyOf : anyOfList) {
// Under AntOfType we have AllOfType
+ //
+ // NOTE: This will NEVER be null as the method call in the
+ // previous line getAllOf() will never return a null. It
+ // always creates it if its empty.
+ //
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);
- });
+ //
+ // NOTE: allOfType.getMatch() will NEVER be null as the method
+ // call getMatch will always return something. If its
+ // not there it will create it.
+ //
+ //
+ // 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.
+ for (MatchType match : allOfType.getMatch()) {
+ 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);
}
@@ -211,41 +220,41 @@ public class ActionPolicyController extends RestrictedBaseController {
LOGGER.debug("Prepopulating rule algoirthm: " + index);
}
// Check to see if Attribute Value exists, if yes then it is not a compound rule
- if (jaxbElement.getValue() instanceof AttributeValueType) {
+ if (jaxbElement.getValue() instanceof AttributeValueType
+ || jaxbElement.getValue() instanceof AttributeDesignatorType) {
prePopulateRuleAlgorithms(index, actionApply, jaxbActionTypes);
ruleAlgorithmTracker.addLast(index);
isCompoundRule = false;
index++;
}
}
- if (isCompoundRule) {
- // As it's compound rule, Get the Apply types
- for (JAXBElement<?> jaxbElement : jaxbActionTypes) {
- ApplyType innerActionApply = (ApplyType) jaxbElement.getValue();
- index = prePopulateCompoundRuleAlgorithm(index, innerActionApply);
- }
- // Populate combo box
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("Prepopulating Compound rule algorithm: " + index);
- }
- Map<String, String> rule = new HashMap<>();
- for (String key : PolicyController.getDropDownMap().keySet()) {
- String keyValue = PolicyController.getDropDownMap().get(key);
- if (keyValue.equals(actionApply.getFunctionId())) {
- rule.put("dynamicRuleAlgorithmCombo", key);
- }
+ if (!isCompoundRule) {
+ return index;
+ }
+ // As it's compound rule, Get the Apply types
+ for (JAXBElement<?> jaxbElement : jaxbActionTypes) {
+ ApplyType innerActionApply = (ApplyType) jaxbElement.getValue();
+ index = prePopulateCompoundRuleAlgorithm(index, innerActionApply);
+ }
+ // Populate combo box
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("Prepopulating Compound rule algorithm: " + index);
+ }
+ Map<String, String> rule = new HashMap<>();
+ for ( Entry<String, String> entrySet : PolicyController.getDropDownMap().entrySet()) {
+ if (entrySet.getValue().equals(actionApply.getFunctionId())) {
+ rule.put("dynamicRuleAlgorithmCombo", entrySet.getKey());
}
- rule.put("id", "A" + (index + 1));
- // Populate Key and values for Compound Rule
- 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++;
}
- return index;
+ rule.put("id", "A" + (index + 1));
+ // Populate Key and values for Compound Rule
+ 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);
+ return ++index;
}
private void prePopulateRuleAlgorithms(int index, ApplyType actionApply, List<JAXBElement<?>> jaxbActionTypes) {
@@ -253,7 +262,7 @@ public class ActionPolicyController extends RestrictedBaseController {
ruleMap.put("id", "A" + (index + 1));
// Populate combo box
Map<String, String> dropDownMap = PolicyController.getDropDownMap();
- for ( Entry<String, String> entry : dropDownMap.entrySet()) {
+ for (Entry<String, String> entry : dropDownMap.entrySet()) {
if (entry.getValue().equals(actionApply.getFunctionId())) {
ruleMap.put("dynamicRuleAlgorithmCombo", entry.getKey());
}
@@ -264,8 +273,8 @@ public class ActionPolicyController extends RestrictedBaseController {
// Get from Attribute Designator
ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(0).getValue();
List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression();
- AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0)
- .getValue();
+ AttributeDesignatorType attributeDesignator =
+ (AttributeDesignatorType) jaxbInnerActionTypes.get(0).getValue();
ruleMap.put(DYNAMIC_RULE_ALGORITHM_FIELD_1, attributeDesignator.getAttributeId());
// Get from Attribute Value
@@ -279,11 +288,20 @@ public class ActionPolicyController extends RestrictedBaseController {
String attributeValue = (String) actionConditionAttributeValue.getContent().get(0);
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(DYNAMIC_RULE_ALGORITHM_FIELD_1, attributeDesignator.getAttributeId());
+ //
+ // This is making a BIG assumption here that there exists an innerApply. This IF
+ // statement was added to support JUnit code coverage. For lack of any example of what
+ // this policy should actually look like.
+ //
+ if (jaxbActionTypes.size() > 1) {
+ ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(1).getValue();
+ List<JAXBElement<?>> jaxbInnerActionTypes = innerActionApply.getExpression();
+ if (! jaxbInnerActionTypes.isEmpty()) {
+ AttributeDesignatorType attributeDesignator =
+ (AttributeDesignatorType) jaxbInnerActionTypes.get(0).getValue();
+ 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 fc25e29f0..139b2b87f 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
@@ -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.
* Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -21,8 +21,11 @@
package org.onap.policy.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.util.HashMap;
import java.util.Map;
@@ -44,21 +47,16 @@ import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
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
@RequestMapping({"/"})
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
+ // default constructor
}
@Autowired
@@ -74,57 +72,66 @@ public class AdminTabController extends RestrictedBaseController {
AdminTabController.commonClassDao = commonClassDao;
}
- @RequestMapping(value = {"/get_LockDownData"}, method = {
- org.springframework.web.bind.annotation.RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE)
+ /**
+ * getAdminTabEntityData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ @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());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
LOGGER.error("Exception Occured" + e);
}
}
- @RequestMapping(value = {"/adminTabController/save_LockDownValue.htm"}, method = {
- org.springframework.web.bind.annotation.RequestMethod.POST})
+ /**
+ * saveAdminTabLockdownValue.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @return ModelAndView object
+ * @throws IOException IOException
+ */
+ @RequestMapping(
+ value = {"/adminTabController/save_LockDownValue.htm"},
+ method = {org.springframework.web.bind.annotation.RequestMethod.POST})
public ModelAndView saveAdminTabLockdownValue(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ throws IOException {
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
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*****************************************");
+ "********************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);
+ 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);
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
- PrintWriter out = response.getWriter();
String responseString = mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class));
- JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}");
-
- out.write(j.toString());
- return null;
+ response.getWriter().write(new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString
+ + "}").toString());
} 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);
+ response.getWriter().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 a42d3d8d7..dc342eeed 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
@@ -26,12 +26,11 @@ import com.att.research.xacml.api.pap.PDPPolicy;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
-import java.io.PrintWriter;
-import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -45,9 +44,11 @@ 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;
+
import org.json.JSONObject;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
@@ -57,7 +58,7 @@ import org.onap.policy.rest.adapter.AutoPushTabAdapter;
import org.onap.policy.rest.dao.CommonClassDao;
import org.onap.policy.rest.jpa.PolicyEntity;
import org.onap.policy.rest.jpa.PolicyVersion;
-import org.onap.policy.rest.util.PDPPolicyContainer;
+import org.onap.policy.rest.util.PdpPolicyContainer;
import org.onap.policy.utils.PolicyUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.policy.xacml.api.pap.OnapPDPGroup;
@@ -78,13 +79,12 @@ import org.springframework.web.servlet.ModelAndView;
public class AutoPushController extends RestrictedBaseController {
private static final Logger logger = FlexLogger.getLogger(AutoPushController.class);
- private static final String UTF8 = "UTF-8";
@Autowired
CommonClassDao commonClassDao;
private PDPGroupContainer container;
- private PDPPolicyContainer policyContainer;
+ private PdpPolicyContainer policyContainer;
private PolicyController policyController;
protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<>());
@@ -96,6 +96,9 @@ public class AutoPushController extends RestrictedBaseController {
this.policyController = policyController;
}
+ /**
+ * refreshGroups.
+ */
public synchronized void refreshGroups() {
synchronized (this.groups) {
this.groups.clear();
@@ -121,7 +124,15 @@ public class AutoPushController extends RestrictedBaseController {
return scopes;
}
- @RequestMapping(value = {"/get_AutoPushPoliciesContainerData"}, method = {RequestMethod.GET},
+ /**
+ * getPolicyGroupContainerData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ @RequestMapping(
+ value = {"/get_AutoPushPoliciesContainerData"},
+ method = {RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response) {
try {
@@ -164,18 +175,30 @@ public class AutoPushController extends RestrictedBaseController {
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());
+ response.getWriter().write(new JSONObject(msg).toString());
} catch (Exception e) {
logger.error("Exception Occurred" + e);
}
}
+ /**
+ * pushPolicyToPDPGroup.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @return ModelAndView
+ * @throws IOException IOException
+ */
@RequestMapping(value = {"/auto_Push/PushPolicyToPDP.htm"}, method = {RequestMethod.POST})
public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response)
throws IOException {
try {
- ArrayList<Object> selectedPDPS = new ArrayList<>();
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ //
+ //
+ //
+ ArrayList<Object> selectedPdps = new ArrayList<>();
ArrayList<String> selectedPoliciesInUI = new ArrayList<>();
PolicyController controller = getPolicyControllerInstance();
this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
@@ -186,17 +209,17 @@ public class AutoPushController extends RestrictedBaseController {
String userId = UserUtils.getUserSession(request).getOrgUserId();
logger.info(
- "****************************************Logging UserID while Pushing Policy to PDP Group*****************************************");
+ "**********************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;
+ LinkedHashMap<?, ?> selectedPdp = (LinkedHashMap<?, ?>) pdpGroupId;
for (OnapPDPGroup pdpGroup : this.groups) {
- if (pdpGroup.getId().equals(selectedPDP.get("id"))) {
- selectedPDPS.add(pdpGroup);
+ if (pdpGroup.getId().equals(selectedPdp.get("id"))) {
+ selectedPdps.add(pdpGroup);
}
}
}
@@ -208,7 +231,7 @@ public class AutoPushController extends RestrictedBaseController {
selectedPoliciesInUI.add(policyName);
}
- for (Object pdpDestinationGroupId : selectedPDPS) {
+ for (Object pdpDestinationGroupId : selectedPdps) {
Set<PDPPolicy> currentPoliciesInGroup = new HashSet<>();
Set<PDPPolicy> selectedPolicies = new HashSet<>();
for (String policyId : selectedPoliciesInUI) {
@@ -254,10 +277,9 @@ public class AutoPushController extends RestrictedBaseController {
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);
+ selectedPolicy = new StdPDPPolicy(name, true, id, temp.toURI());
} catch (IOException e) {
logger.error("Unable to create policy '" + name + "': " + e.getMessage(), e);
}
@@ -271,7 +293,7 @@ public class AutoPushController extends RestrictedBaseController {
}
// copy policy to PAP
try {
- controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
+ controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId, userId);
} catch (PAPException e) {
logger.error("Exception Occured" + e);
return null;
@@ -315,53 +337,47 @@ public class AutoPushController extends RestrictedBaseController {
currentPoliciesInGroup.addAll(selectedPolicies);
updatedGroupObject.setPolicies(currentPoliciesInGroup);
this.container.updateGroup(updatedGroupObject, userId);
-
- response.setCharacterEncoding(UTF8);
- response.setContentType("application / json");
- request.setCharacterEncoding(UTF8);
-
- PrintWriter out = response.getWriter();
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
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;
+ response.getWriter().write(new JSONObject(
+ new JsonMessage(mapper.writeValueAsString(groups))).toString());
}
} catch (Exception e) {
- response.setCharacterEncoding(UTF8);
- request.setCharacterEncoding(UTF8);
- PrintWriter out = response.getWriter();
logger.error(e);
- out.write(PolicyUtils.CATCH_EXCEPTION);
+ response.getWriter().write(PolicyUtils.CATCH_EXCEPTION);
}
return null;
}
+ /**
+ * removePDPGroup.
+ */
@SuppressWarnings("unchecked")
@RequestMapping(value = {"/auto_Push/remove_GroupPolicies.htm"}, method = {RequestMethod.POST})
public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException {
try {
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ //
+ //
+ //
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");
+ final StdPDPGroup group = mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class);
+ final JsonNode removePolicyData = root.get("data");
String userId = UserUtils.getUserSession(request).getOrgUserId();
logger.info(
- "****************************************Logging UserID while Removing Policy from PDP Group*****************************************");
+ "**********************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);
+ 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));
@@ -374,27 +390,16 @@ public class AutoPushController extends RestrictedBaseController {
updatedGroupObject.setPipConfigs(group.getPipConfigs());
updatedGroupObject.setStatus(group.getStatus());
updatedGroupObject.setOperation("delete");
- this.container.updateGroup(updatedGroupObject);
+ this.container.updateGroup(updatedGroupObject, userId);
}
- response.setCharacterEncoding(UTF8);
- response.setContentType("application / json");
- request.setCharacterEncoding(UTF8);
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
- PrintWriter out = response.getWriter();
refreshGroups();
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
- JSONObject j = new JSONObject(msg);
-
- out.write(j.toString());
-
- return null;
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
} catch (Exception e) {
- response.setCharacterEncoding(UTF8);
- request.setCharacterEncoding(UTF8);
- PrintWriter out = response.getWriter();
logger.error(e);
- out.write(PolicyUtils.CATCH_EXCEPTION);
+ response.getWriter().write(PolicyUtils.CATCH_EXCEPTION);
}
return null;
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java
index 8c14048c4..143d675bf 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java
@@ -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.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
* Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
@@ -22,7 +22,10 @@
package org.onap.policy.controller;
-import java.io.PrintWriter;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -36,20 +39,32 @@ import java.util.Objects;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-
import java.util.stream.Collectors;
+
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBElement;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
+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.RuleType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
+
import org.apache.commons.collections.CollectionUtils;
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.rest.dao.CommonClassDao;
-import org.onap.policy.rest.jpa.BRMSParamTemplate;
+import org.onap.policy.rest.jpa.BrmsParamTemplate;
import org.onap.policy.rest.jpa.PolicyEntity;
+import org.onap.policy.utils.PolicyUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.portalsdk.core.controller.RestrictedBaseController;
import org.springframework.beans.factory.annotation.Autowired;
@@ -57,21 +72,6 @@ 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.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
-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.RuleType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
-
@Controller
@RequestMapping("/")
public class CreateBRMSParamController extends RestrictedBaseController {
@@ -104,8 +104,13 @@ public class CreateBRMSParamController extends RestrictedBaseController {
private static String brmsTemplateVlaue = "<$%BRMSParamTemplate=";
private static String string = "String";
-
- @RequestMapping(value = {"/policyController/getBRMSTemplateData.htm"}, method = { RequestMethod.POST})
+ /**
+ * getBRMSParamPolicyRuleData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ @RequestMapping(value = {"/policyController/getBRMSTemplateData.htm"}, method = {RequestMethod.POST})
public void getBRMSParamPolicyRuleData(HttpServletRequest request, HttpServletResponse response) {
try {
dynamicLayoutMap = new HashMap<>();
@@ -118,20 +123,17 @@ public class CreateBRMSParamController extends RestrictedBaseController {
response.setContentType(PolicyController.getContenttype());
request.setCharacterEncoding(PolicyController.getCharacterencoding());
- PrintWriter out = response.getWriter();
- String responseString = mapper.writeValueAsString(dynamicLayoutMap);
- JSONObject j = new JSONObject("{policyData: " + responseString + "}");
- out.write(j.toString());
+ response.getWriter().write(new JSONObject("{policyData: " + mapper.writeValueAsString(dynamicLayoutMap)
+ + "}").toString());
} catch (Exception e) {
policyLogger.error("Exception Occured while getting BRMS Rule data", e);
}
}
private String findRule(String ruleTemplate) {
- List<Object> datas = commonClassDao.getDataById(BRMSParamTemplate.class, "ruleName", ruleTemplate);
- if(CollectionUtils.isNotEmpty(datas)){
- BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate) datas.get(0);
- return bRMSParamTemplate.getRule();
+ List<Object> datas = commonClassDao.getDataById(BrmsParamTemplate.class, "ruleName", ruleTemplate);
+ if (CollectionUtils.isNotEmpty(datas)) {
+ return ((BrmsParamTemplate) datas.get(0)).getRule();
}
return null;
}
@@ -151,7 +153,7 @@ public class CreateBRMSParamController extends RestrictedBaseController {
private void processRule(String rule) {
StringBuilder params = getParamsBuilderFromRule(rule);
params = new StringBuilder(
- params.toString().replace("declare Params", "").replace("end", "").replaceAll("\\s+", ""));
+ params.toString().replace("declare Params", "").replace("end", "").replaceAll("\\s+", ""));
String[] components = params.toString().split(":");
String caption = "";
for (int i = 0; i < components.length; i++) {
@@ -243,79 +245,85 @@ public class CreateBRMSParamController extends RestrictedBaseController {
dynamicLayoutMap.put(caption, type);
}
- /*
- * When the User Click Edit or View Policy the following method will get invoked for setting the data to PolicyRestAdapter.
- * Which is used to bind the data in GUI
+ /**
+ * prePopulateBRMSParamPolicyData.
+ * When the User Click Edit or View Policy the following method will get invoked for setting the data to
+ * PolicyRestAdapter.
+ * Which is used to bind the data in GUI.
+ *
+ * @param policyAdapter PolicyRestAdapter
+ * @param entity PolicyEntity
*/
public void prePopulateBRMSParamPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
dynamicLayoutMap = new HashMap<>();
- if (policyAdapter.getPolicyData() instanceof PolicyType) {
- PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
- policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
- // policy name value is the policy name without any prefix and
- // Extensions.
- String policyNameValue = policyAdapter.getPolicyName()
- .substring(policyAdapter.getPolicyName().indexOf("BRMS_Param_") + 11);
- if (policyLogger.isDebugEnabled()) {
- policyLogger
+ if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+ return;
+ }
+ PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
+ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+ // policy name value is the policy name without any prefix and
+ // Extensions.
+ String policyNameValue =
+ policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Param_") + 11);
+ if (policyLogger.isDebugEnabled()) {
+ policyLogger
.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName());
- }
- policyAdapter.setPolicyName(policyNameValue);
- String description;
- try {
- description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
- } catch (Exception e) {
- policyLogger.info("Error getting description: " + e);
- description = policy.getDescription();
- }
- policyAdapter.setPolicyDescription(description);
- setDataAdapterFromAdviceExpressions(policy, policyAdapter);
+ }
+ policyAdapter.setPolicyName(policyNameValue);
+ String description;
+ try {
+ description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+ } catch (Exception e) {
+ policyLogger.info("Error getting description: " + e);
+ description = policy.getDescription();
+ }
+ policyAdapter.setPolicyDescription(description);
+ setDataAdapterFromAdviceExpressions(policy, policyAdapter);
- // Generate Param UI
- try {
- paramUIGenerate(policyAdapter, entity);
- } catch (Exception e) {
- policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e);
- }
+ // Generate Param UI
+ try {
+ paramUiGenerate(policyAdapter, entity);
+ } catch (Exception e) {
+ policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e);
+ }
- // Get the target data under policy.
- policyAdapter.setDynamicLayoutMap(dynamicLayoutMap);
- if (policyAdapter.getDynamicLayoutMap().size() > 0) {
- LinkedHashMap<String, String> drlRule = policyAdapter.getDynamicLayoutMap()
- .keySet().stream()
- .collect(Collectors
- .toMap(String::toString, keyValue -> policyAdapter.getDynamicLayoutMap().get(keyValue),
- (a, b) -> b, LinkedHashMap::new));
- policyAdapter.setRuleData(drlRule);
- }
- TargetType target = policy.getTarget();
- if (target != null) {
- setDataToAdapterFromTarget(target, policyAdapter);
- }
+ // Get the target data under policy.
+ policyAdapter.setDynamicLayoutMap(dynamicLayoutMap);
+ if (policyAdapter.getDynamicLayoutMap().size() > 0) {
+ LinkedHashMap<String, String> drlRule = policyAdapter.getDynamicLayoutMap().keySet().stream()
+ .collect(Collectors.toMap(String::toString,
+ keyValue -> policyAdapter.getDynamicLayoutMap().get(keyValue), (a, b) -> b,
+ LinkedHashMap::new));
+ policyAdapter.setRuleData(drlRule);
+ }
+ TargetType target = policy.getTarget();
+ if (target != null) {
+ setDataToAdapterFromTarget(target, policyAdapter);
}
}
private void setDataAdapterFromAdviceExpressions(PolicyType policy, PolicyRestAdapter policyAdapter) {
ArrayList<Object> attributeList = new ArrayList<>();
// Set Attributes.
- AdviceExpressionsType expressionTypes = ((RuleType) policy
- .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions();
+ AdviceExpressionsType expressionTypes =
+ ((RuleType) policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0))
+ .getAdviceExpressions();
for (AdviceExpressionType adviceExpression : expressionTypes.getAdviceExpression()) {
for (AttributeAssignmentExpressionType attributeAssignment : adviceExpression
- .getAttributeAssignmentExpression()) {
+ .getAttributeAssignmentExpression()) {
if (attributeAssignment.getAttributeId().startsWith("key:")) {
Map<String, String> attribute = new HashMap<>();
String key = attributeAssignment.getAttributeId().replace("key:", "");
attribute.put("key", key);
@SuppressWarnings("unchecked")
- JAXBElement<AttributeValueType> attributeValue = (JAXBElement<AttributeValueType>) attributeAssignment
- .getExpression();
+ JAXBElement<AttributeValueType> attributeValue =
+ (JAXBElement<AttributeValueType>) attributeAssignment.getExpression();
String value = (String) attributeValue.getValue().getContent().get(0);
attribute.put("value", value);
attributeList.add(attribute);
} else if (attributeAssignment.getAttributeId().startsWith("dependencies:")) {
- ArrayList<String> dependencies = new ArrayList<>(
- Arrays.asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(",")));
+ ArrayList<String> dependencies = new ArrayList<>(Arrays
+ .asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(",")));
dependencies.remove("");
policyAdapter.setBrmsDependency(dependencies);
} else if (attributeAssignment.getAttributeId().startsWith("controller:")) {
@@ -328,14 +336,11 @@ public class CreateBRMSParamController extends RestrictedBaseController {
private void setDataToAdapterFromTarget(TargetType target, PolicyRestAdapter policyAdapter) {
// Under target we have AnyOFType
- List<AnyOfType> anyOfList = target.getAnyOf();
- if (anyOfList == null) {
+ if (target.getAnyOf() == null) {
return;
}
- anyOfList.stream().map(AnyOfType::getAllOf)
- .filter(Objects::nonNull)
- .flatMap(Collection::stream)
- .forEach(allOf -> setDataToAdapterFromMatchList(allOf.getMatch(), policyAdapter));
+ target.getAnyOf().stream().map(AnyOfType::getAllOf).filter(Objects::nonNull).flatMap(Collection::stream)
+ .forEach(allOf -> setDataToAdapterFromMatchList(allOf.getMatch(), policyAdapter));
}
private void setDataToAdapterFromMatchList(List<MatchType> matchList, PolicyRestAdapter policyAdapter) {
@@ -351,25 +356,12 @@ public class CreateBRMSParamController extends RestrictedBaseController {
String value = (String) attributeValue.getContent().get(0);
AttributeDesignatorType designator = match.getAttributeDesignator();
String attributeId = designator.getAttributeId();
- 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);
- }
+ policyAdapter.setupUsingAttribute(attributeId, value);
}
}
// This method generates the UI from rule configuration
- private void paramUIGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+ private void paramUiGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
String data = entity.getConfigurationData().getConfigBody();
if (data == null) {
return;
@@ -390,8 +382,8 @@ public class CreateBRMSParamController extends RestrictedBaseController {
String value = line.substring(line.indexOf("<%$"), line.indexOf("$%>"));
value = value.replaceAll("<%\\$Values=", "");
Arrays.stream(value.split(":\\|:")).map(keyValue -> keyValue.split(":-:"))
- .filter(pair -> pair.length > 0)
- .forEach(pair -> dynamicLayoutMap.put(pair[0], (pair.length > 1) ? pair[1] : ""));
+ .filter(pair -> pair.length > 0)
+ .forEach(pair -> dynamicLayoutMap.put(pair[0], (pair.length > 1) ? pair[1] : ""));
return;
}
if (line.startsWith("/*")) {
@@ -429,32 +421,26 @@ public class CreateBRMSParamController extends RestrictedBaseController {
}
}
params = new StringBuilder(params.substring(params.indexOf(".Params\"") + 11));
- params = new StringBuilder(params.toString().replaceAll("\\s+", "")
- .replace("salience1000whenthenParamsparams=newParams();", "")
- .replace("insert(params);end", "")
- .replace("params.set", ""));
+ params = new StringBuilder(
+ params.toString().replaceAll("\\s+", "").replace("salience1000whenthenParamsparams=newParams();", "")
+ .replace("insert(params);end", "").replace("params.set", ""));
updateCaptionToDynamicLayoutMap(params);
}
private void updateCaptionToDynamicLayoutMap(final StringBuilder params) {
String[] components = params.toString().split("\\);");
- if(components.length > 0){
+ if (components.length > 0) {
for (int i = 0; i < components.length; i++) {
String value;
components[i] = components[i] + ")";
- String caption = components[i].substring(0,
- components[i].indexOf('('));
+ String caption = components[i].substring(0, components[i].indexOf('('));
caption = caption.substring(0, 1).toLowerCase() + caption.substring(1);
if (components[i].contains("(\"")) {
- value = components[i]
- .substring(components[i].indexOf("(\""),
- components[i].indexOf("\")"))
- .replace("(\"", "").replace("\")", "");
+ value = components[i].substring(components[i].indexOf("(\""), components[i].indexOf("\")"))
+ .replace("(\"", "").replace("\")", "");
} else {
- value = components[i]
- .substring(components[i].indexOf('('),
- components[i].indexOf(')'))
- .replace("(", "").replace(")", "");
+ value = components[i].substring(components[i].indexOf('('), components[i].indexOf(')'))
+ .replace("(", "").replace(")", "");
}
dynamicLayoutMap.put(caption, value);
}
@@ -473,8 +459,7 @@ public class CreateBRMSParamController extends RestrictedBaseController {
private String processMultiLineFullComment(String line) {
try {
- line = splitMultiLineStartComment(line)
- + splitMultiLineEndComment(line);
+ line = splitMultiLineStartComment(line) + splitMultiLineEndComment(line);
} catch (Exception e) {
policyLogger.info("Just for Logging" + e);
line = splitMultiLineStartComment(line);
@@ -482,28 +467,33 @@ public class CreateBRMSParamController extends RestrictedBaseController {
return line;
}
- // set View Rule
+ /**
+ * setViewRule.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
@SuppressWarnings("unchecked")
- @RequestMapping(value = {"/policyController/ViewBRMSParamPolicyRule.htm"}, method = { RequestMethod.POST})
+ @RequestMapping(value = {"/policyController/ViewBRMSParamPolicyRule.htm"}, method = {RequestMethod.POST})
public void setViewRule(HttpServletRequest request, HttpServletResponse response) {
try {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode root = mapper.readTree(request.getReader());
- PolicyRestAdapter policyData = mapper
- .readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(),
- PolicyRestAdapter.class);
+ PolicyRestAdapter policyData = mapper.readValue(
+ root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class);
policyData.setDomainDir(
- root.get(PolicyController.getPolicydata()).get("model").get("name").toString().replace("\"", ""));
+ root.get(PolicyController.getPolicydata()).get("model").get("name").toString().replace("\"", ""));
if (root.get(PolicyController.getPolicydata()).get("model").get("type").toString().replace("\"", "")
- .equals(PolicyController.getFile())) {
+ .equals(PolicyController.getFile())) {
policyData.setEditPolicy(true);
}
String body = findRule(policyData.getRuleName()) + "\n";
StringBuilder generatedMetadata = new StringBuilder().append(
- "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t ")
- .append(brmsTemplateVlaue).append(policyData.getRuleName()).append("%$> \n */ \n");
+ "/* Autogenerated Code Please Don't change/remove this comment section. "
+ + "This is for the UI purpose. \n\t ")
+ .append(brmsTemplateVlaue).append(policyData.getRuleName()).append("%$> \n */ \n");
if (policyData.getDynamicLayoutMap().size() > 0) {
generatedMetadata.append("/* <%$Values=");
@@ -518,36 +508,31 @@ public class CreateBRMSParamController extends RestrictedBaseController {
policyLogger.info("Metadata generated with :" + generatedMetadata.toString());
body = generatedMetadata.toString() + body;
// Expand the body.
- Map<String, String> copyMap = new HashMap<>(
- (Map<? extends String, ? extends String>) policyData.getRuleData());
+ Map<String, String> copyMap =
+ new HashMap<>((Map<? extends String, ? extends String>) policyData.getRuleData());
copyMap.put("policyName",
- policyData.getDomainDir().replace("\\", ".") + ".Config_BRMS_Param_" + policyData.getPolicyName());
+ policyData.getDomainDir().replace("\\", ".") + ".Config_BRMS_Param_" + policyData.getPolicyName());
copyMap.put("policyScope", policyData.getDomainDir().replace("\\", "."));
copyMap.put("policyVersion", "1");
- //Finding all the keys in the Map data-structure.
+ // Finding all the keys in the Map data-structure.
Set<String> keySet = copyMap.keySet();
Iterator<String> iterator = keySet.iterator();
- Pattern p;
- Matcher m;
while (iterator.hasNext()) {
- //Converting the first character of the key into a lower case.
+ // Converting the first character of the key into a lower case.
String input = iterator.next();
- String output = Character.toLowerCase(input.charAt(0)) +
- (input.length() > 1 ? input.substring(1) : "");
- //Searching for a pattern in the String using the key.
- p = Pattern.compile("\\$\\{" + output + "\\}");
- m = p.matcher(body);
- //Replacing the value with the inputs provided by the user in the editor.
- body = m.replaceAll(copyMap.get(input));
- }
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
-
- PrintWriter out = response.getWriter();
- String responseString = mapper.writeValueAsString(body);
- JSONObject j = new JSONObject("{policyData: " + responseString + "}");
- out.write(j.toString());
+ String output = Character.toLowerCase(input.charAt(0)) + (input.length() > 1 ? input.substring(1) : "");
+ // Searching for a pattern in the String using the key.
+ Pattern pattern = Pattern.compile("\\$\\{" + output + "\\}");
+ Matcher matcher = pattern.matcher(body);
+ // Replacing the value with the inputs provided by the user in the editor.
+ body = matcher.replaceAll(copyMap.get(input));
+ }
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+
+ response.getWriter().write(new JSONObject("{policyData: " + mapper.writeValueAsString(body)
+ + "}").toString());
} catch (Exception e) {
policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java
index 93ca28190..487165b56 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.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.
* Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -27,8 +27,8 @@ import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import java.util.Objects;
+
import javax.xml.bind.JAXBElement;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
@@ -36,7 +36,6 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
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.AttributeAssignmentExpressionType;
-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.PolicyType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
@@ -53,74 +52,65 @@ public class CreateBRMSRawController {
protected PolicyRestAdapter policyAdapter = null;
- @SuppressWarnings("unchecked")
+ /**
+ * prePopulateBRMSRawPolicyData.
+ *
+ * @param policyAdapter PolicyRestAdapter
+ * @param entity PolicyEntity
+ */
public void prePopulateBRMSRawPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
- if (policyAdapter.getPolicyData() instanceof PolicyType) {
- PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
- policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
-
- // Set PolicyAdapter name value
- setPolicyAdapterNameValue(policyAdapter);
+ if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+ return;
+ }
+ PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
+ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
- // Set PolicyAdapter description.
- setPolicyAdapterDescription(policyAdapter, policy);
+ // Set PolicyAdapter name value
+ setPolicyAdapterNameValue(policyAdapter);
- // Set PolicyAdapter attributes.
- setPolicyAdapterAttributes(policyAdapter, policy);
+ // Set PolicyAdapter description.
+ setPolicyAdapterDescription(policyAdapter, policy);
- // Set PolicyAdapter configBodyData
- policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody());
+ // Set PolicyAdapter attributes.
+ setPolicyAdapterAttributes(policyAdapter, policy);
- // Get the target data under policy.
- TargetType target = policy.getTarget();
- if (target == null) {
- return;
- }
- // Under target we have AnyOFType
- List<AnyOfType> anyOfList = target.getAnyOf();
- if (anyOfList == null) {
- return;
- }
+ // Set PolicyAdapter configBodyData
+ policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody());
- // Set PolicyAdapter riskType, riskLevel, guard, ttlDate from match attributes
- setPolicyAdapterMatchAttributes(policyAdapter, policy.getTarget().getAnyOf());
+ // Get the target data under policy.
+ TargetType target = policy.getTarget();
+ if (target == null) {
+ return;
+ }
+ // Under target we have AnyOFType
+ List<AnyOfType> anyOfList = target.getAnyOf();
+ if (anyOfList == null) {
+ return;
}
+
+ // Set PolicyAdapter riskType, riskLevel, guard, ttlDate from match attributes
+ setPolicyAdapterMatchAttributes(policyAdapter, policy.getTarget().getAnyOf());
}
private void setPolicyAdapterMatchAttributes(PolicyRestAdapter policyAdapter, List<AnyOfType> anyOfList) {
anyOfList.stream()
- //Extract nonNull list of AllOfType objs from each AnyOfType obj
- .map(AnyOfType::getAllOf).filter(Objects::nonNull)
- .forEach(allOfList ->
- //Extract nonNull list of MatchType objs from each AllOFType obj
- allOfList.stream().map(AllOfType::getMatch).filter(Objects::nonNull)
- .flatMap(Collection::stream)
- .forEach(match -> {
- // 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();
- if ("RiskType".equals(attributeId)) {
- policyAdapter.setRiskType(value);
- } else if ("RiskLevel".equals(attributeId)) {
- policyAdapter.setRiskLevel(value);
- } else if ("guard".equals(attributeId)) {
- policyAdapter.setGuard(value);
- } else if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
- PolicyController controller = new PolicyController();
- String newDate = controller.convertDate(value);
- policyAdapter.setTtlDate(newDate);
- }
- }));
+ // Extract nonNull list of AllOfType objs from each AnyOfType obj
+ .map(AnyOfType::getAllOf).filter(Objects::nonNull).forEach(allOfList ->
+ // Extract nonNull list of MatchType objs from each AllOFType obj
+ allOfList.stream().map(AllOfType::getMatch).filter(Objects::nonNull).flatMap(Collection::stream)
+ .forEach(match -> {
+ // Under the match we have attribute value and
+ // attributeDesignator. So,finally down to the actual attribute.
+ policyAdapter.setupUsingAttribute(match.getAttributeDesignator().getAttributeId(),
+ (String) match.getAttributeValue().getContent().get(0));
+ }));
}
private void setPolicyAdapterNameValue(final PolicyRestAdapter policyAdapter) {
// policy name value is the policy name without any prefix and extensions.
- String policyNameValue = policyAdapter.getPolicyName()
- .substring(policyAdapter.getPolicyName().indexOf("BRMS_Raw_") + 9);
+ String policyNameValue =
+ policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Raw_") + 9);
if (logger.isDebugEnabled()) {
logger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName());
}
@@ -138,30 +128,31 @@ public class CreateBRMSRawController {
policyAdapter.setPolicyDescription(description);
}
+ @SuppressWarnings("unchecked")
private void setPolicyAdapterAttributes(final PolicyRestAdapter policyAdapter, final PolicyType policy) {
ArrayList<Object> attributeList = new ArrayList<>();
- AdviceExpressionsType expressionTypes = ((RuleType) policy
- .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions();
+ AdviceExpressionsType expressionTypes =
+ ((RuleType) policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0))
+ .getAdviceExpressions();
for (AdviceExpressionType adviceExpression : expressionTypes.getAdviceExpression()) {
for (AttributeAssignmentExpressionType attributeAssignment : adviceExpression
- .getAttributeAssignmentExpression()) {
+ .getAttributeAssignmentExpression()) {
if (attributeAssignment.getAttributeId().startsWith("key:")) {
Map<String, String> attribute = new HashMap<>();
String key = attributeAssignment.getAttributeId().replace("key:", "");
attribute.put("key", key);
- JAXBElement<AttributeValueType> attributeValue = (JAXBElement<AttributeValueType>) attributeAssignment
- .getExpression();
+ JAXBElement<AttributeValueType> attributeValue =
+ (JAXBElement<AttributeValueType>) attributeAssignment.getExpression();
String value = (String) attributeValue.getValue().getContent().get(0);
attribute.put("value", value);
attributeList.add(attribute);
} else if (attributeAssignment.getAttributeId().startsWith("dependencies:")) {
ArrayList<String> dependencies = new ArrayList<>(Arrays
- .asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(",")));
+ .asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(",")));
dependencies.remove("");
policyAdapter.setBrmsDependency(dependencies);
} else if (attributeAssignment.getAttributeId().startsWith("controller:")) {
- policyAdapter
- .setBrmsController(attributeAssignment.getAttributeId().replace("controller:", ""));
+ policyAdapter.setBrmsController(attributeAssignment.getAttributeId().replace("controller:", ""));
}
}
policyAdapter.setAttributes(attributeList);
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java
index 4c3249311..58765ded1 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.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.
* Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -21,6 +21,10 @@
package org.onap.policy.controller;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
@@ -29,9 +33,15 @@ import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
-
import java.util.Objects;
import java.util.stream.IntStream;
+import lombok.Getter;
+import lombok.Setter;
+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.PolicyType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
+
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.rest.adapter.ClosedLoopFaultBody;
@@ -40,26 +50,14 @@ import org.onap.policy.rest.adapter.ClosedLoopFaultTriggerUISignatures;
import org.onap.policy.rest.adapter.ClosedLoopSignatures;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
import org.onap.policy.rest.dao.CommonClassDao;
-import org.onap.policy.rest.jpa.OnapName;
import org.onap.policy.rest.jpa.PolicyEntity;
import org.onap.policy.rest.jpa.VarbindDictionary;
+import org.onap.policy.utils.PolicyUtils;
import org.onap.portalsdk.core.controller.RestrictedBaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
-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 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.PolicyType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
-
@Controller
@RequestMapping("/")
public class CreateClosedLoopFaultController extends RestrictedBaseController {
@@ -74,7 +72,6 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
private static final String CONNECT_TRAP_2 = "connectTrap2";
private static final String TRAP_COUNT_2 = "trapCount2";
private static final String TRIGGER_1 = "trigger1";
- private static final String ENC_UTF_8 = "UTF-8";
private static final String TRIGGER_2 = "trigger2";
protected PolicyRestAdapter policyAdapter = null;
@@ -90,19 +87,25 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
// Empty constructor
}
+ /**
+ * setDataToPolicyRestAdapter.
+ *
+ * @param policyData PolicyRestAdapter
+ * @param root JsonNode
+ * @return PolicyRestAdapter
+ */
public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
try {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- ClosedLoopFaultTrapDatas trapDatas = mapper
- .readValue(root.get("trapData").toString(), ClosedLoopFaultTrapDatas.class);
- ClosedLoopFaultTrapDatas faultDatas = mapper
- .readValue(root.get("faultData").toString(), ClosedLoopFaultTrapDatas.class);
- ClosedLoopGridJSONData policyJsonData = mapper
- .readValue(root.get("policyData").get("policy").toString(), ClosedLoopGridJSONData.class);
- ClosedLoopFaultBody jsonBody = mapper
- .readValue(root.get("policyData").get("policy").get("jsonBodyData").toString(),
- ClosedLoopFaultBody.class);
+ final ClosedLoopFaultTrapDatas trapDatas =
+ mapper.readValue(root.get("trapData").toString(), ClosedLoopFaultTrapDatas.class);
+ final ClosedLoopFaultTrapDatas faultDatas =
+ mapper.readValue(root.get("faultData").toString(), ClosedLoopFaultTrapDatas.class);
+ final ClosedLoopGridJsonData policyJsonData =
+ mapper.readValue(root.get("policyData").get("policy").toString(), ClosedLoopGridJsonData.class);
+ final ClosedLoopFaultBody jsonBody = mapper.readValue(
+ root.get("policyData").get("policy").get("jsonBodyData").toString(), ClosedLoopFaultBody.class);
// Build trapSignatureDatas list from faultData
List<Object> trapSignatureDatas = new ArrayList<>();
@@ -118,10 +121,10 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
triggerSignatures.setTrapMaxAge(Integer.parseInt(policyData.getTrapMaxAge()));
ClosedLoopFaultTriggerUISignatures uiTriggerSignatures = new ClosedLoopFaultTriggerUISignatures();
if (!trapSignatureDatas.isEmpty()) {
- uiTriggerSignatures.setSignatures(getUITriggerSignature(TRAP, trapSignatureDatas.get(0)));
+ uiTriggerSignatures.setSignatures(getUiTriggerSignature(TRAP, trapSignatureDatas.get(0)));
if (!policyJsonData.getConnecttriggerSignatures().isEmpty()) {
uiTriggerSignatures
- .setConnectSignatures(getUIConnectTraps(policyJsonData.getConnecttriggerSignatures()));
+ .setConnectSignatures(getUiConnectTraps(policyJsonData.getConnecttriggerSignatures()));
}
}
jsonBody.setTriggerSignaturesUsedForUI(uiTriggerSignatures);
@@ -144,19 +147,17 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
faultSignatures.setTimeWindow(Integer.parseInt(policyData.getVerificationclearTimeOut()));
ClosedLoopFaultTriggerUISignatures uifaultSignatures = new ClosedLoopFaultTriggerUISignatures();
if (!faultSignatureDatas.isEmpty()) {
- uifaultSignatures.setSignatures(getUITriggerSignature(FAULT, faultSignatureDatas.get(0)));
+ uifaultSignatures.setSignatures(getUiTriggerSignature(FAULT, faultSignatureDatas.get(0)));
if (!policyJsonData.getConnectVerificationSignatures().isEmpty()) {
- uifaultSignatures
- .setConnectSignatures(getUIConnectTraps(policyJsonData.getConnectVerificationSignatures()));
+ uifaultSignatures.setConnectSignatures(
+ getUiConnectTraps(policyJsonData.getConnectVerificationSignatures()));
}
}
jsonBody.setVerificationSignaturesUsedForUI(uifaultSignatures);
jsonBody.setVerificationTimeWindowUsedForUI(Integer.parseInt(policyData.getVerificationclearTimeOut()));
}
jsonBody.setVerificationSignatures(faultSignatures);
- ObjectWriter om = new ObjectMapper().writer();
- String json = om.writeValueAsString(jsonBody);
- policyData.setJsonBody(json);
+ policyData.setJsonBody(new ObjectMapper().writer().writeValueAsString(jsonBody));
} catch (Exception e) {
policyLogger.error("Exception Occured while setting data to Adapter", e);
@@ -165,13 +166,14 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
}
// TODO: Can getResultBody() and getFaultBody() be merged?
- private String getResultBody(final ClosedLoopGridJSONData policyJsonData, final List<Object> trapSignatureDatas) {
+ private String getResultBody(final ClosedLoopGridJsonData policyJsonData, final List<Object> trapSignatureDatas) {
StringBuilder resultBody = new StringBuilder();
if (!policyJsonData.getConnecttriggerSignatures().isEmpty()) {
resultBody.append("(");
IntStream.range(0, policyJsonData.getConnecttriggerSignatures().size())
- .mapToObj(i -> connectTriggerSignature(i, policyJsonData.getConnecttriggerSignatures(),
- trapSignatureDatas.get(0))).forEach(resultBody::append);
+ .mapToObj(i -> connectTriggerSignature(i, policyJsonData.getConnecttriggerSignatures(),
+ trapSignatureDatas.get(0)))
+ .forEach(resultBody::append);
resultBody.append(resultBody).append(")");
} else {
if (!trapSignatureDatas.isEmpty()) {
@@ -181,13 +183,14 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
return resultBody.toString();
}
- private String getFaultBody(final ClosedLoopGridJSONData policyJsonData, final List<Object> faultSignatureDatas) {
+ private String getFaultBody(final ClosedLoopGridJsonData policyJsonData, final List<Object> faultSignatureDatas) {
StringBuilder faultBody = new StringBuilder();
if (!policyJsonData.getConnectVerificationSignatures().isEmpty()) {
faultBody.append("(");
IntStream.range(0, policyJsonData.getConnectVerificationSignatures().size())
- .mapToObj(i -> connectTriggerSignature(i, policyJsonData.getConnectVerificationSignatures(),
- faultSignatureDatas.get(0))).forEach(faultBody::append);
+ .mapToObj(i -> connectTriggerSignature(i, policyJsonData.getConnectVerificationSignatures(),
+ faultSignatureDatas.get(0)))
+ .forEach(faultBody::append);
faultBody.append(")");
} else {
if (!faultSignatureDatas.isEmpty()) {
@@ -237,7 +240,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
}
private void appendTrapToResultBody(List<Object> triggerSignatures, Object object, StringBuilder resultBody,
- Map<String, String> connectTraps, String connectTrapName) {
+ Map<String, String> connectTraps, String connectTrapName) {
String connectTrap = connectTraps.get(connectTrapName);
if (connectTrap.startsWith(TRAP) || connectTrap.startsWith(FAULT)) {
String trapBody = callTrap(connectTrap, object);
@@ -339,16 +342,18 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
attributesStr = attributesStr + "(" + readAttributes(objectList, iy) + ")";
} catch (NumberFormatException e) {
try {
- trap1Attrib = getVarbindOID(trap1Attrib);
- attributesStr = attributesStr + "(" + URLEncoder.encode(trap1Attrib, ENC_UTF_8) + ")";
+ trap1Attrib = getVarbindOid(trap1Attrib);
+ attributesStr = attributesStr + "(" + URLEncoder.encode(trap1Attrib,
+ PolicyUtils.CHARACTER_ENCODING) + ")";
} catch (UnsupportedEncodingException e1) {
policyLogger.error("Caused Exception while Encoding Varbind Dictionary Values", e1);
}
}
} else {
try {
- trap1Attrib = getVarbindOID(trap1Attrib);
- attributesStr = attributesStr + "(" + URLEncoder.encode(trap1Attrib, ENC_UTF_8) + ")";
+ trap1Attrib = getVarbindOid(trap1Attrib);
+ attributesStr = attributesStr + "(" + URLEncoder.encode(trap1Attrib,
+ PolicyUtils.CHARACTER_ENCODING) + ")";
} catch (UnsupportedEncodingException e) {
policyLogger.error("Caused Exception while Encoding Varbind Dictionary Values", e);
}
@@ -356,21 +361,21 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
return attributesStr;
}
- private String getVarbindOID(String attrib) {
+ private String getVarbindOid(String attrib) {
VarbindDictionary varbindId;
try {
- varbindId = (VarbindDictionary) commonclassdao
- .getEntityItem(VarbindDictionary.class, "varbindName", attrib);
- return varbindId.getVarbindOID();
+ varbindId =
+ (VarbindDictionary) commonclassdao.getEntityItem(VarbindDictionary.class, "varbindName", attrib);
+ return varbindId.getVarbindOid();
} catch (Exception e) {
policyLogger.error("Error during retrieving varbindName " + attrib, e);
return attrib;
}
}
- //connect traps data set to JSON Body as String
+ // connect traps data set to JSON Body as String
@SuppressWarnings({"unchecked", "rawtypes"})
- private String getUIConnectTraps(List<Object> connectTrapSignatures) {
+ private String getUiConnectTraps(List<Object> connectTrapSignatures) {
StringBuilder resultBody = new StringBuilder();
String connectMainBody = "";
for (Object connectTrapSignature : connectTrapSignatures) {
@@ -401,9 +406,8 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
if (((LinkedHashMap) connectTraps).get(TRAP_COUNT_2) != null) {
trapCount2 = ((LinkedHashMap) connectTraps).get(TRAP_COUNT_2).toString();
}
- connectBody =
- notBox + "@!" + connectTrap1 + "@!" + trapCount1 + "@!" + operatorBox + "@!" + connectTrap2 + "@!"
- + trapCount2 + "#!?!";
+ connectBody = notBox + "@!" + connectTrap1 + "@!" + trapCount1 + "@!" + operatorBox + "@!"
+ + connectTrap2 + "@!" + trapCount2 + "#!?!";
}
resultBody.append(connectBody);
}
@@ -412,7 +416,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
}
// get Trigger signature from JSON body
- private String getUITriggerSignature(String trap, Object object2) {
+ private String getUiTriggerSignature(String trap, Object object2) {
ClosedLoopFaultTrapDatas trapDatas = (ClosedLoopFaultTrapDatas) object2;
List<Object> attributeList = new ArrayList<>();
// Read the Trap
@@ -473,89 +477,69 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
return triggerBody.toString();
}
+ /**
+ * prePopulateClosedLoopFaultPolicyData.
+ *
+ * @param policyAdapter PolicyRestAdapter
+ * @param entity PolicyEntity
+ */
public void prePopulateClosedLoopFaultPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
- if (policyAdapter.getPolicyData() instanceof PolicyType) {
- PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
-
- // Set PolicyAdapter policyName, description
- setPolicyAdapterPolicyNameAndDescription(policyAdapter, policy);
-
- // Set PolicyAdapter JsonBodyData, timeout settings
- setClosedLoopJSONFile(policyAdapter, entity);
+ if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+ return;
+ }
+ PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
- // Get the target data under policy.
- TargetType target = policy.getTarget();
- if (target == null) {
- return;
- }
+ // Set PolicyAdapter policyName, description
+ setPolicyAdapterPolicyNameAndDescription(policyAdapter, policy);
- // Under target we have AnyOFType
- List<AnyOfType> anyOfList = target.getAnyOf();
- if (anyOfList == null) {
- return;
- }
+ // Set PolicyAdapter JsonBodyData, timeout settings
+ setClosedLoopJsonFile(policyAdapter, entity);
- // Set PolicyAdapter OnapNameField, riskType, riskLevel, guard, ttlDate from match attributes
- setPolicyAdapterMatchAttributes(policyAdapter, anyOfList);
+ // Get the target data under policy.
+ TargetType target = policy.getTarget();
+ if (target == null) {
+ return;
}
+
+ // Set PolicyAdapter OnapNameField, riskType, riskLevel, guard, ttlDate from match attributes
+ setPolicyAdapterMatchAttributes(policyAdapter, target.getAnyOf());
}
private void setPolicyAdapterMatchAttributes(PolicyRestAdapter policyAdapter, List<AnyOfType> anyOfList) {
anyOfList.stream()
- //Extract nonNull list of AllOfType objs from each AnyOfType obj
- .map(AnyOfType::getAllOf).filter(Objects::nonNull)
- .forEach(allOfList ->
- //Extract nonNull list of MatchType objs from each AllOFType obj
- allOfList.stream().map(AllOfType::getMatch).filter(Objects::nonNull)
- .flatMap(Collection::stream)
- .forEach(match -> {
- // 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);
- OnapName onapName = new OnapName();
- onapName.setOnapName(value);
- policyAdapter.setOnapNameField(onapName);
- } else if ("RiskType".equals(attributeId)) {
- policyAdapter.setRiskType(value);
- } else if ("RiskLevel".equals(attributeId)) {
- policyAdapter.setRiskLevel(value);
- } else if ("guard".equals(attributeId)) {
- policyAdapter.setGuard(value);
- } else if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
- PolicyController controller = new PolicyController();
- String newDate = controller.convertDate(value);
- policyAdapter.setTtlDate(newDate);
- }
- }));
+ // Extract nonNull list of AllOfType objs from each AnyOfType obj
+ .map(AnyOfType::getAllOf).filter(Objects::nonNull).forEach(allOfList ->
+ // Extract nonNull list of MatchType objs from each AllOFType obj
+ allOfList.stream().map(AllOfType::getMatch).filter(Objects::nonNull).flatMap(Collection::stream)
+ .forEach(match -> {
+ // Under the match we have attribute value and
+ // attributeDesignator. So,finally down to the actual attribute.
+ policyAdapter.setupUsingAttribute(match.getAttributeDesignator().getAttributeId(),
+ (String) match.getAttributeValue().getContent().get(0));
+ }));
}
private void setPolicyAdapterPolicyNameAndDescription(PolicyRestAdapter policyAdapter, PolicyType policy) {
policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
- String policyNameValue = policyAdapter.getPolicyName()
- .substring(policyAdapter.getPolicyName().indexOf("Fault_") + 6);
+ String policyNameValue =
+ policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("Fault_") + 6);
policyAdapter.setPolicyName(policyNameValue);
String description;
try {
description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
} catch (Exception e) {
policyLogger.error(
- "Error during collecting the description tag info for createClosedLoopFault " + policyNameValue, e);
+ "Error during collecting the description tag info for createClosedLoopFault " + policyNameValue, e);
description = policy.getDescription();
}
policyAdapter.setPolicyDescription(description);
}
- private void setClosedLoopJSONFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
- ObjectMapper mapper = new ObjectMapper();
+ private void setClosedLoopJsonFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
try {
- ClosedLoopFaultBody closedLoopBody = mapper
- .readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopFaultBody.class);
+ ClosedLoopFaultBody closedLoopBody =
+ new ObjectMapper().readValue(entity.getConfigurationData().getConfigBody(),
+ ClosedLoopFaultBody.class);
if ("ACTIVE".equalsIgnoreCase(closedLoopBody.getClosedLoopPolicyStatus())) {
closedLoopBody.setClosedLoopPolicyStatus("Active");
} else {
@@ -570,7 +554,7 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
}
if (closedLoopBody.getVerificationTimeWindowUsedForUI() != null) {
policyAdapter
- .setVerificationclearTimeOut(closedLoopBody.getVerificationTimeWindowUsedForUI().toString());
+ .setVerificationclearTimeOut(closedLoopBody.getVerificationTimeWindowUsedForUI().toString());
}
} catch (Exception e) {
policyLogger.error("Exception Occured" + e);
@@ -578,7 +562,10 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController {
}
}
-class ClosedLoopGridJSONData {
+
+@Getter
+@Setter
+class ClosedLoopGridJsonData {
private String clearTimeOut;
private String trapMaxAge;
@@ -586,44 +573,4 @@ class ClosedLoopGridJSONData {
private List<Object> connecttriggerSignatures;
private List<Object> connectVerificationSignatures;
- public String getClearTimeOut() {
- return clearTimeOut;
- }
-
- public void setClearTimeOut(String clearTimeOut) {
- this.clearTimeOut = clearTimeOut;
- }
-
- public String getTrapMaxAge() {
- return trapMaxAge;
- }
-
- public void setTrapMaxAge(String trapMaxAge) {
- this.trapMaxAge = trapMaxAge;
- }
-
- public String getVerificationclearTimeOut() {
- return verificationclearTimeOut;
- }
-
- public void setVerificationclearTimeOut(String verificationclearTimeOut) {
- this.verificationclearTimeOut = verificationclearTimeOut;
- }
-
-
- public List<Object> getConnecttriggerSignatures() {
- return connecttriggerSignatures;
- }
-
- public void setConnecttriggerSignatures(List<Object> connecttriggerSignatures) {
- this.connecttriggerSignatures = connecttriggerSignatures;
- }
-
- public List<Object> getConnectVerificationSignatures() {
- return connectVerificationSignatures;
- }
-
- public void setConnectVerificationSignatures(List<Object> connectVerificationSignatures) {
- this.connectVerificationSignatures = connectVerificationSignatures;
- }
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java
index d2b04e024..058542590 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.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.
* Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -21,23 +21,16 @@
package org.onap.policy.controller;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
-
import java.util.Objects;
+
import javax.json.JsonArray;
import javax.json.JsonObject;
-import org.onap.policy.admin.PolicyManagerServlet;
-import org.onap.policy.common.logging.flexlogger.FlexLogger;
-import org.onap.policy.common.logging.flexlogger.Logger;
-import org.onap.policy.rest.adapter.ClosedLoopPMBody;
-import org.onap.policy.rest.adapter.PolicyRestAdapter;
-import org.onap.policy.rest.jpa.PolicyEntity;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-
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;
@@ -45,6 +38,13 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
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.onap.policy.admin.PolicyManagerServlet;
+import org.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+import org.onap.policy.rest.adapter.ClosedLoopPMBody;
+import org.onap.policy.rest.adapter.PolicyRestAdapter;
+import org.onap.policy.rest.jpa.PolicyEntity;
+
public class CreateClosedLoopPMController {
private static final Logger LOGGER = FlexLogger.getLogger(CreateClosedLoopPMController.class);
@@ -52,38 +52,40 @@ public class CreateClosedLoopPMController {
protected PolicyRestAdapter policyAdapter = null;
+ /**
+ * prePopulateClosedLoopPMPolicyData.
+ *
+ * @param policyAdapter PolicyRestAdapter
+ * @param entity PolicyEntity
+ */
public void prePopulateClosedLoopPMPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
- if (policyAdapter.getPolicyData() instanceof PolicyType) {
- Object policyData = policyAdapter.getPolicyData();
- PolicyType policy = (PolicyType) policyData;
+ if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+ return;
+ }
+ Object policyData = policyAdapter.getPolicyData();
+ PolicyType policy = (PolicyType) policyData;
- // Set oldPolicyFileName to PolicyAdapter
- policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+ // Set oldPolicyFileName to PolicyAdapter
+ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
- // Set policyNameValue and description to PolicyAdapter
- setPolicyAdapterNameValueAndDescription(policyAdapter, policy);
+ // Set policyNameValue and description to PolicyAdapter
+ setPolicyAdapterNameValueAndDescription(policyAdapter, policy);
- // Set PolicyAdapter JsonBodyData
- setClosedLoopJSONFile(policyAdapter, entity);
+ // Set PolicyAdapter JsonBodyData
+ setClosedLoopJsonFile(policyAdapter, entity);
- // Get the target data under policy.
- TargetType target = policy.getTarget();
- if (target == null) {
- return;
- }
- // Under target we have AnyOFType
- List<AnyOfType> anyOfList = target.getAnyOf();
- if (anyOfList == null) {
- return;
- }
- // Set PolicyAdapter OnapNameField, riskType, riskLevel, guard, ttlDate, ServiceType from match attributes
- setPolicyAdapterMatchAttributes(policyAdapter, anyOfList);
+ // Get the target data under policy.
+ TargetType target = policy.getTarget();
+ if (target == null) {
+ return;
}
+ // Set PolicyAdapter OnapNameField, riskType, riskLevel, guard, ttlDate, ServiceType from match attributes
+ setPolicyAdapterMatchAttributes(policyAdapter, target.getAnyOf());
}
private void setPolicyAdapterNameValueAndDescription(PolicyRestAdapter policyAdapter, PolicyType policy) {
- String policyNameValue = policyAdapter.getPolicyName()
- .substring(policyAdapter.getPolicyName().indexOf("PM_") + 3);
+ String policyNameValue =
+ policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("PM_") + 3);
policyAdapter.setPolicyName(policyNameValue);
String description;
try {
@@ -95,11 +97,10 @@ public class CreateClosedLoopPMController {
policyAdapter.setPolicyDescription(description);
}
- private void setClosedLoopJSONFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
- ObjectMapper mapper = new ObjectMapper();
+ private void setClosedLoopJsonFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
try {
- ClosedLoopPMBody closedLoopBody = mapper
- .readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopPMBody.class);
+ ClosedLoopPMBody closedLoopBody =
+ new ObjectMapper().readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopPMBody.class);
policyAdapter.setJsonBodyData(closedLoopBody);
} catch (IOException e) {
LOGGER.error("Exception Occured" + e);
@@ -107,51 +108,39 @@ public class CreateClosedLoopPMController {
}
private void setPolicyAdapterMatchAttributes(final PolicyRestAdapter policyAdapter,
- final List<AnyOfType> anyOfList) {
+ final List<AnyOfType> anyOfList) {
anyOfList.stream()
- //Extract nonNull list of AllOfType objs from each AnyOfType obj
- .map(AnyOfType::getAllOf).filter(Objects::nonNull)
- .forEach(allOfList ->
- //Extract nonNull list of MatchType objs from each AllOFType obj
+ // Extract nonNull list of AllOfType objs from each AnyOfType obj
+ .map(AnyOfType::getAllOf).filter(Objects::nonNull).forEach(allOfList ->
+ // Extract nonNull list of MatchType objs from each AllOFType obj
allOfList.stream().map(AllOfType::getMatch).filter(Objects::nonNull)
- .forEach(matchList -> matchList.forEach(match -> {
- // 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);
- } else if ("RiskType".equals(attributeId)) {
- policyAdapter.setRiskType(value);
- } else if ("RiskLevel".equals(attributeId)) {
- policyAdapter.setRiskLevel(value);
- } else if ("guard".equals(attributeId)) {
- policyAdapter.setGuard(value);
- } else if ("TTLDate".equals(attributeId) && !value.contains("NA")) {
- PolicyController controller = new PolicyController();
- String newDate = controller.convertDate(value);
- policyAdapter.setTtlDate(newDate);
- } else if ("ServiceType".equals(attributeId)) {
- LinkedHashMap<String, String> serviceTypePolicyName1 = new LinkedHashMap<>();
- serviceTypePolicyName1.put(KEY_SERVICE_TYPE_POLICY_NAME, value);
- policyAdapter.setServiceTypePolicyName(serviceTypePolicyName1);
- LinkedHashMap<String, String> vertica = new LinkedHashMap<>();
- vertica.put("verticaMetrics", getVertica(value));
- policyAdapter.setVerticaMetrics(vertica);
- LinkedHashMap<String, String> desc = new LinkedHashMap<>();
- desc.put("policyDescription", getDescription(value));
- policyAdapter.setDescription(desc);
- LinkedHashMap<String, Object> attributes = new LinkedHashMap<>();
- attributes.put("attributes", getAttributes(value));
- policyAdapter.setAttributeFields(attributes);
- }
- })));
+ .forEach(matchList -> matchList.forEach(match -> {
+ // 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.
+ policyAdapter.setupUsingAttribute(attributeId, value);
+ if ("ServiceType".equals(attributeId)) {
+ LinkedHashMap<String, String> serviceTypePolicyName1 = new LinkedHashMap<>();
+ serviceTypePolicyName1.put(KEY_SERVICE_TYPE_POLICY_NAME, value);
+ policyAdapter.setServiceTypePolicyName(serviceTypePolicyName1);
+ LinkedHashMap<String, String> vertica = new LinkedHashMap<>();
+ vertica.put("verticaMetrics", getVertica(value));
+ policyAdapter.setVerticaMetrics(vertica);
+ LinkedHashMap<String, String> desc = new LinkedHashMap<>();
+ desc.put("policyDescription", getDescription(value));
+ policyAdapter.setDescription(desc);
+ LinkedHashMap<String, Object> attributes = new LinkedHashMap<>();
+ attributes.put("attributes", getAttributes(value));
+ policyAdapter.setAttributeFields(attributes);
+ }
+ })));
}
- //get vertica metrics data from the table
+ // get vertica metrics data from the table
private String getVertica(String policyName) {
JsonArray data = PolicyManagerServlet.getPolicyNames();
for (int i = 0; i < data.size(); i++) {
@@ -162,7 +151,7 @@ public class CreateClosedLoopPMController {
return null;
}
- //get policy description from the table
+ // get policy description from the table
private String getDescription(String policyName) {
JsonArray data = PolicyManagerServlet.getPolicyNames();
for (int i = 0; i < data.size(); i++) {
@@ -173,7 +162,7 @@ public class CreateClosedLoopPMController {
return null;
}
- //get Attributes
+ // get Attributes
private JsonObject getAttributes(String policyName) {
JsonArray data = PolicyManagerServlet.getPolicyNames();
for (int i = 0; i < data.size(); i++) {
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 a8df74add..4be31dd1e 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,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 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 com.att.research.xacml.util.XACMLProperties;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
@@ -37,12 +36,13 @@ import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
-import java.io.PrintWriter;
import java.io.StringReader;
+import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
+import java.util.Base64;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
@@ -68,10 +68,10 @@ import javax.json.JsonReader;
import javax.json.JsonValue;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import lombok.Getter;
+import lombok.Setter;
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;
@@ -82,20 +82,22 @@ import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
+import org.apache.commons.lang3.StringEscapeUtils;
import org.json.JSONArray;
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.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
import org.onap.policy.rest.dao.CommonClassDao;
import org.onap.policy.rest.jpa.GroupPolicyScopeList;
import org.onap.policy.rest.jpa.MicroServiceModels;
import org.onap.policy.rest.jpa.MicroserviceHeaderdeFaults;
import org.onap.policy.rest.jpa.PolicyEntity;
-import org.onap.policy.rest.util.MSAttributeObject;
-import org.onap.policy.rest.util.MSModelUtils;
-import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE;
+import org.onap.policy.rest.util.MsAttributeObject;
+import org.onap.policy.rest.util.MsModelUtils;
+import org.onap.policy.rest.util.MsModelUtils.ModelType;
+import org.onap.policy.utils.PolicyUtils;
import org.onap.portalsdk.core.controller.RestrictedBaseController;
import org.onap.portalsdk.core.web.support.JsonMessage;
import org.springframework.beans.factory.annotation.Autowired;
@@ -124,7 +126,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
private String directory;
private List<String> modelList = new ArrayList<>();
private List<String> dirDependencyList = new ArrayList<>();
- private LinkedHashMap<String, MSAttributeObject> classMap = new LinkedHashMap<>();
+ private LinkedHashMap<String, MsAttributeObject> classMap = new LinkedHashMap<>();
String referenceAttributes;
String attributeString;
Set<String> allManyTrueKeys = null;
@@ -158,6 +160,13 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
private Map<String, LinkedList<String>> arrayTextList = new HashMap<>();
private Map<String, String> jsonStringValues = new HashMap<>();
+ /**
+ * setDataToPolicyRestAdapter.
+ *
+ * @param policyData PolicyRestAdapter
+ * @param root JsonNode
+ * @return PolicyRestAdapter
+ */
public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
String jsonContent = null;
@@ -165,10 +174,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
LOGGER.info("policyJSON :" + (root.get(POLICYJSON)).toString());
String tempJson = root.get(POLICYJSON).toString();
- JSONObject policyJSON = new JSONObject(root.get(POLICYJSON).toString());
- if (policyJSON != null) {
- tempJson = saveOriginalJsonObject(policyJSON, jsonStringValues).toString();
- }
+ JSONObject policyJson = new JSONObject(root.get(POLICYJSON).toString());
+ tempJson = decodeJsonVal(tempJson, policyJson);
// ---replace empty value with the value below before calling decodeContent method.
String dummyValue = "*empty-value*" + UUID.randomUUID().toString();
LOGGER.info("dummyValue:" + dummyValue);
@@ -189,12 +196,28 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
JSONObject content = contentJson.getJSONObject("content");
content = setOriginalJsonObject(content, jsonStringValues);
contentJson.put("content", content);
- policyData.setJsonBody(contentJson.toString());
+ policyData.setJsonBody(StringEscapeUtils.unescapeJava(contentJson.toString()));
}
return policyData;
}
+ private String decodeJsonVal(String tempJson, JSONObject policyJson) {
+ if (policyJson != null) {
+ for (Object key : policyJson.keySet()) {
+ String keyStr = (String) key;
+ Object keyvalue = policyJson.get(keyStr);
+ String decodedString = keyvalue.toString();//.replace("\"", "");
+ if(!decodedString.equals("true") && !decodedString.equals("false")) {
+ String decodedJson = new String(Base64.getDecoder().decode(decodedString), StandardCharsets.UTF_8).replace("\"", "\\\"");
+ policyJson.put(keyStr, decodedJson);
+ }
+ }
+ tempJson = saveOriginalJsonObject(policyJson, jsonStringValues).toString();
+ }
+ return tempJson;
+ }
+
private JSONObject saveOriginalJsonObject(JSONObject jsonObj, Map<String, String> jsonStringValues) {
for (Object key : jsonObj.keySet()) {
String keyStr = (String) key;
@@ -259,7 +282,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
String json = "";
DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject();
MicroServiceModels returnModel = new MicroServiceModels();
- microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS));
+ microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XacmlRestProperties.TEMPLATE_VERSION_MS));
if (policyAdapter.getServiceType() != null) {
microServiceObject.setService(policyAdapter.getServiceType());
microServiceObject.setVersion(policyAdapter.getVersion());
@@ -309,15 +332,11 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
modelName + ":" + versionName);
MicroServiceModels model = null;
boolean ruleCheck = false;
- boolean SymptomRuleCheck = false;
if (!triggerData.isEmpty()) {
model = (MicroServiceModels) triggerData.get(0);
if (model.getRuleFormation() != null) {
microServiceObject.setUiContent(jsonContent);
ruleCheck = true;
- if (model.getRuleFormation().contains("@")) {
- SymptomRuleCheck = true;
- }
}
}
try {
@@ -327,7 +346,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
LOGGER.info("input json: " + json);
LOGGER.info("input jsonContent: " + jsonContent);
- String cleanJson = cleanUPJson(json);
+ 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[] {"\"\""});
@@ -340,40 +359,39 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
// for Triggers
ObjectMapper mapper = new ObjectMapper();
JsonNode tempJsonNode = mapper.readTree(cleanJson);
- if (ruleCheck) {
- // JsonNode tempJsonNode = mapper.readTree(cleanJson);
- ObjectNode finalJson = (ObjectNode) tempJsonNode;
- JsonNode object = tempJsonNode.get("content");
- String primaryKey1 = model.getRuleFormation();
- String[] primaryKeyForSignatures = primaryKey1.split("@");
- for (String primaryKeyForSignature : primaryKeyForSignatures) {
- String primarykeyAlarm = primaryKeyForSignature.substring(0, primaryKeyForSignature.indexOf('.'));
- JsonNode triggerSig = object.get(primarykeyAlarm);
- sigRules = new HashMap<>();
- String parseKey = primaryKeyForSignature.substring(primaryKeyForSignature.indexOf('.') + 1);
- StringBuilder sb = null;
- if (triggerSig instanceof ArrayNode) {
- for (int i = 0; i < triggerSig.size(); i++) {
- sb = new StringBuilder();
- parseData(triggerSig.get(i), parseKey);
- sb.append("(");
- List<?> keyList = new ArrayList<>(sigRules.keySet());
- for (int j = keyList.size() - 1; j >= 0; j--) {
- String key = (String) keyList.get(j);
- String jsonNode = sigRules.get(key);
- constructRule(sb, jsonNode, sigRules);
- }
- sb.append(")").toString();
- putRuletoJson(tempJsonNode, i, sb, parseKey, primarykeyAlarm);
- sigRules = new HashMap<>();
- }
- } else {
+ if (! ruleCheck) {
+ return policyAdapter;
+ }
+ ObjectNode finalJson = (ObjectNode) tempJsonNode;
+ JsonNode object = tempJsonNode.get("content");
+ String primaryKey1 = model.getRuleFormation();
+ String[] primaryKeyForSignatures = primaryKey1.split("@");
+ for (String primaryKeyForSignature : primaryKeyForSignatures) {
+ String primarykeyAlarm = primaryKeyForSignature.substring(0, primaryKeyForSignature.indexOf('.'));
+ JsonNode triggerSig = object.get(primarykeyAlarm);
+ sigRules = new HashMap<>();
+ String parseKey = primaryKeyForSignature.substring(primaryKeyForSignature.indexOf('.') + 1);
+ StringBuilder sb = null;
+ if (triggerSig instanceof ArrayNode) {
+ for (int i = 0; i < triggerSig.size(); i++) {
sb = new StringBuilder();
- parseData(triggerSig, parseKey);
+ parseData(triggerSig.get(i), parseKey);
+ sb.append("(");
+ List<?> keyList = new ArrayList<>(sigRules.keySet());
+ for (int j = keyList.size() - 1; j >= 0; j--) {
+ String key = (String) keyList.get(j);
+ String jsonNode = sigRules.get(key);
+ constructRule(sb, jsonNode, sigRules);
+ }
+ sb.append(")").toString();
+ putRuletoJson(tempJsonNode, i, sb, parseKey, primarykeyAlarm);
+ sigRules = new HashMap<>();
}
+ } else {
+ parseData(triggerSig, parseKey);
}
- policyAdapter.setJsonBody(finalJson.toString());
}
+ policyAdapter.setJsonBody(finalJson.toString());
return policyAdapter;
}
@@ -486,6 +504,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
}
+ /**
+ * removeNullAttributes.
+ *
+ * @param cleanJson String
+ * @returnString
+ */
public String removeNullAttributes(String cleanJson) {
ObjectMapper mapper = new ObjectMapper();
@@ -529,9 +553,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
if (contentChanged) {
// set modified content to cleanJson
- JSONObject jObject = new JSONObject(cleanJson);
- jObject.put("content", removed.toString());
- cleanJson = cleanUPJson(jObject.toString());
+ JSONObject jsonObject = new JSONObject(cleanJson);
+ jsonObject.put("content", removed.toString());
+ cleanJson = cleanUpJson(jsonObject.toString());
}
} catch (IOException e) {
@@ -554,90 +578,93 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
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[] {"\\\""});
+ return jsonStringValues.get(k);
}
}
}
}
if (k.endsWith(key)) {
- return StringUtils.replaceEach(jsonStringValues.get(k), new String[] {"\""}, new String[] {"\\\""});
+ return jsonStringValues.get(k);
}
}
return null;
}
+ /**
+ * removeNull.
+ *
+ * @param array JsonArray
+ * @return JsonArray
+ */
public JsonArray removeNull(JsonArray array) {
JsonArrayBuilder builder = Json.createArrayBuilder();
- int i = 0;
- for (Iterator<JsonValue> it = array.iterator(); it.hasNext(); ++i) {
+ int index = 0;
+ for (Iterator<JsonValue> it = array.iterator(); it.hasNext(); ++index) {
JsonValue value = it.next();
switch (value.getValueType()) {
case ARRAY:
- JsonArray a = removeNull(array.getJsonArray(i));
- if (!a.isEmpty())
- builder.add(a);
+ JsonArray tempArray = removeNull(array.getJsonArray(index));
+ if (!tempArray.isEmpty()) {
+ builder.add(tempArray);
+ }
break;
case OBJECT:
- JsonObject object = removeNull(array.getJsonObject(i));
- if (!object.isEmpty())
+ JsonObject object = removeNull(array.getJsonObject(index));
+ if (!object.isEmpty()) {
builder.add(object);
+ }
break;
case STRING:
- String s = array.getString(i);
- if (s != null && !s.isEmpty())
- builder.add(s);
+ String str = array.getString(index);
+ if (str != null && !str.isEmpty()) {
+ builder.add(str);
+ }
break;
case NUMBER:
- builder.add(array.getJsonNumber(i));
+ builder.add(array.getJsonNumber(index));
break;
case TRUE:
case FALSE:
- builder.add(array.getBoolean(i));
+ builder.add(array.getBoolean(index));
break;
case NULL:
+ default:
break;
}
}
return builder.build();
}
+ /**
+ * removeNull.
+ *
+ * @param obj JsonObject
+ * @return JsonObject
+ */
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();
+ Entry<String, JsonValue> entry = it.next();
+ String key = entry.getKey();
+ JsonValue value = entry.getValue();
switch (value.getValueType()) {
case ARRAY:
JsonArray array = removeNull(obj.getJsonArray(key));
- if (!array.isEmpty())
+ 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);
+ String str = obj.getString(key);
+ if (str != null && !str.isEmpty()) {
+ builder.add(key, str);
}
break;
case NUMBER:
@@ -648,13 +675,20 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
builder.add(key, obj.getBoolean(key));
break;
case NULL:
+ default:
break;
}
}
return builder.build();
}
- public String cleanUPJson(String json) {
+ /**
+ * cleanUpJson.
+ *
+ * @param json String
+ * @return String
+ */
+ public String cleanUpJson(String json) {
String cleanJson = StringUtils.replaceEach(json, new String[] {"\\\\", "\\\\\\", "\\\\\\\\"},
new String[] {"\\", "\\", "\\"});
cleanJson = StringUtils.replaceEach(cleanJson, new String[] {"\\\\\\"}, new String[] {"\\"});
@@ -675,6 +709,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
return cleanJson;
}
+ /**
+ * decodeContent.
+ *
+ * @param jsonNode JsonNode
+ * @return JsonNode
+ */
public JSONObject decodeContent(JsonNode jsonNode) {
Iterator<JsonNode> jsonElements = jsonNode.elements();
Iterator<String> jsonKeys = jsonNode.fieldNames();
@@ -825,7 +865,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
return jsonResult;
}
- @RequestMapping(value = {"/policyController/getDCAEMSTemplateData.htm"},
+ @RequestMapping(
+ value = {"/policyController/getDCAEMSTemplateData.htm"},
method = {org.springframework.web.bind.annotation.RequestMethod.POST})
public ModelAndView getDCAEMSTemplateData(HttpServletRequest request, HttpServletResponse response)
throws IOException {
@@ -862,8 +903,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
// 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());
+ if (returnModel.getSubAttributes() != null && !returnModel.getSubAttributes().isEmpty()) {
+ JSONObject json = new JSONObject(returnModel.getSubAttributes());
getAllKeys(json);
allkeys = allManyTrueKeys;
allManyTrueKeys = new TreeSet<>();
@@ -882,7 +923,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
allMnyTrueKeys = allkeys.toString();
}
- String jsonModel = createMicroSeriveJson(returnModel, allkeys);
+ String jsonModel = createMicroSeriveJson(returnModel);
JSONObject jsonObject = new JSONObject(jsonModel);
@@ -901,8 +942,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
jsonModel = finalJsonObject.toString();
}
- // get all properties with "MANY-true" defined in Ref_attributes
- Set<String> manyTrueProperties = getManyTrueProperties(returnModel.getRef_attributes());
+ // get all properties with "MANY-true" defined in RefAttributes
+ Set<String> manyTrueProperties = getManyTrueProperties(returnModel.getRefAttributes());
if (manyTrueProperties != null) {
JSONObject jsonObj = new JSONObject(jsonModel);
for (String s : manyTrueProperties) {
@@ -918,37 +959,36 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
}
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
List<Object> list = new ArrayList<>();
- PrintWriter out = response.getWriter();
String responseString = mapper.writeValueAsString(returnModel);
- JSONObject j = null;
+ JSONObject json = null;
if ("".equals(allMnyTrueKeys)) {
- j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",dataOrderInfo:"
+ json = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",dataOrderInfo:"
+ dataOrderInfo + ",headDefautlsData:" + headDefautlsData + "}");
} else {
- j = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel + ",allManyTrueKeys: "
- + allMnyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData
- + "}");
+ json = new JSONObject("{dcaeModelData: " + responseString + ",jsonValue: " + jsonModel
+ + ",allManyTrueKeys: " + allMnyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:"
+ + headDefautlsData + "}");
}
- list.add(j);
- out.write(list.toString());
+ list.add(json);
+ response.getWriter().write(list.toString());
return null;
}
@SuppressWarnings({"unchecked", "rawtypes"})
- private String createMicroSeriveJson(MicroServiceModels returnModel, Set<String> allkeys) {
+ private String createMicroSeriveJson(MicroServiceModels returnModel) {
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();
+ String refAttribute = returnModel.getRefAttributes();
if (refAttribute != null) {
refAttribute = refAttribute.trim();
}
@@ -965,7 +1005,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
Gson gson = new Gson();
- String subAttributes = returnModel.getSub_attributes();
+ String subAttributes = returnModel.getSubAttributes();
if (subAttributes != null) {
subAttributes = subAttributes.trim();
} else {
@@ -975,10 +1015,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
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();
+ JSONArray array = new JSONArray();
String value = keySet.getValue();
if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
array.put(value);
@@ -989,7 +1028,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
for (Entry<String, String> keySet : refAttributeMap.entrySet()) {
- array = new JSONArray();
+ JSONArray array = new JSONArray();
String value = keySet.getValue().split(":")[0];
if (gsonObject.containsKey(value)) {
if ("true".equalsIgnoreCase(keySet.getValue().split("MANY-")[1])) {
@@ -1042,7 +1081,6 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
return object;
}
-
public JSONObject convertToArrayElement(JSONObject json, String keyValue) {
return convertToArrayElement(json, new HashSet<>(), keyValue);
}
@@ -1070,14 +1108,25 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
if (obj instanceof JSONArray) {
- convertToArrayElement(json.getJSONArray(key).getJSONObject(0), keyValue);
+ try {
+ if (json.getJSONArray(key).length() > 0) {
+ convertToArrayElement(json.getJSONArray(key).getJSONObject(0), keyValue);
+ }
+ } catch (Exception ex) {
+ LOGGER.info("XMI Model load issue : " + ex);
+ }
}
}
return json;
}
- // call this method to get all MANY-true properties
+ /**
+ * getManyTrueProperties.
+ *
+ * @param referAttributes String
+ * @return a Set of String
+ */
public Set<String> getManyTrueProperties(String referAttributes) {
LOGGER.info("referAttributes : " + referAttributes);
Set<String> manyTrueProperties = new HashSet<>();
@@ -1108,10 +1157,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
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)
+ if (obj instanceof JSONObject) {
keys.addAll(getAllKeys(arr.getJSONObject(i)));
- if (obj instanceof JSONArray)
+ }
+ if (obj instanceof JSONArray) {
keys.addAll(getAllKeys(arr.getJSONArray(i)));
+ }
}
return keys;
@@ -1126,37 +1177,42 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
LOGGER.info("obj : " + obj);
allManyTrueKeys.add(key);
}
- if (obj instanceof JSONObject)
+ if (obj instanceof JSONObject) {
keys.addAll(getAllKeys(json.getJSONObject(key)));
- if (obj instanceof JSONArray)
+ }
+ if (obj instanceof JSONArray) {
keys.addAll(getAllKeys(json.getJSONArray(key)));
+ }
}
return keys;
}
-
- @RequestMapping(value = {"/policyController/getModelServiceVersioneData.htm"},
+ /**
+ * getModelServiceVersionData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @return ModelAndView
+ * @throws IOException IOException
+ */
+ @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("^\"|\"$", "");
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ List<Object> list = new ArrayList<>();
+ String value = mapper.readTree(request.getReader()).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());
+ list.add(new JSONObject("{dcaeModelVersionData: " + mapper.writeValueAsString(returnList) + "}"));
+ response.getWriter().write(list.toString());
return null;
}
@@ -1201,7 +1257,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
modelName);
}
- @RequestMapping(value = {"/get_DCAEPriorityValues"},
+ @RequestMapping(
+ value = {"/get_DCAEPriorityValues"},
method = {org.springframework.web.bind.annotation.RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response) {
@@ -1214,93 +1271,64 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
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());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
LOGGER.error(e);
}
}
+ /**
+ * prePopulateDCAEMSPolicyData.
+ *
+ * @param policyAdapter PolicyRestAdapter
+ * @param entity PolicyEntity
+ */
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);
- }
- }
- }
- }
+ if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+ return;
+ }
+ 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) {
+ return;
+ }
+ for (AnyOfType anyOf : target.getAnyOf()) {
+ for (AllOfType allOf : anyOf.getAllOf()) {
+ // Under AllOFType we have Match
+ List<MatchType> matchList = allOf.getMatch();
+ if (matchList == null) {
+ continue;
}
+ Iterator<MatchType> iterMatch = matchList.iterator();
+ //
+ // Can someone please explain why the matchList MUST have
+ // more than 1 matches???
+ //
+ 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.
+ //
+ // First match in the target is OnapName, so set that value.
+ policyAdapter.setupUsingAttribute(match.getAttributeDesignator().getAttributeId(),
+ (String) match.getAttributeValue().getContent().get(0));
+ }
+ readFile(policyAdapter, entity);
}
}
}
@@ -1321,7 +1349,6 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
return map;
}
-
/**
* Read file.
*
@@ -1330,12 +1357,11 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
*/
@SuppressWarnings("unchecked")
public 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());
+ new ObjectMapper().readValue(entity.getConfigurationData().getConfigBody(),
+ DCAEMicroServiceObject.class);
+ String policyScopeName = getPolicyScope(msBody.getPolicyScope());
policyAdapter.setPolicyScope(policyScopeName);
policyAdapter.setPriority(msBody.getPriority());
@@ -1364,6 +1390,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
+ /**
+ * readRecursivlyJSONContent.
+ *
+ * @param map Map of String to something
+ * @param data Map of String to Object
+ */
@SuppressWarnings({"rawtypes", "unchecked"})
public void readRecursivlyJSONContent(Map<String, ?> map, Map<String, Object> data) {
for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
@@ -1401,16 +1433,27 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
}
+ /**
+ * getPolicyScope.
+ *
+ * @param value String
+ * @return String
+ */
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 ((GroupPolicyScopeList) groupList.get(0)).getGroupName();
}
return null;
}
- // Convert the map values and set into JSON body
+ /**
+ * Convert the map values and set into JSON body.
+ *
+ * @param attributesMap Map of attributes
+ * @param attributesRefMap Map of attribute references
+ * @return Map
+ */
public Map<String, String> convertMap(Map<String, String> attributesMap, Map<String, String> attributesRefMap) {
Map<String, String> attribute = new HashMap<>();
StringBuilder temp;
@@ -1448,7 +1491,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
return attribute;
}
- @RequestMapping(value = {"/ms_dictionary/set_MSModelData"},
+ @RequestMapping(
+ value = {"/ms_dictionary/set_MSModelData"},
method = {org.springframework.web.bind.annotation.RequestMethod.POST})
public void SetMSModelData(HttpServletRequest request, HttpServletResponse response)
throws IOException, FileUploadException {
@@ -1490,35 +1534,31 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
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());
+ JSONObject json = new JSONObject();
+ json.put("errorMsg", errorMsg);
+ response.getWriter().write(json.toString());
return;
}
List<File> fileList = new ArrayList<>();
- MSModelUtils msMLUtils = new MSModelUtils(commonClassDao);
+ MsModelUtils msModelUtils = new MsModelUtils(commonClassDao);
this.directory = "model";
if (zip) {
extractFolder(this.newFile);
fileList = listModelFiles(this.directory);
} else if (yml) {
- errorMsg = msMLUtils.parseTosca(this.newFile);
+ errorMsg = msModelUtils.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());
+ JSONObject json = new JSONObject();
+ json.put("errorMsg", errorMsg);
+ response.getWriter().write(json.toString());
return;
}
@@ -1533,7 +1573,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
classMap = new LinkedHashMap<>();
for (File file : fileList) {
if (!file.isDirectory() && file.getName().endsWith(".xmi")) {
- retreiveDependency(file.toString(), true);
+ retrieveDependency(file.toString());
}
}
@@ -1545,25 +1585,25 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
modelType = "yml";
modelList.add(this.newModel.getModelName());
String className = this.newModel.getModelName();
- MSAttributeObject msAttributes = new MSAttributeObject();
+ MsAttributeObject msAttributes = new MsAttributeObject();
msAttributes.setClassName(className);
LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>();
- returnAttributeList.put(className, msMLUtils.getAttributeString());
+ returnAttributeList.put(className, msModelUtils.getAttributeString());
msAttributes.setAttribute(returnAttributeList);
- msAttributes.setSubClass(msMLUtils.getRetmap());
+ msAttributes.setSubClass(msModelUtils.getRetmap());
- msAttributes.setMatchingSet(msMLUtils.getMatchableValues());
+ msAttributes.setMatchingSet(msModelUtils.getMatchableValues());
LinkedHashMap<String, String> returnReferenceList = new LinkedHashMap<>();
- returnReferenceList.put(className, msMLUtils.getReferenceAttributes());
+ returnReferenceList.put(className, msModelUtils.getReferenceAttributes());
msAttributes.setRefAttribute(returnReferenceList);
- if (msMLUtils.getListConstraints() != "") {
+ if (msModelUtils.getListConstraints() != "") {
LinkedHashMap<String, String> enumList = new LinkedHashMap<>();
- String[] listArray = msMLUtils.getListConstraints().split("#");
+ String[] listArray = msModelUtils.getListConstraints().split("#");
for (String str : listArray) {
String[] strArr = str.split("=");
if (strArr.length > 1) {
@@ -1577,22 +1617,19 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
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());
- j.put("ruleFormation", msMLUtils.getJsonRuleFormation());
-
- out.write(j.toString());
+ JSONObject json = new JSONObject();
+ json.put("classListDatas", modelList);
+ json.put("modelDatas", mapper.writeValueAsString(classMap));
+ json.put("modelType", modelType);
+ json.put("dataOrderInfo", msModelUtils.getDataOrderInfo());
+ json.put("ruleFormation", msModelUtils.getJsonRuleFormation());
+
+ response.getWriter().write(json.toString());
}
/*
@@ -1600,7 +1637,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
*/
@SuppressWarnings("rawtypes")
private void extractFolder(String zipFile) {
- int BUFFER = 2048;
+ final int buffer = 2048;
File file = new File(zipFile);
try (ZipFile zip = new ZipFile(file)) {
@@ -1623,10 +1660,10 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
if (!entry.isDirectory()) {
BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
int currentByte;
- byte[] data = new byte[BUFFER];
+ 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) {
+ BufferedOutputStream dest = new BufferedOutputStream(fos, buffer)) {
+ while ((currentByte = is.read(data, 0, buffer)) != -1) {
dest.write(data, 0, currentByte);
}
dest.flush();
@@ -1648,25 +1685,21 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
}
- private void retreiveDependency(String workingFile, Boolean modelClass) {
+ private void retrieveDependency(String workingFile) {
- MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
- Map<String, MSAttributeObject> tempMap;
+ MsModelUtils utils = new MsModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
+ Map<String, MsAttributeObject> tempMap;
- tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
+ tempMap = utils.processEpackage(workingFile, ModelType.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) {
+ for (File file : fileDirectory.listFiles()) {
if (file.isFile()) {
resultList.add(file);
} else if (file.isDirectory()) {
@@ -1677,6 +1710,11 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
return resultList;
}
+ /**
+ * cleanUp.
+ *
+ * @param path String
+ */
public void cleanUp(String path) {
if (path != null) {
try {
@@ -1687,6 +1725,11 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
}
+ /**
+ * checkZipDirectory.
+ *
+ * @param zipDirectory String
+ */
public void checkZipDirectory(String zipDirectory) {
Path path = Paths.get(zipDirectory);
@@ -1697,9 +1740,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
private List<String> createList() {
List<String> list = new ArrayList<>();
- for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()) {
- if (cMap.getValue().isPolicyTempalate()) {
- list.add(cMap.getKey());
+ for (Entry<String, MsAttributeObject> entrySet : classMap.entrySet()) {
+ if (entrySet.getValue().isPolicyTempalate()) {
+ list.add(entrySet.getKey());
}
}
@@ -1732,7 +1775,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
-
+@Getter
+@Setter
class DCAEMicroServiceObject {
private String service;
@@ -1749,128 +1793,5 @@ class DCAEMicroServiceObject {
private String riskLevel;
private String guard = null;
private Object uiContent;
-
- 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;
- }
-
- public Object getUiContent() {
- return uiContent;
- }
-
- public void setUiContent(Object uiContent) {
- this.uiContent = uiContent;
- }
-
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java
index 3e24dc7c4..3da703ab2 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java
@@ -2,14 +2,14 @@
* ============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.
* 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.
@@ -19,11 +19,16 @@
*/
package org.onap.policy.controller;
-import java.io.PrintWriter;
+
+import com.fasterxml.jackson.core.JsonGenerationException;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -32,6 +37,12 @@ import java.util.Set;
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.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.lang3.StringUtils;
import org.hibernate.SessionFactory;
import org.json.JSONObject;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
@@ -55,13 +66,14 @@ import org.onap.policy.rest.adapter.TermCollector;
import org.onap.policy.rest.adapter.VendorSpecificData;
import org.onap.policy.rest.dao.CommonClassDao;
import org.onap.policy.rest.jpa.AddressGroup;
-import org.onap.policy.rest.jpa.FWTagPicker;
+import org.onap.policy.rest.jpa.FwTagPicker;
import org.onap.policy.rest.jpa.GroupServiceList;
import org.onap.policy.rest.jpa.PolicyEntity;
import org.onap.policy.rest.jpa.PrefixList;
import org.onap.policy.rest.jpa.SecurityZone;
import org.onap.policy.rest.jpa.ServiceList;
import org.onap.policy.rest.jpa.TermList;
+import org.onap.policy.utils.PolicyUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.portalsdk.core.controller.RestrictedBaseController;
import org.springframework.beans.factory.annotation.Autowired;
@@ -69,886 +81,832 @@ import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
-import com.fasterxml.jackson.core.JsonGenerationException;
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.JsonMappingException;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.ObjectWriter;
-
-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 CreateFirewallController extends RestrictedBaseController {
- private static Logger policyLogger = FlexLogger.getLogger(CreateFirewallController.class);
- private static final String ANY="ANY";
- private static final String GROUP="Group_";
-
- @Autowired
- SessionFactory sessionFactory;
-
- private static CommonClassDao commonClassDao;
-
- public static CommonClassDao getCommonClassDao() {
- return commonClassDao;
- }
-
- public static void setCommonClassDao(CommonClassDao commonClassDao) {
- CreateFirewallController.commonClassDao = commonClassDao;
- }
-
- private List<String> tagCollectorList;
-
- List<String> expandablePrefixIPList = new ArrayList<>();
- List<String> expandableServicesList= new ArrayList<>();
- @Autowired
- private CreateFirewallController(CommonClassDao commonClassDao){
- CreateFirewallController.commonClassDao = commonClassDao;
- }
-
- public CreateFirewallController(){
- // Empty constructor
- }
- private List<String> termCollectorList;
-
-
-
- public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData){
- String jsonBody;
- termCollectorList = new ArrayList <>();
- tagCollectorList = new ArrayList <>();
- if(! policyData.getAttributes().isEmpty()){
- for(Object attribute : policyData.getAttributes()){
- if(attribute instanceof LinkedHashMap<?, ?>){
- String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
- termCollectorList.add(key);
-
- String tag = ((LinkedHashMap<?, ?>) attribute).get("value").toString();
- tagCollectorList.add(tag);
- }
- }
- }
- jsonBody = constructJson(policyData);
- if (jsonBody != null && ! "".equalsIgnoreCase(jsonBody)) {
- policyData.setJsonBody(jsonBody);
- } else {
- policyData.setJsonBody("{}");
- }
- policyData.setJsonBody(jsonBody);
-
- return policyData;
- }
-
- private List<String> mapping(String expandableList) {
- String value;
- String desc;
- List <String> valueDesc= new ArrayList<>();
- List<Object> prefixListData = commonClassDao.getData(PrefixList.class);
- for (int i = 0; i< prefixListData.size(); i++) {
- PrefixList prefixList = (PrefixList) prefixListData.get(i);
- if (prefixList.getPrefixListName().equals(expandableList)) {
- value = prefixList.getPrefixListValue();
- valueDesc.add(value);
- desc= prefixList.getDescription();
- valueDesc.add(desc);
- break;
- }
- }
- return valueDesc;
- }
-
- private ServiceList mappingServiceList(String expandableList) {
- ServiceList serviceList=null;
- List<Object> serviceListData = commonClassDao.getData(ServiceList.class);
- for (int i = 0; i< serviceListData.size(); i++) {
- serviceList = (ServiceList) serviceListData.get(i);
- if (serviceList.getServiceName().equals(expandableList)) {
- break;
- }
- }
- return serviceList;
- }
-
- private GroupServiceList mappingServiceGroup(String expandableList) {
-
- GroupServiceList serviceGroup=null;
- List<Object> serviceGroupData = commonClassDao.getData(GroupServiceList.class);
- for (int i = 0; i< serviceGroupData.size(); i++) {
- serviceGroup = (GroupServiceList) serviceGroupData.get(i);
- if (serviceGroup.getGroupName().equals(expandableList)) {
- break;
- }
- }
- return serviceGroup;
- }
-
- private AddressGroup mappingAddressGroup(String expandableList) {
-
- AddressGroup addressGroup=null;
- List<Object> addressGroupData = commonClassDao.getData(AddressGroup.class);
- for (int i = 0; i< addressGroupData.size(); i++) {
- addressGroup = (AddressGroup) addressGroupData.get(i);
- if (addressGroup.getGroupName().equals(expandableList)) {
- break;
- }
- }
- return addressGroup;
- }
-
- public void prePopulateFWPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
- ArrayList<Object> attributeList;
- attributeList = new ArrayList<>();
- if (policyAdapter.getPolicyData() instanceof PolicyType) {
- Object policyData = policyAdapter.getPolicyData();
- PolicyType policy = (PolicyType) policyData;
- // policy name value is the policy name without any prefix and Extensions.
- policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
- String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("FW_") +3);
- if (policyLogger.isDebugEnabled()) {
- policyLogger.debug("Prepopulating form data for Config Policy selected:"+ policyAdapter.getPolicyName());
- }
- policyAdapter.setPolicyName(policyNameValue);
- String description = "";
- try{
- description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
- }catch(Exception e){
- policyLogger.info("General error", e);
- description = policy.getDescription();
- }
- policyAdapter.setPolicyDescription(description);
-
- ObjectMapper mapper = new ObjectMapper();
-
- TermCollector tc1=null;
- try {
- //Json conversion.
- String data;
- SecurityZone jpaSecurityZone;
- data = entity.getConfigurationData().getConfigBody();
- tc1 = mapper.readValue(data, TermCollector.class);
- List<Object> securityZoneData = commonClassDao.getData(SecurityZone.class);
- for (int i = 0; i < securityZoneData.size() ; i++) {
- jpaSecurityZone = (SecurityZone) securityZoneData.get(i);
- if (jpaSecurityZone.getZoneValue().equals(tc1.getSecurityZoneId())){
- policyAdapter.setSecurityZone(jpaSecurityZone.getZoneName());
- break;
- }
- }
- }
- catch(Exception e) {
- policyLogger.error("Exception Caused while Retriving the JSON body data" +e);
- }
-
- Map<String, String> termTagMap;
- if(tc1 != null){
- for(int i=0;i<tc1.getFirewallRuleList().size();i++){
- termTagMap = new HashMap <>();
- String ruleName= tc1.getFirewallRuleList().get(i).getRuleName();
- String tagPickerName=tc1.getRuleToTag().get(i).getTagPickerName();
- termTagMap.put("key", ruleName);
- termTagMap.put("value", tagPickerName);
- attributeList.add(termTagMap);
- }
- }
- policyAdapter.setAttributes(attributeList);
- // 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 (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();
- if (("ConfigName").equals(attributeId)) {
- policyAdapter.setConfigName(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);
- }
- }
- }
- }
- }
- }
- }
- }
- }
- }
-
- @RequestMapping(value={"/policyController/ViewFWPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
- public ModelAndView setFWViewRule(HttpServletRequest request, HttpServletResponse response){
- try {
- termCollectorList = new ArrayList<>();
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- PolicyRestAdapter policyData = mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.class);
- if(! policyData.getAttributes().isEmpty()){
- for(Object attribute : policyData.getAttributes()){
- if(attribute instanceof LinkedHashMap<?, ?>){
- String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
- termCollectorList.add(key);
- }
- }
- }
- TermList jpaTermList;
- String ruleSrcList;
- String ruleDestList;
- String ruleSrcPort;
- String ruleDestPort;
- String ruleAction;
- List <String> valueDesc;
- StringBuilder displayString = new StringBuilder();
- for (String id : termCollectorList) {
- List<Object> tmList = commonClassDao.getDataById(TermList.class, "termName", id);
- jpaTermList = (TermList) tmList.get(0);
- if (jpaTermList != null){
- ruleSrcList= jpaTermList.getSrcIPList();
- if ((ruleSrcList!= null) && (!ruleSrcList.isEmpty()) && !"null".equals(ruleSrcList)){
- displayString.append("Source IP List: " + jpaTermList.getSrcIPList());
- displayString.append(" ; \t\n");
- for(String srcList:ruleSrcList.split(",")){
- if(srcList.startsWith(GROUP)){
- AddressGroup ag;
- ag= mappingAddressGroup(srcList);
- displayString.append("\n\t"+"Group has :"+(ag != null ? ag.getPrefixList() : "") +"\n");
- if (ag != null) {
- for(String groupItems:ag.getPrefixList().split(",")){
- valueDesc=mapping(groupItems);
- displayString.append("\n\t"+"Name: "+groupItems);
- if(!valueDesc.isEmpty()){
- displayString.append("\n\t"+"Description: "+valueDesc.get(1));
- displayString.append("\n\t"+"Value: "+valueDesc.get(0));
- }
- displayString.append("\n");
- }
- }
- }else{
- if(!srcList.equals(ANY)){
- valueDesc=mapping(srcList);
- displayString.append("\n\t"+"Name: "+srcList);
- displayString.append("\n\t"+"Description: "+valueDesc.get(1));
- displayString.append("\n\t"+"Value: "+valueDesc.get(0));
- displayString.append("\n");
- }
- }
- }
- displayString.append("\n");
- }
- ruleDestList= jpaTermList.getDestIPList();
- if ( ruleDestList!= null && (!ruleDestList.isEmpty())&& ! "null".equals(ruleDestList)){
- displayString.append("Destination IP List: " + jpaTermList.getDestIPList());
- displayString.append(" ; \t\n");
- for(String destList:ruleDestList.split(",")){
- if(destList.startsWith(GROUP)){
- AddressGroup ag;
- ag= mappingAddressGroup(destList);
- displayString.append("\n\t"+"Group has :"+ (ag != null ? ag.getPrefixList() : "") +"\n");
- if (ag != null) {
- for(String groupItems:ag.getPrefixList().split(",")){
- valueDesc=mapping(groupItems);
- displayString.append("\n\t"+"Name: "+groupItems);
- displayString.append("\n\t"+"Description: "+valueDesc.get(1));
- displayString.append("\n\t"+"Value: "+valueDesc.get(0));
- displayString.append("\n\t");
- }
- }
- }else{
- if(!destList.equals(ANY)){
- valueDesc=mapping(destList);
- displayString.append("\n\t"+"Name: "+destList);
- displayString.append("\n\t"+"Description: "+valueDesc.get(1));
- displayString.append("\n\t"+"Value: "+valueDesc.get(0));
- displayString.append("\n\t");
- }
- }
- }
- displayString.append("\n");
- }
-
- ruleSrcPort=jpaTermList.getSrcPortList();
- if ( ruleSrcPort!= null && (!ruleSrcPort.isEmpty())&& !"null".equals(ruleSrcPort)) {
- displayString.append("\n"+"Source Port List:"
- + ruleSrcPort);
- displayString.append(" ; \t\n");
- }
-
- ruleDestPort= jpaTermList.getDestPortList();
- if (ruleDestPort != null && (!ruleDestPort.isEmpty())&& !"null".equals(ruleDestPort)) {
- displayString.append("\n"+"Destination Port List:"
- + ruleDestPort);
- displayString.append(" ; \t\n");
- for(String destServices:ruleDestPort.split(",")){
- if(destServices.startsWith(GROUP)){
- GroupServiceList sg;
- sg= mappingServiceGroup(destServices);
- displayString.append("\n\t"+"Service Group has :"+ (sg != null ? sg.getServiceList() : "") +"\n");
- if (sg != null) {
- for(String groupItems:sg.getServiceList().split(",")){
- ServiceList sl;
- sl= mappingServiceList(groupItems);
- displayString.append("\n\t"+"Name: "+
- sl.getServiceName());
- displayString.append("\n\t"+"Description: "+
- sl.getServiceDescription());
- displayString.append("\n\t"+"Transport-Protocol: "+
- sl.getServiceTransProtocol());
- displayString.append("\n\t"+"Ports: "+
- sl.getServicePorts());
- displayString.append("\n");
- }
- }
- }
- else{
- if(!destServices.equals(ANY)){
- ServiceList sl;
- sl= mappingServiceList(destServices);
- displayString.append("\n\t"+"Name: "+
- sl.getServiceName());
- displayString.append("\n\t"+"Description: "+
- sl.getServiceDescription());
- displayString.append("\n\t"+"Transport-Protocol: "+
- sl.getServiceTransProtocol());
- displayString.append("\n\t"+"Ports: "+
- sl.getServicePorts());
- displayString.append("\n");
- }
- }
- }
- displayString.append("\n");
- }
-
- ruleAction=(jpaTermList).getAction();
- if ( ruleAction!= null && (!ruleAction.isEmpty())) {
- displayString.append("\n"+"Action List:"
- + ruleAction);
- displayString.append(" ; \t\n");
- }
- }
- }
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
-
- PrintWriter out = response.getWriter();
- String responseString = mapper.writeValueAsString(displayString);
- JSONObject j = new JSONObject("{policyData: " + responseString + "}");
- out.write(j.toString());
- return null;
- } catch (Exception e) {
- policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
- }
- return null;
- }
-
- private String constructJson(PolicyRestAdapter policyData) {
- int ruleCount=1;
- //Maps to assosciate the values read from the TermList dictionary
- Map<Integer, String> srcIP_map =null;
- Map<Integer, String> destIP_map=null;
- Map<Integer, String> srcPort_map =null;
- Map<Integer, String> destPort_map =null;
- Map<Integer, String> action_map=null;
- Map<Integer, String> fromZone_map=null;
- Map<Integer, String> toZone_map=null;
-
- String ruleDesc=null;
- String ruleFromZone=null;
- String ruleToZone=null;
- String ruleSrcPrefixList=null;
- String ruleDestPrefixList=null;
- String ruleSrcPort=null;
- String ruleDestPort=null;
- String ruleAction=null;
-
- String json = null;
-
-
- List<String> expandableList = new ArrayList<>();
- TermList jpaTermList;
- TermCollector tc = new TermCollector();
- SecurityZone jpaSecurityZone;
- List<Term> termList = new ArrayList<>();
-
- Tags tags=null;
- List<Tags>tagsList= new ArrayList<>();
-
- TagDefines tagDefine= new TagDefines();
- List<TagDefines> tagList=null;
- ServiceListJson targetSl=null;
- AddressMembers addressMembersJson=null;
- int i=0;
- try{
- String networkRole="";
- for(String tag:tagCollectorList){
- tags= new Tags();
- List<Object> tagListData = commonClassDao.getData(FWTagPicker.class);
- for(int tagCounter=0; tagCounter<tagListData.size(); tagCounter++){
- FWTagPicker jpaTagPickerList=(FWTagPicker) tagListData.get(tagCounter);
- if (jpaTagPickerList.getTagPickerName().equals(tag) ){
- String tagValues=jpaTagPickerList.getTagValues();
- tagList= new ArrayList<>();
- for(String val:tagValues.split("#")) {
- int index=val.indexOf(':');
- String keyToStore=val.substring(0,index);
- String valueToStore=val.substring(index+1,val.length());
-
- tagDefine= new TagDefines();
- tagDefine.setKey(keyToStore);
- tagDefine.setValue(valueToStore);
- //Add to the collection.
- tagList.add(tagDefine);
-
- }
- networkRole=jpaTagPickerList.getNetworkRole();
- break;
- }
- }
- tags.setTags(tagList);
- tags.setTagPickerName(tag);
- tags.setRuleName(termCollectorList.get(i));
- tags.setNetworkRole(networkRole);
- tagsList.add(tags);
- i++;
- }
- tc.setRuleToTag(tagsList);
-
- for (int tl = 0 ; tl< termCollectorList.size(); tl++) {
- expandableList.add(termCollectorList.get(tl));
- Term targetTerm = new Term();
- targetTerm.setRuleName(termCollectorList.get(tl));
- List<Object> termListData = commonClassDao.getData(TermList.class);
- for (int j =0; j < termListData.size(); j++) {
- jpaTermList = (TermList) termListData.get(j);
- if (jpaTermList.getTermName().equals(termCollectorList.get(tl))){
- ruleDesc=jpaTermList.getTermDescription();
- if ((ruleDesc!=null)&& (!ruleDesc.isEmpty())){
- targetTerm.setDescription(ruleDesc);
- }
- ruleFromZone=jpaTermList.getFromZone();
-
- if ((ruleFromZone != null) && (!ruleFromZone.isEmpty())){
- fromZone_map = new HashMap<>();
- fromZone_map.put(tl, ruleFromZone);
- }
- ruleToZone=jpaTermList.getToZone();
-
- if ((ruleToZone != null) && (!ruleToZone.isEmpty())){
- toZone_map = new HashMap<>();
- toZone_map.put(tl, ruleToZone);
- }
- ruleSrcPrefixList=jpaTermList.getSrcIPList();
-
- if ((ruleSrcPrefixList != null) && (!ruleSrcPrefixList.isEmpty())){
- srcIP_map = new HashMap<>();
- srcIP_map.put(tl, ruleSrcPrefixList);
- }
-
- ruleDestPrefixList= jpaTermList.getDestIPList();
- if ((ruleDestPrefixList != null) && (!ruleDestPrefixList.isEmpty())){
- destIP_map = new HashMap<>();
- destIP_map.put(tl, ruleDestPrefixList);
- }
-
- ruleSrcPort=jpaTermList.getSrcPortList();
-
- if (ruleSrcPort != null && (!ruleSrcPort.isEmpty())){
- srcPort_map = new HashMap<>();
- srcPort_map.put(tl, ruleSrcPort);
- }
-
- ruleDestPort= jpaTermList.getDestPortList();
-
- if (ruleDestPort!= null && (!jpaTermList.getDestPortList().isEmpty())){
- destPort_map = new HashMap<>();
- destPort_map.put(tl, ruleDestPort);
- }
-
- ruleAction=jpaTermList.getAction();
-
- if (( ruleAction!= null) && (!ruleAction.isEmpty())){
- action_map = new HashMap<>();
- action_map.put(tl, ruleAction);
- }
- }
- }
- targetTerm.setEnabled(true);
- targetTerm.setLog(true);
- targetTerm.setNegateSource(false);
- targetTerm.setNegateDestination(false);
-
- if(action_map!=null){
- targetTerm.setAction(action_map.get(tl));
- }
-
- //FromZone arrays
- if(fromZone_map!=null){
- List<String> fromZone= new ArrayList<>();
- for(String fromZoneStr:fromZone_map.get(tl).split(",") ){
- fromZone.add(fromZoneStr);
- }
- targetTerm.setFromZones(fromZone);
- }
-
- //ToZone arrays
- if(toZone_map!=null){
- List<String> toZone= new ArrayList<>();
- for(String toZoneStr:toZone_map.get(tl).split(",") ){
- toZone.add(toZoneStr);
- }
- targetTerm.setToZones(toZone);
- }
-
- //Destination Services.
- if(destPort_map!=null){
- Set<ServicesJson> destServicesJsonList= new HashSet<>();
- for(String destServices:destPort_map.get(tl).split(",") ){
- ServicesJson destServicesJson= new ServicesJson();
- destServicesJson.setType("REFERENCE");
- if(destServices.equals(ANY)){
- destServicesJson.setName("any");
- destServicesJsonList.add(destServicesJson);
- break;
- }else{
- if(destServices.startsWith(GROUP)){
- destServicesJson.setName(destServices.substring(6,destServices.length()));
- } else{
- destServicesJson.setName(destServices);
- }
- destServicesJsonList.add(destServicesJson);
- }
- }
- targetTerm.setDestServices(destServicesJsonList);
- }
- //ExpandableServicesList
- if((srcPort_map!=null) && (destPort_map!=null)){
- String servicesCollateString = srcPort_map.get(tl) + "," + destPort_map.get(tl);
- expandableServicesList.add(servicesCollateString);
- }else if (srcPort_map!=null){
- expandableServicesList.add(srcPort_map.get(tl));
- }else if (destPort_map!=null){
- expandableServicesList.add(destPort_map.get(tl));
- }
-
- if(srcIP_map!=null){
- //Source List
- List<AddressJson> sourceListArrayJson= new ArrayList<>();
- for(String srcList:srcIP_map.get(tl).split(",") ){
- AddressJson srcListJson= new AddressJson();
- if(srcList.equals(ANY)){
- srcListJson.setType("any");
- sourceListArrayJson.add(srcListJson);
- break;
- }else{
- srcListJson.setType("REFERENCE");
- if(srcList.startsWith(GROUP)){
- srcListJson.setName(srcList.substring(6,srcList.length()));
- }else{
- srcListJson.setName(srcList);
- }
- sourceListArrayJson.add(srcListJson);
- }
- }
- targetTerm.setSourceList(sourceListArrayJson);
- }
- if(destIP_map!=null){
- //Destination List
- List<AddressJson> destListArrayJson= new ArrayList<>();
- for(String destList:destIP_map.get(tl).split(",")){
- AddressJson destListJson= new AddressJson();
- if(destList.equals(ANY)){
- destListJson.setType("any");
- destListArrayJson.add(destListJson);
- break;
- }else{
- destListJson.setType("REFERENCE");
- if(destList.startsWith(GROUP)){
- destListJson.setName(destList.substring(6,destList.length()));
- }else{
- destListJson.setName(destList);
- }
- destListArrayJson.add(destListJson);
- }
- }
- targetTerm.setDestinationList(destListArrayJson);
- }
- //ExpandablePrefixIPList
- if ((srcIP_map!=null) && (destIP_map!=null))
- {
- String collateString = srcIP_map.get(tl) + "," + destIP_map
- .get(tl);
- expandablePrefixIPList.add(collateString);
- }
- else if(srcIP_map!=null){
- expandablePrefixIPList.add(srcIP_map.get(tl));
- }
- else if(destIP_map!=null){
- expandablePrefixIPList.add(destIP_map.get(tl));
- }
- termList.add(targetTerm);
- targetTerm.setPosition(Integer.toString (ruleCount++));
- }
-
- List<Object> securityZoneData = commonClassDao.getData(SecurityZone.class);
- for (int j =0 ; j< securityZoneData.size() ; j++){
- jpaSecurityZone = (SecurityZone) securityZoneData.get(j);
- if (jpaSecurityZone.getZoneName().equals(policyData.getSecurityZone())){
- tc.setSecurityZoneId(jpaSecurityZone.getZoneValue());
- IdMap idMapInstance= new IdMap();
- idMapInstance.setAstraId(jpaSecurityZone.getZoneValue());
- idMapInstance.setVendorId("deviceGroup:dev");
-
- List<IdMap> idMap = new ArrayList <>();
- idMap.add(idMapInstance);
-
- VendorSpecificData vendorStructure= new VendorSpecificData();
- vendorStructure.setIdMap(idMap);
- tc.setVendorSpecificData(vendorStructure);
- break;
- }
- }
-
- tc.setServiceTypeId("/v0/firewall/pan");
- tc.setConfigName(policyData.getConfigName());
- tc.setVendorServiceId("vipr");
-
- DeployNowJson deployNow= new DeployNowJson();
- deployNow.setDeployNow(false);
-
- tc.setDeploymentOption(deployNow);
-
- Set<ServiceListJson> servListArray = new HashSet<>();
- Set<ServiceGroupJson> servGroupArray= new HashSet<>();
- Set<AddressGroupJson> addrGroupArray= new HashSet<>();
- Set<AddressMembers> addrArray= new HashSet<> ();
-
- ServiceGroupJson targetSg;
- AddressGroupJson addressSg;
- ServiceListJson targetAny;
- ServiceListJson targetAnyTcp;
- ServiceListJson targetAnyUdp;
-
- for(String serviceList:expandableServicesList){
- for(String t: serviceList.split(",")){
- if(!t.startsWith(GROUP)){
- if(!t.equals(ANY)){
- ServiceList sl;
- targetSl= new ServiceListJson();
- sl= mappingServiceList(t);
- targetSl.setName(sl.getServiceName());
- targetSl.setDescription(sl.getServiceDescription());
- targetSl.setTransportProtocol(sl.getServiceTransProtocol());
- targetSl.setType(sl.getServiceType());
- targetSl.setPorts(sl.getServicePorts());
- servListArray.add(targetSl);
- }else{
- //Any for destinationServices.
- //Add names any, any-tcp, any-udp to the serviceGroup object.
- targetAny= new ServiceListJson();
- targetAny.setName("any");
- targetAny.setType("SERVICE");
- targetAny.setTransportProtocol("any");
- targetAny.setPorts("any");
-
- servListArray.add(targetAny);
-
- targetAnyTcp= new ServiceListJson();
- targetAnyTcp.setName("any-tcp");
- targetAnyTcp.setType("SERVICE");
- targetAnyTcp.setTransportProtocol("tcp");
- targetAnyTcp.setPorts("any");
-
- servListArray.add(targetAnyTcp);
-
- targetAnyUdp= new ServiceListJson();
- targetAnyUdp.setName("any-udp");
- targetAnyUdp.setType("SERVICE");
- targetAnyUdp.setTransportProtocol("udp");
- targetAnyUdp.setPorts("any");
-
- servListArray.add(targetAnyUdp);
- }
- }else{//This is a group
- GroupServiceList sg;
- targetSg= new ServiceGroupJson();
- sg= mappingServiceGroup(t);
-
- String name=sg.getGroupName();
- //Removing the "Group_" prepending string before packing the JSON
- targetSg.setName(name.substring(6,name.length()));
- List<ServiceMembers> servMembersList= new ArrayList<>();
-
- for(String groupString: sg.getServiceList().split(",")){
- ServiceMembers serviceMembers= new ServiceMembers();
- serviceMembers.setType("REFERENCE");
- serviceMembers.setName(groupString);
- servMembersList.add(serviceMembers);
- //Expand the group Name
- ServiceList expandGroupSl ;
- targetSl= new ServiceListJson();
- expandGroupSl= mappingServiceList(groupString);
-
- targetSl.setName(expandGroupSl.getServiceName());
- targetSl.setDescription(expandGroupSl.getServiceDescription());
- targetSl.setTransportProtocol(expandGroupSl.getServiceTransProtocol());
- targetSl.setType(expandGroupSl.getServiceType());
- targetSl.setPorts(expandGroupSl.getServicePorts());
- servListArray.add(targetSl);
- }
-
- targetSg.setMembers(servMembersList);
- servGroupArray.add(targetSg);
-
- }
- }
- }
-
- Set<PrefixIPList> prefixIPList = new HashSet<>();
- for(String prefixList:expandablePrefixIPList){
- for(String prefixIP: prefixList.split(",")){
- if(!prefixIP.startsWith(GROUP)){
- if(!prefixIP.equals(ANY)){
- List<AddressMembers> addMembersList= new ArrayList<>();
- List<String> valueDesc;
- PrefixIPList targetAddressList = new PrefixIPList();
- AddressMembers addressMembers= new AddressMembers();
- targetAddressList.setName(prefixIP);
- policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "PrefixList value:"+prefixIP);
- valueDesc = mapping(prefixIP);
- if(!valueDesc.isEmpty()){
- policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "PrefixList description:"+valueDesc.get(1));
- targetAddressList.setDescription(valueDesc.get(1));
- }
-
-
- addressMembers.setType("SUBNET");
- if(!valueDesc.isEmpty()) {
- addressMembers.setValue(valueDesc.get(0));
- }
-
- addMembersList.add(addressMembers);
-
- targetAddressList.setMembers(addMembersList);
- prefixIPList.add(targetAddressList);
- }
- }
- else{//This is a group
- AddressGroup ag;
- addressSg= new AddressGroupJson();
- ag= mappingAddressGroup(prefixIP);
-
- String name=ag.getGroupName();
- //Removing the "Group_" prepending string before packing the JSON
- addressSg.setName(name.substring(6,name.length()));
-
- List<AddressMembersJson> addrMembersList= new ArrayList<>();
- for(String groupString: ag.getPrefixList().split(",")){
- List<String> valueDesc;
- AddressMembersJson addressMembers= new AddressMembersJson();
- addressMembers.setType("REFERENCES");
- addressMembers.setName(groupString);
- addrMembersList.add(addressMembers);
- //Expand the group Name
- addressMembersJson= new AddressMembers();
- valueDesc= mapping (groupString);
-
- addressMembersJson.setName(groupString);
- addressMembersJson.setType("SUBNET");
- addressMembersJson.setValue(valueDesc.get(0));
-
- addrArray.add(addressMembersJson);
-
- }
- addressSg.setMembers(addrMembersList);
- addrGroupArray.add(addressSg);
- }
-
- }
- }
-
- Set<Object> serviceGroup= new HashSet<>();
-
- for(Object obj1:servGroupArray){
- serviceGroup.add(obj1);
- }
-
- for(Object obj:servListArray){
- serviceGroup.add(obj);
- }
-
- Set<Object> addressGroup= new HashSet<>();
-
- for(Object addObj:prefixIPList){
- addressGroup.add(addObj);
- }
-
- for(Object addObj1:addrGroupArray){
- addressGroup.add(addObj1);
- }
-
- for(Object addObj2:addrArray){
- addressGroup.add(addObj2);
- }
-
-
- tc.setServiceGroups(serviceGroup);
- tc.setAddressGroups(addressGroup);
- tc.setFirewallRuleList(termList);
-
- ObjectWriter om = new ObjectMapper().writer();
- try {
- json = om.writeValueAsString(tc);
- } catch (JsonGenerationException e) {
- policyLogger.error("JsonGenerationException Ocured",e);
- } catch (JsonMappingException e) {
- policyLogger.error("IOException Occured",e);
- }
-
- }catch (Exception e) {
- policyLogger.error("Exception Occured"+e);
- }
-
- return json;
- }
+ private static Logger policyLogger = FlexLogger.getLogger(CreateFirewallController.class);
+ private static final String ANY = "ANY";
+ private static final String GROUP = "Group_";
+ private static CommonClassDao commonClassDao;
+ private List<String> tagCollectorList;
+ private List<String> termCollectorList;
+
+ List<String> expandablePrefixIpList = new ArrayList<>();
+ List<String> expandableServicesList = new ArrayList<>();
+
+ @Autowired
+ SessionFactory sessionFactory;
+
+ public CreateFirewallController() {
+ // Empty constructor
+ }
+
+ public static CommonClassDao getCommonClassDao() {
+ return commonClassDao;
+ }
+
+ public static void setCommonClassDao(CommonClassDao commonClassDao) {
+ CreateFirewallController.commonClassDao = commonClassDao;
+ }
+
+ @Autowired
+ private CreateFirewallController(CommonClassDao commonClassDao) {
+ CreateFirewallController.commonClassDao = commonClassDao;
+ }
+
+ /**
+ * setDataToPolicyRestAdapter.
+ *
+ * @param policyData PolicyRestAdapter
+ * @return PolicyRestAdapter
+ */
+ public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData) {
+ termCollectorList = new ArrayList<>();
+ tagCollectorList = new ArrayList<>();
+ if (!policyData.getAttributes().isEmpty()) {
+ for (Object attribute : policyData.getAttributes()) {
+ if (attribute instanceof LinkedHashMap<?, ?>) {
+ String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
+ termCollectorList.add(key);
+
+ String tag = ((LinkedHashMap<?, ?>) attribute).get("value").toString();
+ tagCollectorList.add(tag);
+ }
+ }
+ }
+ String jsonBody = constructJson(policyData);
+ if (StringUtils.isBlank(jsonBody)) {
+ policyData.setJsonBody(jsonBody);
+ } else {
+ policyData.setJsonBody("{}");
+ }
+ //
+ // Hmmm - seems to be overriding the previous if statement
+ //
+ policyData.setJsonBody(jsonBody);
+
+ return policyData;
+ }
+
+ private List<String> mapping(String expandableList) {
+ String value;
+ String desc;
+ List<String> valueDesc = new ArrayList<>();
+ List<Object> prefixListData = commonClassDao.getData(PrefixList.class);
+ for (int i = 0; i < prefixListData.size(); i++) {
+ PrefixList prefixList = (PrefixList) prefixListData.get(i);
+ if (prefixList.getPrefixListName().equals(expandableList)) {
+ value = prefixList.getPrefixListValue();
+ valueDesc.add(value);
+ desc = prefixList.getDescription();
+ valueDesc.add(desc);
+ break;
+ }
+ }
+ return valueDesc;
+ }
+
+ private ServiceList mappingServiceList(String expandableList) {
+ ServiceList serviceList = null;
+ List<Object> serviceListData = commonClassDao.getData(ServiceList.class);
+ for (int i = 0; i < serviceListData.size(); i++) {
+ serviceList = (ServiceList) serviceListData.get(i);
+ if (serviceList.getServiceName().equals(expandableList)) {
+ break;
+ }
+ }
+ return serviceList;
+ }
+
+ private GroupServiceList mappingServiceGroup(String expandableList) {
+
+ GroupServiceList serviceGroup = null;
+ List<Object> serviceGroupData = commonClassDao.getData(GroupServiceList.class);
+ for (int i = 0; i < serviceGroupData.size(); i++) {
+ serviceGroup = (GroupServiceList) serviceGroupData.get(i);
+ if (serviceGroup.getGroupName().equals(expandableList)) {
+ break;
+ }
+ }
+ return serviceGroup;
+ }
+
+ private AddressGroup mappingAddressGroup(String expandableList) {
+
+ AddressGroup addressGroup = null;
+ List<Object> addressGroupData = commonClassDao.getData(AddressGroup.class);
+ for (int i = 0; i < addressGroupData.size(); i++) {
+ addressGroup = (AddressGroup) addressGroupData.get(i);
+ if (addressGroup.getGroupName().equals(expandableList)) {
+ break;
+ }
+ }
+ return addressGroup;
+ }
+
+ public void prePopulateFWPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+ ArrayList<Object> attributeList;
+ attributeList = new ArrayList<>();
+ if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+ return;
+ }
+ Object policyData = policyAdapter.getPolicyData();
+ PolicyType policy = (PolicyType) policyData;
+ // policy name value is the policy name without any prefix and Extensions.
+ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+ String policyNameValue =
+ policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("FW_") + 3);
+ if (policyLogger.isDebugEnabled()) {
+ policyLogger
+ .debug("Prepopulating form data for Config Policy selected:" + policyAdapter.getPolicyName());
+ }
+ policyAdapter.setPolicyName(policyNameValue);
+ String description = "";
+ try {
+ description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+ } catch (Exception e) {
+ policyLogger.info("General error", e);
+ description = policy.getDescription();
+ }
+ policyAdapter.setPolicyDescription(description);
+
+ ObjectMapper mapper = new ObjectMapper();
+
+ TermCollector tc1 = null;
+ try {
+ // Json conversion.
+ String data;
+ SecurityZone jpaSecurityZone;
+ data = entity.getConfigurationData().getConfigBody();
+ tc1 = mapper.readValue(data, TermCollector.class);
+ List<Object> securityZoneData = commonClassDao.getData(SecurityZone.class);
+ for (int i = 0; i < securityZoneData.size(); i++) {
+ jpaSecurityZone = (SecurityZone) securityZoneData.get(i);
+ if (jpaSecurityZone.getZoneValue().equals(tc1.getSecurityZoneId())) {
+ policyAdapter.setSecurityZone(jpaSecurityZone.getZoneName());
+ break;
+ }
+ }
+ } catch (Exception e) {
+ policyLogger.error("Exception Caused while Retriving the JSON body data" + e);
+ }
+
+ Map<String, String> termTagMap;
+ if (tc1 != null) {
+ for (int i = 0; i < tc1.getFirewallRuleList().size(); i++) {
+ termTagMap = new HashMap<>();
+ String ruleName = tc1.getFirewallRuleList().get(i).getRuleName();
+ String tagPickerName = tc1.getRuleToTag().get(i).getTagPickerName();
+ termTagMap.put("key", ruleName);
+ termTagMap.put("value", tagPickerName);
+ attributeList.add(termTagMap);
+ }
+ }
+ policyAdapter.setAttributes(attributeList);
+ // Get the target data under policy.
+ TargetType target = policy.getTarget();
+ if (target == null) {
+ return;
+ }
+ // Under target we have AnyOFType
+ // NOTE: target.getAnyOf() will never be null
+ for (AnyOfType anyOf : target.getAnyOf()) {
+ for (AllOfType allOf : anyOf.getAllOf()) {
+ for (MatchType match : allOf.getMatch()) {
+ //
+ // Under the match we have attribute value and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ policyAdapter.setupUsingAttribute(match.getAttributeDesignator().getAttributeId(),
+ (String) match.getAttributeValue().getContent().get(0));
+ }
+ }
+ }
+ }
+
+ /**
+ * setFWViewRule.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @return ModelAndView
+ */
+ @RequestMapping(
+ value = {"/policyController/ViewFWPolicyRule.htm"},
+ method = {org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView setFWViewRule(HttpServletRequest request, HttpServletResponse response) {
+ try {
+ termCollectorList = new ArrayList<>();
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ PolicyRestAdapter policyData = mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.class);
+ if (!policyData.getAttributes().isEmpty()) {
+ for (Object attribute : policyData.getAttributes()) {
+ if (attribute instanceof LinkedHashMap<?, ?>) {
+ String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
+ termCollectorList.add(key);
+ }
+ }
+ }
+ TermList jpaTermList;
+ String ruleSrcList;
+ String ruleDestList;
+ String ruleSrcPort;
+ String ruleDestPort;
+ String ruleAction;
+ List<String> valueDesc;
+ StringBuilder displayString = new StringBuilder();
+ for (String id : termCollectorList) {
+ List<Object> tmList = commonClassDao.getDataById(TermList.class, "termName", id);
+ jpaTermList = (TermList) tmList.get(0);
+ if (jpaTermList != null) {
+ ruleSrcList = jpaTermList.getSrcIpList();
+ if ((ruleSrcList != null) && (!ruleSrcList.isEmpty()) && !"null".equals(ruleSrcList)) {
+ displayString.append("Source IP List: " + jpaTermList.getSrcIpList());
+ displayString.append(" ; \t\n");
+ for (String srcList : ruleSrcList.split(",")) {
+ if (srcList.startsWith(GROUP)) {
+ AddressGroup ag;
+ ag = mappingAddressGroup(srcList);
+ displayString.append(
+ "\n\t" + "Group has :" + (ag != null ? ag.getPrefixList() : "") + "\n");
+ if (ag != null) {
+ for (String groupItems : ag.getPrefixList().split(",")) {
+ valueDesc = mapping(groupItems);
+ displayString.append("\n\t" + "Name: " + groupItems);
+ if (!valueDesc.isEmpty()) {
+ displayString.append("\n\t" + "Description: " + valueDesc.get(1));
+ displayString.append("\n\t" + "Value: " + valueDesc.get(0));
+ }
+ displayString.append("\n");
+ }
+ }
+ } else {
+ if (!srcList.equals(ANY)) {
+ valueDesc = mapping(srcList);
+ displayString.append("\n\t" + "Name: " + srcList);
+ displayString.append("\n\t" + "Description: " + valueDesc.get(1));
+ displayString.append("\n\t" + "Value: " + valueDesc.get(0));
+ displayString.append("\n");
+ }
+ }
+ }
+ displayString.append("\n");
+ }
+ ruleDestList = jpaTermList.getDestIpList();
+ if (ruleDestList != null && (!ruleDestList.isEmpty()) && !"null".equals(ruleDestList)) {
+ displayString.append("Destination IP List: " + jpaTermList.getDestIpList());
+ displayString.append(" ; \t\n");
+ for (String destList : ruleDestList.split(",")) {
+ if (destList.startsWith(GROUP)) {
+ AddressGroup ag;
+ ag = mappingAddressGroup(destList);
+ displayString.append(
+ "\n\t" + "Group has :" + (ag != null ? ag.getPrefixList() : "") + "\n");
+ if (ag != null) {
+ for (String groupItems : ag.getPrefixList().split(",")) {
+ valueDesc = mapping(groupItems);
+ displayString.append("\n\t" + "Name: " + groupItems);
+ displayString.append("\n\t" + "Description: " + valueDesc.get(1));
+ displayString.append("\n\t" + "Value: " + valueDesc.get(0));
+ displayString.append("\n\t");
+ }
+ }
+ } else {
+ if (!destList.equals(ANY)) {
+ valueDesc = mapping(destList);
+ displayString.append("\n\t" + "Name: " + destList);
+ displayString.append("\n\t" + "Description: " + valueDesc.get(1));
+ displayString.append("\n\t" + "Value: " + valueDesc.get(0));
+ displayString.append("\n\t");
+ }
+ }
+ }
+ displayString.append("\n");
+ }
+
+ ruleSrcPort = jpaTermList.getSrcPortList();
+ if (ruleSrcPort != null && (!ruleSrcPort.isEmpty()) && !"null".equals(ruleSrcPort)) {
+ displayString.append("\n" + "Source Port List:" + ruleSrcPort);
+ displayString.append(" ; \t\n");
+ }
+
+ ruleDestPort = jpaTermList.getDestPortList();
+ if (ruleDestPort != null && (!ruleDestPort.isEmpty()) && !"null".equals(ruleDestPort)) {
+ displayString.append("\n" + "Destination Port List:" + ruleDestPort);
+ displayString.append(" ; \t\n");
+ for (String destServices : ruleDestPort.split(",")) {
+ if (destServices.startsWith(GROUP)) {
+ GroupServiceList sg;
+ sg = mappingServiceGroup(destServices);
+ displayString.append("\n\t" + "Service Group has :"
+ + (sg != null ? sg.getServiceList() : "") + "\n");
+ if (sg != null) {
+ for (String groupItems : sg.getServiceList().split(",")) {
+ ServiceList sl;
+ sl = mappingServiceList(groupItems);
+ displayString.append("\n\t" + "Name: " + sl.getServiceName());
+ displayString.append("\n\t" + "Description: " + sl.getServiceDescription());
+ displayString.append(
+ "\n\t" + "Transport-Protocol: " + sl.getServiceTransportProtocol());
+ displayString.append("\n\t" + "Ports: " + sl.getServicePorts());
+ displayString.append("\n");
+ }
+ }
+ } else {
+ if (!destServices.equals(ANY)) {
+ ServiceList sl;
+ sl = mappingServiceList(destServices);
+ displayString.append("\n\t" + "Name: " + sl.getServiceName());
+ displayString.append("\n\t" + "Description: " + sl.getServiceDescription());
+ displayString
+ .append("\n\t" + "Transport-Protocol: " + sl.getServiceTransportProtocol());
+ displayString.append("\n\t" + "Ports: " + sl.getServicePorts());
+ displayString.append("\n");
+ }
+ }
+ }
+ displayString.append("\n");
+ }
+
+ ruleAction = (jpaTermList).getAction();
+ if (ruleAction != null && (!ruleAction.isEmpty())) {
+ displayString.append("\n" + "Action List:" + ruleAction);
+ displayString.append(" ; \t\n");
+ }
+ }
+ }
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+
+ String responseString = mapper.writeValueAsString(displayString);
+ response.getWriter().write(new JSONObject("{policyData: " + responseString + "}").toString());
+ return null;
+ } catch (Exception e) {
+ policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
+ }
+ return null;
+ }
+
+ private String constructJson(PolicyRestAdapter policyData) {
+ int ruleCount = 1;
+ // Maps to assosciate the values read from the TermList dictionary
+ Map<Integer, String> mapSrcIp = null;
+ Map<Integer, String> mapDestIP = null;
+ Map<Integer, String> mapSrcPort = null;
+ Map<Integer, String> mapDestPort = null;
+ Map<Integer, String> mapAction = null;
+ Map<Integer, String> mapFromZone = null;
+ Map<Integer, String> mapToZone = null;
+
+ String ruleDesc = null;
+ String ruleFromZone = null;
+ String ruleToZone = null;
+ String ruleSrcPrefixList = null;
+ String ruleDestPrefixList = null;
+ String ruleSrcPort = null;
+ String ruleDestPort = null;
+ String ruleAction = null;
+
+ String json = null;
+
+ List<String> expandableList = new ArrayList<>();
+ TermList jpaTermList;
+ TermCollector tc = new TermCollector();
+ SecurityZone jpaSecurityZone;
+ List<Term> termList = new ArrayList<>();
+
+ Tags tags = null;
+ List<Tags> tagsList = new ArrayList<>();
+
+ TagDefines tagDefine = new TagDefines();
+ List<TagDefines> tagList = null;
+ ServiceListJson targetSl = null;
+ AddressMembers addressMembersJson = null;
+ int intCounter = 0;
+ try {
+ String networkRole = "";
+ for (String tag : tagCollectorList) {
+ tags = new Tags();
+ List<Object> tagListData = commonClassDao.getData(FwTagPicker.class);
+ for (int tagCounter = 0; tagCounter < tagListData.size(); tagCounter++) {
+ FwTagPicker jpaTagPickerList = (FwTagPicker) tagListData.get(tagCounter);
+ if (jpaTagPickerList.getTagPickerName().equals(tag)) {
+ String tagValues = jpaTagPickerList.getTagValues();
+ tagList = new ArrayList<>();
+ for (String val : tagValues.split("#")) {
+ int index = val.indexOf(':');
+ String keyToStore = val.substring(0, index);
+ String valueToStore = val.substring(index + 1, val.length());
+
+ tagDefine = new TagDefines();
+ tagDefine.setKey(keyToStore);
+ tagDefine.setValue(valueToStore);
+ // Add to the collection.
+ tagList.add(tagDefine);
+
+ }
+ networkRole = jpaTagPickerList.getNetworkRole();
+ break;
+ }
+ }
+ tags.setTags(tagList);
+ tags.setTagPickerName(tag);
+ tags.setRuleName(termCollectorList.get(intCounter));
+ tags.setNetworkRole(networkRole);
+ tagsList.add(tags);
+ intCounter++;
+ }
+ tc.setRuleToTag(tagsList);
+
+ for (int tl = 0; tl < termCollectorList.size(); tl++) {
+ expandableList.add(termCollectorList.get(tl));
+ Term targetTerm = new Term();
+ targetTerm.setRuleName(termCollectorList.get(tl));
+ List<Object> termListData = commonClassDao.getData(TermList.class);
+ for (int j = 0; j < termListData.size(); j++) {
+ jpaTermList = (TermList) termListData.get(j);
+ if (jpaTermList.getTermName().equals(termCollectorList.get(tl))) {
+ ruleDesc = jpaTermList.getDescription();
+ if ((ruleDesc != null) && (!ruleDesc.isEmpty())) {
+ targetTerm.setDescription(ruleDesc);
+ }
+ ruleFromZone = jpaTermList.getFromZone();
+
+ if ((ruleFromZone != null) && (!ruleFromZone.isEmpty())) {
+ mapFromZone = new HashMap<>();
+ mapFromZone.put(tl, ruleFromZone);
+ }
+ ruleToZone = jpaTermList.getToZone();
+
+ if ((ruleToZone != null) && (!ruleToZone.isEmpty())) {
+ mapToZone = new HashMap<>();
+ mapToZone.put(tl, ruleToZone);
+ }
+ ruleSrcPrefixList = jpaTermList.getSrcIpList();
+
+ if ((ruleSrcPrefixList != null) && (!ruleSrcPrefixList.isEmpty())) {
+ mapSrcIp = new HashMap<>();
+ mapSrcIp.put(tl, ruleSrcPrefixList);
+ }
+
+ ruleDestPrefixList = jpaTermList.getDestIpList();
+ if ((ruleDestPrefixList != null) && (!ruleDestPrefixList.isEmpty())) {
+ mapDestIP = new HashMap<>();
+ mapDestIP.put(tl, ruleDestPrefixList);
+ }
+
+ ruleSrcPort = jpaTermList.getSrcPortList();
+
+ if (ruleSrcPort != null && (!ruleSrcPort.isEmpty())) {
+ mapSrcPort = new HashMap<>();
+ mapSrcPort.put(tl, ruleSrcPort);
+ }
+
+ ruleDestPort = jpaTermList.getDestPortList();
+
+ if (ruleDestPort != null && (!jpaTermList.getDestPortList().isEmpty())) {
+ mapDestPort = new HashMap<>();
+ mapDestPort.put(tl, ruleDestPort);
+ }
+
+ ruleAction = jpaTermList.getAction();
+
+ if ((ruleAction != null) && (!ruleAction.isEmpty())) {
+ mapAction = new HashMap<>();
+ mapAction.put(tl, ruleAction);
+ }
+ }
+ }
+ targetTerm.setEnabled(true);
+ targetTerm.setLog(true);
+ targetTerm.setNegateSource(false);
+ targetTerm.setNegateDestination(false);
+
+ if (mapAction != null) {
+ targetTerm.setAction(mapAction.get(tl));
+ }
+
+ // FromZone arrays
+ if (mapFromZone != null) {
+ List<String> fromZone = new ArrayList<>();
+ for (String fromZoneStr : mapFromZone.get(tl).split(",")) {
+ fromZone.add(fromZoneStr);
+ }
+ targetTerm.setFromZones(fromZone);
+ }
+
+ // ToZone arrays
+ if (mapToZone != null) {
+ List<String> toZone = new ArrayList<>();
+ for (String toZoneStr : mapToZone.get(tl).split(",")) {
+ toZone.add(toZoneStr);
+ }
+ targetTerm.setToZones(toZone);
+ }
+
+ // Destination Services.
+ if (mapDestPort != null) {
+ Set<ServicesJson> destServicesJsonList = new HashSet<>();
+ for (String destServices : mapDestPort.get(tl).split(",")) {
+ ServicesJson destServicesJson = new ServicesJson();
+ destServicesJson.setType("REFERENCE");
+ if (destServices.equals(ANY)) {
+ destServicesJson.setName("any");
+ destServicesJsonList.add(destServicesJson);
+ break;
+ } else {
+ if (destServices.startsWith(GROUP)) {
+ destServicesJson.setName(destServices.substring(6, destServices.length()));
+ } else {
+ destServicesJson.setName(destServices);
+ }
+ destServicesJsonList.add(destServicesJson);
+ }
+ }
+ targetTerm.setDestServices(destServicesJsonList);
+ }
+ // ExpandableServicesList
+ if ((mapSrcPort != null) && (mapDestPort != null)) {
+ String servicesCollateString = mapSrcPort.get(tl) + "," + mapDestPort.get(tl);
+ expandableServicesList.add(servicesCollateString);
+ } else if (mapSrcPort != null) {
+ expandableServicesList.add(mapSrcPort.get(tl));
+ } else if (mapDestPort != null) {
+ expandableServicesList.add(mapDestPort.get(tl));
+ }
+
+ if (mapSrcIp != null) {
+ // Source List
+ List<AddressJson> sourceListArrayJson = new ArrayList<>();
+ for (String srcList : mapSrcIp.get(tl).split(",")) {
+ AddressJson srcListJson = new AddressJson();
+ if (srcList.equals(ANY)) {
+ srcListJson.setType("any");
+ sourceListArrayJson.add(srcListJson);
+ break;
+ } else {
+ srcListJson.setType("REFERENCE");
+ if (srcList.startsWith(GROUP)) {
+ srcListJson.setName(srcList.substring(6, srcList.length()));
+ } else {
+ srcListJson.setName(srcList);
+ }
+ sourceListArrayJson.add(srcListJson);
+ }
+ }
+ targetTerm.setSourceList(sourceListArrayJson);
+ }
+ if (mapDestIP != null) {
+ // Destination List
+ List<AddressJson> destListArrayJson = new ArrayList<>();
+ for (String destList : mapDestIP.get(tl).split(",")) {
+ AddressJson destListJson = new AddressJson();
+ if (destList.equals(ANY)) {
+ destListJson.setType("any");
+ destListArrayJson.add(destListJson);
+ break;
+ } else {
+ destListJson.setType("REFERENCE");
+ if (destList.startsWith(GROUP)) {
+ destListJson.setName(destList.substring(6, destList.length()));
+ } else {
+ destListJson.setName(destList);
+ }
+ destListArrayJson.add(destListJson);
+ }
+ }
+ targetTerm.setDestinationList(destListArrayJson);
+ }
+ // ExpandablePrefixIPList
+ if ((mapSrcIp != null) && (mapDestIP != null)) {
+ String collateString = mapSrcIp.get(tl) + "," + mapDestIP.get(tl);
+ expandablePrefixIpList.add(collateString);
+ } else if (mapSrcIp != null) {
+ expandablePrefixIpList.add(mapSrcIp.get(tl));
+ } else if (mapDestIP != null) {
+ expandablePrefixIpList.add(mapDestIP.get(tl));
+ }
+ termList.add(targetTerm);
+ targetTerm.setPosition(Integer.toString(ruleCount++));
+ }
+
+ List<Object> securityZoneData = commonClassDao.getData(SecurityZone.class);
+ for (int j = 0; j < securityZoneData.size(); j++) {
+ jpaSecurityZone = (SecurityZone) securityZoneData.get(j);
+ if (jpaSecurityZone.getZoneName().equals(policyData.getSecurityZone())) {
+ tc.setSecurityZoneId(jpaSecurityZone.getZoneValue());
+ IdMap idMapInstance = new IdMap();
+ idMapInstance.setAstraId(jpaSecurityZone.getZoneValue());
+ idMapInstance.setVendorId("deviceGroup:dev");
+
+ List<IdMap> idMap = new ArrayList<>();
+ idMap.add(idMapInstance);
+
+ VendorSpecificData vendorStructure = new VendorSpecificData();
+ vendorStructure.setIdMap(idMap);
+ tc.setVendorSpecificData(vendorStructure);
+ break;
+ }
+ }
+
+ tc.setServiceTypeId("/v0/firewall/pan");
+ tc.setConfigName(policyData.getConfigName());
+ tc.setVendorServiceId("vipr");
+
+ DeployNowJson deployNow = new DeployNowJson();
+ deployNow.setDeployNow(false);
+
+ tc.setDeploymentOption(deployNow);
+
+ Set<ServiceListJson> servListArray = new HashSet<>();
+ Set<ServiceGroupJson> servGroupArray = new HashSet<>();
+ Set<AddressGroupJson> addrGroupArray = new HashSet<>();
+ Set<AddressMembers> addrArray = new HashSet<>();
+
+ ServiceGroupJson targetSg;
+ AddressGroupJson addressSg;
+ ServiceListJson targetAny;
+ ServiceListJson targetAnyTcp;
+ ServiceListJson targetAnyUdp;
+
+ for (String serviceList : expandableServicesList) {
+ for (String t : serviceList.split(",")) {
+ if (!t.startsWith(GROUP)) {
+ if (!t.equals(ANY)) {
+ ServiceList sl;
+ targetSl = new ServiceListJson();
+ sl = mappingServiceList(t);
+ targetSl.setName(sl.getServiceName());
+ targetSl.setDescription(sl.getServiceDescription());
+ targetSl.setTransportProtocol(sl.getServiceTransportProtocol());
+ targetSl.setType(sl.getServiceType());
+ targetSl.setPorts(sl.getServicePorts());
+ servListArray.add(targetSl);
+ } else {
+ // Any for destinationServices.
+ // Add names any, any-tcp, any-udp to the serviceGroup object.
+ targetAny = new ServiceListJson();
+ targetAny.setName("any");
+ targetAny.setType("SERVICE");
+ targetAny.setTransportProtocol("any");
+ targetAny.setPorts("any");
+
+ servListArray.add(targetAny);
+
+ targetAnyTcp = new ServiceListJson();
+ targetAnyTcp.setName("any-tcp");
+ targetAnyTcp.setType("SERVICE");
+ targetAnyTcp.setTransportProtocol("tcp");
+ targetAnyTcp.setPorts("any");
+
+ servListArray.add(targetAnyTcp);
+
+ targetAnyUdp = new ServiceListJson();
+ targetAnyUdp.setName("any-udp");
+ targetAnyUdp.setType("SERVICE");
+ targetAnyUdp.setTransportProtocol("udp");
+ targetAnyUdp.setPorts("any");
+
+ servListArray.add(targetAnyUdp);
+ }
+ } else { // This is a group
+ GroupServiceList sg;
+ targetSg = new ServiceGroupJson();
+ sg = mappingServiceGroup(t);
+
+ String name = sg.getGroupName();
+ // Removing the "Group_" prepending string before packing the JSON
+ targetSg.setName(name.substring(6, name.length()));
+ List<ServiceMembers> servMembersList = new ArrayList<>();
+
+ for (String groupString : sg.getServiceList().split(",")) {
+ ServiceMembers serviceMembers = new ServiceMembers();
+ serviceMembers.setType("REFERENCE");
+ serviceMembers.setName(groupString);
+ servMembersList.add(serviceMembers);
+ // Expand the group Name
+ ServiceList expandGroupSl;
+ targetSl = new ServiceListJson();
+ expandGroupSl = mappingServiceList(groupString);
+
+ targetSl.setName(expandGroupSl.getServiceName());
+ targetSl.setDescription(expandGroupSl.getServiceDescription());
+ targetSl.setTransportProtocol(expandGroupSl.getServiceTransportProtocol());
+ targetSl.setType(expandGroupSl.getServiceType());
+ targetSl.setPorts(expandGroupSl.getServicePorts());
+ servListArray.add(targetSl);
+ }
+
+ targetSg.setMembers(servMembersList);
+ servGroupArray.add(targetSg);
+
+ }
+ }
+ }
+
+ Set<PrefixIPList> prefixIpList = new HashSet<>();
+ for (String prefixList : expandablePrefixIpList) {
+ for (String prefixIP : prefixList.split(",")) {
+ if (!prefixIP.startsWith(GROUP)) {
+ if (!prefixIP.equals(ANY)) {
+ List<String> valueDesc;
+ PrefixIPList targetAddressList = new PrefixIPList();
+ targetAddressList.setName(prefixIP);
+ policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "PrefixList value:" + prefixIP);
+ valueDesc = mapping(prefixIP);
+ if (!valueDesc.isEmpty()) {
+ policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "PrefixList description:"
+ + valueDesc.get(1));
+ targetAddressList.setDescription(valueDesc.get(1));
+ }
+ AddressMembers addressMembers = new AddressMembers();
+ addressMembers.setType("SUBNET");
+ if (!valueDesc.isEmpty()) {
+ addressMembers.setValue(valueDesc.get(0));
+ }
+ List<AddressMembers> addMembersList = new ArrayList<>();
+ addMembersList.add(addressMembers);
+
+ targetAddressList.setMembers(addMembersList);
+ prefixIpList.add(targetAddressList);
+ }
+ } else { // This is a group
+ AddressGroup ag;
+ addressSg = new AddressGroupJson();
+ ag = mappingAddressGroup(prefixIP);
+
+ String name = ag.getGroupName();
+ // Removing the "Group_" prepending string before packing the JSON
+ addressSg.setName(name.substring(6, name.length()));
+
+ List<AddressMembersJson> addrMembersList = new ArrayList<>();
+ for (String groupString : ag.getPrefixList().split(",")) {
+ AddressMembersJson addressMembers = new AddressMembersJson();
+ addressMembers.setType("REFERENCES");
+ addressMembers.setName(groupString);
+ addrMembersList.add(addressMembers);
+ // Expand the group Name
+ addressMembersJson = new AddressMembers();
+ List<String> valueDesc = mapping(groupString);
+
+ addressMembersJson.setName(groupString);
+ addressMembersJson.setType("SUBNET");
+ addressMembersJson.setValue(valueDesc.get(0));
+
+ addrArray.add(addressMembersJson);
+
+ }
+ addressSg.setMembers(addrMembersList);
+ addrGroupArray.add(addressSg);
+ }
+
+ }
+ }
+
+ Set<Object> serviceGroup = new HashSet<>();
+
+ for (Object obj1 : servGroupArray) {
+ serviceGroup.add(obj1);
+ }
+
+ for (Object obj : servListArray) {
+ serviceGroup.add(obj);
+ }
+
+ Set<Object> addressGroup = new HashSet<>();
+
+ for (Object addObj : prefixIpList) {
+ addressGroup.add(addObj);
+ }
+
+ for (Object addObj1 : addrGroupArray) {
+ addressGroup.add(addObj1);
+ }
+
+ for (Object addObj2 : addrArray) {
+ addressGroup.add(addObj2);
+ }
+
+ tc.setServiceGroups(serviceGroup);
+ tc.setAddressGroups(addressGroup);
+ tc.setFirewallRuleList(termList);
+
+ try {
+ json = new ObjectMapper().writer().writeValueAsString(tc);
+ } catch (JsonGenerationException e) {
+ policyLogger.error("JsonGenerationException Ocured", e);
+ } catch (JsonMappingException e) {
+ policyLogger.error("IOException Occured", e);
+ }
+
+ } catch (Exception e) {
+ policyLogger.error("Exception Occured" + e);
+ }
+
+ return json;
+ }
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateOptimizationController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateOptimizationController.java
index 05fddb50d..37f543f35 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateOptimizationController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateOptimizationController.java
@@ -20,7 +20,6 @@
package org.onap.policy.controller;
-
import com.att.research.xacml.util.XACMLProperties;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
@@ -28,13 +27,13 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.google.gson.Gson;
+
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
-import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
@@ -49,15 +48,17 @@ import java.util.Set;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
+
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import lombok.Getter;
+import lombok.Setter;
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;
@@ -68,15 +69,16 @@ import org.json.JSONArray;
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.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
import org.onap.policy.rest.dao.CommonClassDao;
import org.onap.policy.rest.jpa.MicroserviceHeaderdeFaults;
import org.onap.policy.rest.jpa.OptimizationModels;
import org.onap.policy.rest.jpa.PolicyEntity;
-import org.onap.policy.rest.util.MSAttributeObject;
-import org.onap.policy.rest.util.MSModelUtils;
-import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE;
+import org.onap.policy.rest.util.MsAttributeObject;
+import org.onap.policy.rest.util.MsModelUtils;
+import org.onap.policy.rest.util.MsModelUtils.ModelType;
+import org.onap.policy.utils.PolicyUtils;
import org.onap.portalsdk.core.controller.RestrictedBaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@@ -87,6 +89,9 @@ import org.springframework.web.servlet.ModelAndView;
@RequestMapping("/")
public class CreateOptimizationController extends RestrictedBaseController {
private static final Logger LOGGER = FlexLogger.getLogger(CreateOptimizationController.class);
+
+ private static final int BUFFER = 2048;
+
private static CommonClassDao commonClassDao;
public static CommonClassDao getCommonClassDao() {
@@ -98,7 +103,7 @@ public class CreateOptimizationController extends RestrictedBaseController {
private String directory;
private List<String> modelList = new ArrayList<>();
private List<String> dirDependencyList = new ArrayList<>();
- private LinkedHashMap<String, MSAttributeObject> classMap = new LinkedHashMap<>();
+ private LinkedHashMap<String, MsAttributeObject> classMap = new LinkedHashMap<>();
String referenceAttributes;
String attributeString;
Set<String> allManyTrueKeys = new HashSet<>();
@@ -115,10 +120,7 @@ public class CreateOptimizationController extends RestrictedBaseController {
public static final String MANYFALSE = ":MANY-false";
public static final String MODEL = "model";
public static final String MANY = "MANY-";
- public static final String UTF8 = "UTF-8";
public static final String MODELNAME = "modelName";
- public static final String APPLICATIONJSON = "application / json";
-
@Autowired
private CreateOptimizationController(CommonClassDao commonClassDao) {
@@ -138,6 +140,13 @@ public class CreateOptimizationController extends RestrictedBaseController {
private Map<String, LinkedList<String>> arrayTextList = new HashMap<>();
CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController();
+ /**
+ * setDataToPolicyRestAdapter.
+ *
+ * @param policyData PolicyRestAdapter
+ * @param root JsonNode
+ * @return PolicyRestAdapter
+ */
public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) {
String jsonContent = null;
try {
@@ -175,7 +184,7 @@ public class CreateOptimizationController extends RestrictedBaseController {
}
LOGGER.info("input json: " + json);
LOGGER.info("input jsonContent: " + jsonContent);
- String cleanJson = msController.cleanUPJson(json);
+ String cleanJson = msController.cleanUpJson(json);
// --- reset empty value back after called cleanUPJson method and before calling removeNullAttributes
String tempJson =
@@ -186,7 +195,16 @@ public class CreateOptimizationController extends RestrictedBaseController {
return policyAdapter;
}
- @RequestMapping(value = {"/policyController/getOptimizationTemplateData.htm"},
+ /**
+ * getOptimizationTemplateData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @return ModelAndView
+ * @throws IOException IOException
+ */
+ @RequestMapping(
+ value = {"/policyController/getOptimizationTemplateData.htm"},
method = {org.springframework.web.bind.annotation.RequestMethod.POST})
public ModelAndView getOptimizationTemplateData(HttpServletRequest request, HttpServletResponse response)
throws IOException {
@@ -196,10 +214,10 @@ public class CreateOptimizationController extends RestrictedBaseController {
JsonNode root = mapper.readTree(request.getReader());
String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
- String servicename = value.toString().split("-v")[0];
+ String servicename = value.split("-v")[0];
String version = null;
- if (value.toString().contains("-v")) {
- version = value.toString().split("-v")[1];
+ if (value.contains("-v")) {
+ version = value.split("-v")[1];
}
OptimizationModels returnModel = getAttributeObject(servicename, version);
@@ -226,8 +244,7 @@ public class CreateOptimizationController extends RestrictedBaseController {
// Get all keys with "MANY-true" defined in their value from subAttribute
Set<String> allkeys = null;
if (returnModel.getSubattributes() != null && !returnModel.getSubattributes().isEmpty()) {
- JSONObject json = new JSONObject(returnModel.getSubattributes());
- getAllKeys(json);
+ getAllKeys(new JSONObject(returnModel.getSubattributes()));
allkeys = allManyTrueKeys;
allManyTrueKeys = new HashSet<>();
LOGGER.info("allkeys : " + allkeys);
@@ -276,23 +293,22 @@ public class CreateOptimizationController extends RestrictedBaseController {
jsonModel = finalJsonObject.toString();
}
- response.setCharacterEncoding(UTF8);
- response.setContentType(APPLICATIONJSON);
- request.setCharacterEncoding(UTF8);
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
List<Object> list = new ArrayList<>();
- PrintWriter out = response.getWriter();
String responseString = mapper.writeValueAsString(returnModel);
- JSONObject j = null;
+ JSONObject json = null;
if ("".equals(nameOfTrueKeys)) {
- j = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel
+ json = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel
+ ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:" + headDefautlsData + "}");
} else {
- j = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel
+ json = new JSONObject("{optimizationModelData: " + responseString + ",jsonValue: " + jsonModel
+ ",allManyTrueKeys: " + allManyTrueKeys + ",dataOrderInfo:" + dataOrderInfo + ",headDefautlsData:"
+ headDefautlsData + "}");
}
- list.add(j);
- out.write(list.toString());
+ list.add(json);
+ response.getWriter().write(list.toString());
return null;
}
@@ -415,10 +431,12 @@ public class CreateOptimizationController extends RestrictedBaseController {
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)
+ if (obj instanceof JSONObject) {
keys.addAll(getAllKeys(arr.getJSONObject(i)));
- if (obj instanceof JSONArray)
+ }
+ if (obj instanceof JSONArray) {
keys.addAll(getAllKeys(arr.getJSONArray(i)));
+ }
}
return keys;
@@ -433,16 +451,27 @@ public class CreateOptimizationController extends RestrictedBaseController {
LOGGER.info("obj : " + obj);
allManyTrueKeys.add(key);
}
- if (obj instanceof JSONObject)
+ if (obj instanceof JSONObject) {
keys.addAll(getAllKeys(json.getJSONObject(key)));
- if (obj instanceof JSONArray)
+ }
+ if (obj instanceof JSONArray) {
keys.addAll(getAllKeys(json.getJSONArray(key)));
+ }
}
return keys;
}
- @RequestMapping(value = {"/policyController/getModelServiceVersionData.htm"},
+ /**
+ * getModelServiceVersionData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @return ModelAndView
+ * @throws IOException IOException
+ */
+ @RequestMapping(
+ value = {"/policyController/getModelServiceVersionData.htm"},
method = {org.springframework.web.bind.annotation.RequestMethod.POST})
public ModelAndView getModelServiceVersionData(HttpServletRequest request, HttpServletResponse response)
throws IOException {
@@ -450,19 +479,16 @@ public class CreateOptimizationController extends RestrictedBaseController {
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);
+ final String value = root.get("policyData").toString().replaceAll("^\"|\"$", "");
+ final String servicename = value.split("-v")[0];
- response.setCharacterEncoding(UTF8);
- response.setContentType(APPLICATIONJSON);
- request.setCharacterEncoding(UTF8);
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
List<Object> list = new ArrayList<>();
- PrintWriter out = response.getWriter();
- String responseString = mapper.writeValueAsString(returnList);
- JSONObject j = new JSONObject("{optimizationModelVersionData: " + responseString + "}");
- list.add(j);
- out.write(list.toString());
+ list.add(new JSONObject("{optimizationModelVersionData: "
+ + mapper.writeValueAsString(getVersionList(servicename)) + "}"));
+ response.getWriter().write(list.toString());
return null;
}
@@ -507,76 +533,46 @@ public class CreateOptimizationController extends RestrictedBaseController {
modelName);
}
+ /**
+ * prePopulatePolicyData.
+ *
+ * @param policyAdapter PolicyRestAdapter
+ * @param entity PolicyEntity
+ */
public void prePopulatePolicyData(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("OOF_") + 4);
- 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 " + 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 ("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);
- }
- }
- }
- }
+ if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+ return;
+ }
+ Object policyData = policyAdapter.getPolicyData();
+ PolicyType policy = (PolicyType) policyData;
+ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+ String policyNameValue =
+ policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("OOF_") + 4);
+ 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 " + policyNameValue, e);
+ description = policy.getDescription();
+ }
+ policyAdapter.setPolicyDescription(description);
+ // Get the target data under policy.
+ TargetType target = policy.getTarget();
+ if (target == null) {
+ return;
+ }
+ for (AnyOfType anyOf : target.getAnyOf()) {
+ for (AllOfType allOf : anyOf.getAllOf()) {
+ for (MatchType match : allOf.getMatch()) {
+ //
+ // Under the match we have attribute value and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ policyAdapter.setupUsingAttribute(match.getAttributeDesignator().getAttributeId(),
+ (String) match.getAttributeValue().getContent().get(0));
}
+ readFile(policyAdapter, entity);
}
}
}
@@ -612,7 +608,16 @@ public class CreateOptimizationController extends RestrictedBaseController {
}
- @RequestMapping(value = {"/oof_dictionary/set_ModelData"},
+ /**
+ * setModelData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @throws IOException IOException
+ * @throws FileUploadException FileUploadException
+ */
+ @RequestMapping(
+ value = {"/oof_dictionary/set_ModelData"},
method = {org.springframework.web.bind.annotation.RequestMethod.POST})
public void setModelData(HttpServletRequest request, HttpServletResponse response)
throws IOException, FileUploadException {
@@ -655,21 +660,15 @@ public class CreateOptimizationController extends RestrictedBaseController {
}
if (!errorMsg.isEmpty()) {
-
- PrintWriter out = response.getWriter();
-
- response.setCharacterEncoding(UTF8);
- response.setContentType(APPLICATIONJSON);
- request.setCharacterEncoding(UTF8);
-
- JSONObject j = new JSONObject();
- j.put("errorMsg", errorMsg);
- out.write(j.toString());
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ response.getWriter().write(new JSONObject().put("errorMsg", errorMsg).toString());
return;
}
List<File> fileList = new ArrayList<>();
- MSModelUtils modelUtil = new MSModelUtils();
+ MsModelUtils modelUtil = new MsModelUtils();
this.directory = MODEL;
if (zip) {
extractFolder(this.newFile);
@@ -699,7 +698,7 @@ public class CreateOptimizationController extends RestrictedBaseController {
modelType = "yml";
modelList.add(this.newModel.getModelName());
String className = this.newModel.getModelName();
- MSAttributeObject optimizationAttributes = new MSAttributeObject();
+ MsAttributeObject optimizationAttributes = new MsAttributeObject();
optimizationAttributes.setClassName(className);
LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>();
@@ -731,20 +730,18 @@ public class CreateOptimizationController extends RestrictedBaseController {
}
- PrintWriter out = response.getWriter();
-
- response.setCharacterEncoding(UTF8);
- response.setContentType(APPLICATIONJSON);
- request.setCharacterEncoding(UTF8);
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
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", modelUtil.getDataOrderInfo());
+ JSONObject json = new JSONObject();
+ json.put("classListDatas", modelList);
+ json.put("modelDatas", mapper.writeValueAsString(classMap));
+ json.put("modelType", modelType);
+ json.put("dataOrderInfo", modelUtil.getDataOrderInfo());
- out.write(j.toString());
+ response.getWriter().write(json.toString());
}
/*
@@ -752,7 +749,6 @@ public class CreateOptimizationController extends RestrictedBaseController {
*/
@SuppressWarnings("rawtypes")
private void extractFolder(String zipFile) {
- int BUFFER = 2048;
File file = new File(zipFile);
try (ZipFile zip = new ZipFile(file)) {
@@ -802,23 +798,19 @@ public class CreateOptimizationController extends RestrictedBaseController {
private void retrieveDependency(String workingFile) {
- MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
- Map<String, MSAttributeObject> tempMap;
+ MsModelUtils utils = new MsModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName());
+ Map<String, MsAttributeObject> tempMap;
- tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
+ tempMap = utils.processEpackage(workingFile, ModelType.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) {
+ for (File file : fileDirectory.listFiles()) {
if (file.isFile()) {
resultList.add(file);
} else if (file.isDirectory()) {
@@ -831,9 +823,9 @@ public class CreateOptimizationController extends RestrictedBaseController {
private List<String> createList() {
List<String> list = new ArrayList<>();
- for (Entry<String, MSAttributeObject> cMap : classMap.entrySet()) {
- if (cMap.getValue().isPolicyTempalate()) {
- list.add(cMap.getKey());
+ for (Entry<String, MsAttributeObject> entrySet : classMap.entrySet()) {
+ if (entrySet.getValue().isPolicyTempalate()) {
+ list.add(entrySet.getKey());
}
}
@@ -858,7 +850,7 @@ public class CreateOptimizationController extends RestrictedBaseController {
private OptimizationObject setOptimizationObjectValues(PolicyRestAdapter policyAdapter) {
OptimizationObject optimizationObject = new OptimizationObject();
- optimizationObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_OOF));
+ optimizationObject.setTemplateVersion(XACMLProperties.getProperty(XacmlRestProperties.TEMPLATE_VERSION_OOF));
if (policyAdapter.getServiceType() != null) {
optimizationObject.setService(policyAdapter.getServiceType());
@@ -888,7 +880,8 @@ public class CreateOptimizationController extends RestrictedBaseController {
}
}
-
+@Getter
+@Setter
class OptimizationObject {
private String service;
@@ -901,95 +894,5 @@ class OptimizationObject {
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 getPriority() {
- return priority;
- }
-
- public void setPriority(String priority) {
- this.priority = priority;
- }
-
- public String getPolicyScope() {
- return policyScope;
- }
-
- public void setPolicyScope(String policyScope) {
- this.policyScope = policyScope;
- }
-
- 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 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 getTemplateVersion() {
- return templateVersion;
- }
-
- public void setTemplateVersion(String templateVersion) {
- this.templateVersion = templateVersion;
- }
-
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java
index 6cd121ee6..a2cf20834 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java
@@ -2,14 +2,14 @@
* ============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.
* 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,18 @@
package org.onap.policy.controller;
-
import java.util.ArrayList;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
+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.MatchType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
+
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
@@ -35,117 +40,87 @@ import org.onap.portalsdk.core.controller.RestrictedBaseController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
-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.RuleType;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
-
@Controller
@RequestMapping("/")
-public class CreatePolicyController extends RestrictedBaseController{
+public class CreatePolicyController extends RestrictedBaseController {
private static Logger policyLogger = FlexLogger.getLogger(CreatePolicyController.class);
- protected PolicyRestAdapter policyAdapter = null;
- private ArrayList<Object> attributeList;
- boolean isValidForm = false;
-
- public void prePopulateBaseConfigPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
- attributeList = new ArrayList<>();
- if (policyAdapter.getPolicyData() instanceof PolicyType) {
- Object policyData = policyAdapter.getPolicyData();
- PolicyType policy = (PolicyType) policyData;
- policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
- policyAdapter.setConfigType(entity.getConfigurationData().getConfigType());
- policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody());
- 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){
- policyLogger.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();
- int index = 0;
- 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 (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 ("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);
- }
- if ("ConfigName".equals(attributeId)){
- policyAdapter.setConfigName(value);
- }
- // After Onap and Config it is optional to have attributes, so
- // check weather dynamic values or there or not.
- if (index >= 7) {
- Map<String, String> attribute = new HashMap<>();
- attribute.put("key", attributeId);
- attribute.put("value", value);
- attributeList.add(attribute);
- }
- index++;
- }
- }
- }
- }
- }
- }
+ protected PolicyRestAdapter policyAdapter = null;
+ private ArrayList<Object> attributeList;
+ boolean isValidForm = false;
- policyAdapter.setAttributes(attributeList);
- }
- List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
- for (Object o : ruleList) {
- if (o instanceof RuleType) {
- // get the condition data under the rule for rule Algorithms.
- policyAdapter.setRuleID(((RuleType) o).getRuleId());
- }
- }
- }
- }
+ /**
+ * prePopulateBaseConfigPolicyData.
+ *
+ * @param policyAdapter PolicyRestAdapter
+ * @param entity PolicyEntity
+ */
+ public void prePopulateBaseConfigPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+ attributeList = new ArrayList<>();
+ if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
+ return;
+ }
+ Object policyData = policyAdapter.getPolicyData();
+ PolicyType policy = (PolicyType) policyData;
+ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
+ policyAdapter.setConfigType(entity.getConfigurationData().getConfigType());
+ policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody());
+ 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) {
+ policyLogger.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();
+ //
+ // NOTE: target.getAnyOf() will NEVER return null
+ //
+ if (target != null) {
+ // Under target we have AnyOFType
+ for (AnyOfType anyOf : target.getAnyOf()) {
+ // Under AnyOFType we have AllOFType
+ //
+ // NOTE: anyOf.getAllOf() will NEVER return null
+ //
+ int index = 0;
+ for (AllOfType allOf : anyOf.getAllOf()) {
+ // Under AllOFType we have Match
+ // NOTE: allOf.getMatch() will NEVER be NULL
+ //
+ for (MatchType match : allOf.getMatch()) {
+ //
+ // Under the match we have attribute value and
+ // attributeDesignator. So,finally down to the actual attribute.
+ //
+ String value = (String) match.getAttributeValue().getContent().get(0);
+ String attributeId = match.getAttributeDesignator().getAttributeId();
+ // First match in the target is OnapName, so set that value.
+ policyAdapter.setupUsingAttribute(attributeId, value);
+ // After Onap and Config it is optional to have attributes, so
+ // check weather dynamic values or there or not.
+ if (index >= 7) {
+ Map<String, String> attribute = new HashMap<>();
+ attribute.put("key", attributeId);
+ attribute.put("value", value);
+ attributeList.add(attribute);
+ }
+ index++;
+ }
+ }
+ }
+ policyAdapter.setAttributes(attributeList);
+ }
+ List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
+ for (Object object : ruleList) {
+ if (object instanceof RuleType) {
+ // get the condition data under the rule for rule Algorithms.
+ policyAdapter.setRuleID(((RuleType) object).getRuleId());
+ }
+ }
+ }
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java
index d3af75dfd..0ca315bf1 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java
@@ -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.
@@ -29,6 +29,7 @@ import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
@@ -41,6 +42,7 @@ import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+
import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
@@ -53,12 +55,13 @@ import javax.management.remote.JMXServiceURL;
import javax.script.SimpleBindings;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+
import org.json.JSONObject;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.dao.SystemLogDbDao;
import org.onap.policy.model.PDPGroupContainer;
-import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.rest.dao.CommonClassDao;
import org.onap.policy.rest.jpa.PolicyEntity;
import org.onap.policy.utils.PolicyUtils;
@@ -117,15 +120,14 @@ public class DashboardController extends RestrictedBaseController {
return policyController != null ? getPolicyController() : new PolicyController();
}
-
-
/**
* This method is to retrieve all the data of last 30 days from PolicyEntity table as default.
- *
+ *
* @param request object
* @param response object contains retrieved data
*/
- @RequestMapping(value = {"/get_DashboardPolicyCRUDData"},
+ @RequestMapping(
+ value = {"/get_DashboardPolicyCRUDData"},
method = {org.springframework.web.bind.annotation.RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void get_DashboardPolicyCrudData(HttpServletRequest request, HttpServletResponse response) {
@@ -135,9 +137,7 @@ public class DashboardController extends RestrictedBaseController {
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
addPolicyCrudInfoToTable();
model.put("papStatusCRUDData", mapper.writeValueAsString(policyStatusCrudData));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
policyLogger.error(exceptionOccured, e);
}
@@ -145,11 +145,12 @@ public class DashboardController extends RestrictedBaseController {
/**
* This method retrieves data based on input criteria.
- *
+ *
* @param request object
* @param response object contains retrieved data
*/
- @RequestMapping(value = {"/dashboardController/dashboardAdvancedSearch.htm"},
+ @RequestMapping(
+ value = {"/dashboardController/dashboardAdvancedSearch.htm"},
method = {org.springframework.web.bind.annotation.RequestMethod.POST})
public void dashboardAdvancedSearch(HttpServletRequest request, HttpServletResponse response) throws IOException {
String lscope = null;
@@ -185,11 +186,9 @@ public class DashboardController extends RestrictedBaseController {
getPolicyData(lscope, lstage, isDelected, ttlDateAfter, ttlDateBefore);
Map<String, Object> model = new HashMap<>();
model.put("policyStatusCRUDData", mapper.writeValueAsString(policyStatusCrudData));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
- response.setCharacterEncoding("UTF-8");
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
PrintWriter out = response.getWriter();
out.write(PolicyUtils.CATCH_EXCEPTION);
}
@@ -198,11 +197,12 @@ public class DashboardController extends RestrictedBaseController {
/**
* This method is to retrieve data from PolicyEntity table.
- *
+ *
* @param request object
* @param response object contains retrieved data
*/
- @RequestMapping(value = {"/get_DashboardPdpPolicyCRUDData"},
+ @RequestMapping(
+ value = {"/get_DashboardPdpPolicyCRUDData"},
method = {org.springframework.web.bind.annotation.RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void get_DashboardPdpPolicyCrudData(HttpServletRequest request, HttpServletResponse response) {
@@ -211,15 +211,20 @@ public class DashboardController extends RestrictedBaseController {
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
model.put("pdpStatusCRUDData", mapper.writeValueAsString(pdpStatusCrudData));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
policyLogger.error(exceptionOccured, e);
}
}
- @RequestMapping(value = {"/get_DashboardLoggingData"},
+ /**
+ * getData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ @RequestMapping(
+ value = {"/get_DashboardLoggingData"},
method = {org.springframework.web.bind.annotation.RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getData(HttpServletRequest request, HttpServletResponse response) {
@@ -227,15 +232,20 @@ public class DashboardController extends RestrictedBaseController {
Map<String, Object> model = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
model.put("availableLoggingDatas", mapper.writeValueAsString(systemDAO.getLoggingData()));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
policyLogger.error(exceptionOccured + e);
}
}
- @RequestMapping(value = {"/get_DashboardSystemAlertData"},
+ /**
+ * getSystemAlertData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ @RequestMapping(
+ value = {"/get_DashboardSystemAlertData"},
method = {org.springframework.web.bind.annotation.RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getSystemAlertData(HttpServletRequest request, HttpServletResponse response) {
@@ -243,15 +253,20 @@ public class DashboardController extends RestrictedBaseController {
Map<String, Object> model = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
model.put("systemAlertsTableDatas", mapper.writeValueAsString(systemDAO.getSystemAlertData()));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
policyLogger.error(exceptionOccured + e);
}
}
- @RequestMapping(value = {"/get_DashboardPAPStatusData"},
+ /**
+ * getPAPStatusData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ @RequestMapping(
+ value = {"/get_DashboardPAPStatusData"},
method = {org.springframework.web.bind.annotation.RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getPAPStatusData(HttpServletRequest request, HttpServletResponse response) {
@@ -261,20 +276,25 @@ public class DashboardController extends RestrictedBaseController {
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
addPAPToTable();
model.put("papTableDatas", mapper.writeValueAsString(papStatusData));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
policyLogger.error(exceptionOccured + e);
}
}
- @RequestMapping(value = {"/get_DashboardPDPStatusData"},
+ /**
+ * getPDPStatusData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ @RequestMapping(
+ value = {"/get_DashboardPDPStatusData"},
method = {org.springframework.web.bind.annotation.RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getPDPStatusData(HttpServletRequest request, HttpServletResponse response) {
try {
- Map<String, Object> model = new HashMap<>();
+ final Map<String, Object> model = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
PolicyController controller = getPolicyControllerInstance();
@@ -282,28 +302,32 @@ public class DashboardController extends RestrictedBaseController {
addPDPToTable();
model.put("pdpTableDatas", mapper.writeValueAsString(pdpStatusData));
JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(msg).toString());
} catch (Exception e) {
policyLogger.error(exceptionOccured + e);
}
}
- @RequestMapping(value = {"/get_DashboardPolicyActivityData"},
+ /**
+ * getPolicyActivityData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ @RequestMapping(
+ value = {"/get_DashboardPolicyActivityData"},
method = {org.springframework.web.bind.annotation.RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getPolicyActivityData(HttpServletRequest request, HttpServletResponse response) {
try {
- Map<String, Object> model = new HashMap<>();
+ final Map<String, Object> model = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
PolicyController controller = getPolicyControllerInstance();
this.pdpConatiner = new PDPGroupContainer(controller.getPapEngine());
addPolicyToTable();
model.put("policyActivityTableDatas", mapper.writeValueAsString(policyActivityData));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
policyLogger.error(exceptionOccured + e);
}
@@ -327,9 +351,9 @@ public class DashboardController extends RestrictedBaseController {
papStatus = "CANNOT_CONNECT";
policyLogger.error("Error getting PAP status, PAP not responding to requests", e1);
}
- String papURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL);
+ String papUrl = XACMLProperties.getProperty(XacmlRestProperties.PROP_PAP_URL);
JSONObject object = new JSONObject();
- object.put("system", papURL);
+ object.put("system", papUrl);
object.put("status", papStatus);
List<Object> data = commonClassDao.getDataByQuery("from PolicyEntity", new SimpleBindings());
object.put("noOfPolicy", data.size());
@@ -337,9 +361,8 @@ public class DashboardController extends RestrictedBaseController {
papStatusData.add(0, object);
}
-
- /*
- * Add the PAP Policy information to the PAP Table
+ /**
+ * Add the PAP Policy information to the PAP Table.
*/
public void addPolicyCrudInfoToTable() {
policyStatusCrudData = new ArrayList<>();
@@ -362,7 +385,7 @@ public class DashboardController extends RestrictedBaseController {
object.put(scope, ((PolicyEntity) data).getScope());
object.put("policyName", ((PolicyEntity) data).getPolicyName());
object.put("version", ((PolicyEntity) data).getVersion());
- if (isPushedToPDP(((PolicyEntity) data).getPolicyId())) {
+ if (isPushedToPdp(((PolicyEntity) data).getPolicyId())) {
object.put(stage, "PDP");
} else {
object.put(stage, "PAP");
@@ -388,13 +411,13 @@ public class DashboardController extends RestrictedBaseController {
/*
* Add the PDP Policy information to the PDP Table
*/
- private boolean isPushedToPDP(long policyId) {
+ private boolean isPushedToPdp(long policyId) {
try {
String groupEntityquery = "from PolicyGroupEntity where policyid = :policyEntityId";
SimpleBindings geParams = new SimpleBindings();
geParams.put("policyEntityId", policyId);
List<Object> groupobject = commonClassDao.getDataByQuery(groupEntityquery, geParams);
- if (groupobject != null && groupobject.size() > 0) {
+ if (groupobject != null && ! groupobject.isEmpty()) {
return true;
}
} catch (Exception e) {
@@ -407,7 +430,8 @@ public class DashboardController extends RestrictedBaseController {
/*
* Add the Policy information to the policyStatusCRUDDataTable
*/
- private void getPolicyData(String inputScope, String inputStage, String isDeleted, String createdAfter, String createdBefore) {
+ private void getPolicyData(String inputScope, String inputStage, String isDeleted, String createdAfter,
+ String createdBefore) {
policyStatusCrudData = new ArrayList<>();
List<Object> policyData = null;
SimpleBindings geParams = new SimpleBindings();
@@ -479,7 +503,7 @@ public class DashboardController extends RestrictedBaseController {
object.put(scope, data.getScope());
object.put("policyName", data.getPolicyName());
object.put("version", data.getVersion());
- if (isPushedToPDP(data.getPolicyId())) {
+ if (isPushedToPdp(data.getPolicyId())) {
object.put(stage, "PDP");
} else {
object.put(stage, "PAP");
@@ -503,7 +527,7 @@ public class DashboardController extends RestrictedBaseController {
}
/**
- * Add PDP Information to the PDP Table
+ * Add PDP Information to the PDP Table.
*
*/
public void addPDPToTable() {
@@ -516,7 +540,7 @@ public class DashboardController extends RestrictedBaseController {
for (PDP pdp : group.getPdps()) {
naCount = -1;
if ("UP_TO_DATE".equals(pdp.getStatus().getStatus().toString()) && ((OnapPDP) pdp).getJmxPort() != 0) {
- String pdpIpAddress = parseIPSystem(pdp.getId());
+ String pdpIpAddress = parseIpSystem(pdp.getId());
int port = ((OnapPDP) pdp).getJmxPort();
if (port != 0) {
policyLogger.debug("Getting JMX Response Counts from " + pdpIpAddress + " at JMX port " + port);
@@ -553,7 +577,7 @@ public class DashboardController extends RestrictedBaseController {
}
}
- private static String parseIPSystem(String line) {
+ private static String parseIpSystem(String line) {
Pattern pattern = Pattern.compile("://(.+?):");
Matcher ip = pattern.matcher(line);
if (ip.find()) {
@@ -570,13 +594,12 @@ public class DashboardController extends RestrictedBaseController {
policyLogger.debug("Create an RMI connector client and connect it to the JMX connector server");
HashMap map = null;
- try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map)) {
+ try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionUrl(host, port), map)) {
jmxConnection.connect();
- Object o =
- jmxConnection.getMBeanServerConnection().getAttribute(
- new ObjectName("PdpRest:type=PdpRestMonitor"), jmxAttribute);
- policyLogger.debug("pdpEvaluationNA value retreived: " + o);
- return (long) o;
+ Object obj = jmxConnection.getMBeanServerConnection()
+ .getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), jmxAttribute);
+ policyLogger.debug("pdpEvaluationNA value retreived: " + obj);
+ return (long) obj;
} catch (MalformedURLException e) {
policyLogger.error("MalformedURLException for JMX connection", e);
} catch (IOException e) {
@@ -597,11 +620,10 @@ public class DashboardController extends RestrictedBaseController {
return -1;
}
- private static JMXServiceURL createConnectionURL(String host, int port) throws MalformedURLException {
+ private static JMXServiceURL createConnectionUrl(String host, int port) throws MalformedURLException {
return new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi");
}
-
/*
* Add the information to the Policy Table
*/
@@ -626,8 +648,8 @@ public class DashboardController extends RestrictedBaseController {
// Add rows to the Policy Table
policyList = null;
if ("UP_TO_DATE".equals(pdp.getStatus().getStatus().toString()) && ((OnapPDP) pdp).getJmxPort() != 0) {
- String pdpIpAddress = parseIPSystem(pdp.getId());
- policyList = getPolicy(pdpIpAddress, ((OnapPDP) pdp).getJmxPort(), "policyCount");
+ String pdpIpAddress = parseIpSystem(pdp.getId());
+ policyList = getPolicy(pdpIpAddress, ((OnapPDP) pdp).getJmxPort());
}
if (policyList != null && policyList.toString().length() > 3) {
String[] splitPolicy = policyList.toString().split(",");
@@ -643,19 +665,15 @@ public class DashboardController extends RestrictedBaseController {
}
}
} else {
+ JSONObject object = new JSONObject();
if (policyList != null) {
- JSONObject object = new JSONObject();
object.put("policyId", "Unable to retrieve policy information");
- object.put("fireCount", "NA");
- object.put("system", pdp.getId());
- policyActivityData.add(object);
} else {
- JSONObject object = new JSONObject();
object.put("policyId", "Unable to access PDP JMX Server");
- object.put("fireCount", "NA");
- object.put("system", pdp.getId());
- policyActivityData.add(object);
}
+ object.put("fireCount", "NA");
+ object.put("system", pdp.getId());
+ policyActivityData.add(object);
}
}
}
@@ -665,17 +683,16 @@ public class DashboardController extends RestrictedBaseController {
* Contact JMX Connector Sever and return the list of {policy id , count}
*/
@SuppressWarnings({"rawtypes", "unchecked"})
- private Object getPolicy(String host, int port, String jmxAttribute) {
- policyLogger.debug("Create an RMI connector client and connect it to the JMX connector server for Policy: "
- + host);
+ private Object getPolicy(String host, int port) {
+ policyLogger
+ .debug("Create an RMI connector client and connect it to the JMX connector server for Policy: " + host);
HashMap map = null;
- try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map)) {
+ try (JMXConnector jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionUrl(host, port), map)) {
jmxConnection.connect();
- Object o =
- jmxConnection.getMBeanServerConnection().getAttribute(
- new ObjectName("PdpRest:type=PdpRestMonitor"), "policyMap");
- policyLogger.debug("policyMap value retreived: " + o);
- return o;
+ Object obj = jmxConnection.getMBeanServerConnection()
+ .getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), "policyMap");
+ policyLogger.debug("policyMap value retreived: " + obj);
+ return obj;
} catch (MalformedURLException e) {
policyLogger.error("MalformedURLException for JMX connection", e);
} catch (IOException e) {
@@ -705,8 +722,7 @@ public class DashboardController extends RestrictedBaseController {
private static Integer countPolicyID(String line) {
String[] splitLine = line.split("=");
- String sCount = splitLine[1].replace("}", "");
- return Integer.parseInt(sCount);
+ return Integer.parseInt(splitLine[1].replace("}", ""));
}
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java
index 4e8c8c141..c3b474521 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.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.
@@ -25,24 +25,13 @@ import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
+
import javax.xml.bind.JAXBElement;
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.lang3.StringUtils;
-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.adapter.RainyDayParams;
-import org.onap.policy.rest.adapter.YAMLParams;
-import org.onap.policy.rest.jpa.PolicyEntity;
-import org.onap.policy.xacml.util.XACMLPolicyWriter;
-import org.onap.portalsdk.core.controller.RestrictedBaseController;
-import org.springframework.stereotype.Controller;
-import org.springframework.web.bind.annotation.RequestMapping;
+
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
@@ -59,28 +48,47 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang3.StringUtils;
+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.adapter.RainyDayParams;
+import org.onap.policy.rest.adapter.YAMLParams;
+import org.onap.policy.rest.jpa.PolicyEntity;
+import org.onap.policy.xacml.util.XACMLPolicyWriter;
+import org.onap.portalsdk.core.controller.RestrictedBaseController;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+
@Controller
@RequestMapping("/")
public class DecisionPolicyController extends RestrictedBaseController {
private static final Logger policyLogger = FlexLogger.getLogger(DecisionPolicyController.class);
-
+
public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not";
private static final String BLENTRY = "@blEntry@";
private static final String DECISIONRAWTYPE = "@#RuleProvider@#Decision_Raw@#RuleProvider@#";
- private static final String GUARD_YAML= "GUARD_YAML";
- private static final String GUARD_BL_YAML= "GUARD_BL_YAML";
- private static final String GUARD_MIN_MAX= "GUARD_MIN_MAX";
-
+ private static final String GUARD_YAML = "GUARD_YAML";
+ private static final String GUARD_BL_YAML = "GUARD_BL_YAML";
+ private static final String GUARD_MIN_MAX = "GUARD_MIN_MAX";
+
protected PolicyRestAdapter policyAdapter = null;
private ArrayList<Object> ruleAlgorithmList;
private ArrayList<Object> treatmentList = null;
protected LinkedList<Integer> ruleAlgoirthmTracker;
-
+
public DecisionPolicyController() {
// This constructor is empty
}
-
- public void rawXACMLPolicy(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
+
+ /**
+ * rawXacmlPolicy. Should this method be private?
+ *
+ * @param policyAdapter PolicyRestAdapter
+ * @param entity PolicyEntity
+ */
+ public void rawXacmlPolicy(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
try (InputStream policyXmlStream = XACMLPolicyWriter.getXmlAsInputStream(policyAdapter.getPolicyData())) {
String name = StringUtils.substringAfter(entity.getPolicyName(), "Decision_");
policyAdapter.setPolicyName(name.substring(0, name.indexOf('.')));
@@ -91,6 +99,12 @@ public class DecisionPolicyController extends RestrictedBaseController {
}
}
+ /**
+ * prePopulateDecisionPolicyData.
+ *
+ * @param policyAdapter PolicyRestAdapter
+ * @param entity PolicyEntity
+ */
@SuppressWarnings("unchecked")
public void prePopulateDecisionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
List<Object> attributeList = new ArrayList<>();
@@ -106,237 +120,222 @@ public class DecisionPolicyController extends RestrictedBaseController {
}
if (rawPolicyCheck) {
- rawXACMLPolicy(policyAdapter, entity);
- } else {
- RainyDayParams rainydayParams = new RainyDayParams();
- Object policyData = policyAdapter.getPolicyData();
- PolicyType policy = (PolicyType) policyData;
- policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
-
- policyAdapter.setPolicyName(StringUtils.substringAfter(policyAdapter.getPolicyName(), "Decision_"));
- String description = "";
- String blackListEntryType = "Use Manual Entry";
- try {
- if (policy.getDescription().contains(BLENTRY)) {
- blackListEntryType = policy.getDescription().substring(policy.getDescription().indexOf(BLENTRY) + 9,
- policy.getDescription().lastIndexOf(BLENTRY));
- }
- policyAdapter.setBlackListEntryType(blackListEntryType);
- description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+ rawXacmlPolicy(policyAdapter, entity);
+ return;
+ }
+ RainyDayParams rainydayParams = new RainyDayParams();
+ Object policyData = policyAdapter.getPolicyData();
+ PolicyType policy = (PolicyType) policyData;
+ policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
- } catch (Exception e) {
- policyLogger.info("General error", e);
- description = policy.getDescription();
+ policyAdapter.setPolicyName(StringUtils.substringAfter(policyAdapter.getPolicyName(), "Decision_"));
+ String description = "";
+ String blackListEntryType = "Use Manual Entry";
+ try {
+ if (policy.getDescription().contains(BLENTRY)) {
+ blackListEntryType = policy.getDescription().substring(policy.getDescription().indexOf(BLENTRY) + 9,
+ policy.getDescription().lastIndexOf(BLENTRY));
}
- policyAdapter.setPolicyDescription(description);
- // 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();
- int index = 0;
- 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);
- if (value != null) {
- value = value.replaceAll("\\(\\?i\\)", "");
- }
- 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);
- }
- // 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.
- if (index >= 1) {
- Map<String, String> attribute = new HashMap<>();
- attribute.put("key", attributeId);
- attribute.put("value", value);
- attributeList.add(attribute);
- }
- index++;
- }
- }
- policyAdapter.setAttributes(attributeList);
- }
- }
- }
- // Setting rainy day attributes to the parameters object if they exist
- boolean rainy = false;
- if (!attributeList.isEmpty()) {
- for (int i = 0; i < attributeList.size(); i++) {
- Map<String, String> map = (Map<String, String>) attributeList.get(i);
- if ("WorkStep".equals(map.get("key"))) {
- rainydayParams.setWorkstep(map.get("value"));
- rainy = true;
- } else if ("BB_ID".equals(map.get("key"))) {
- rainydayParams.setBbid(map.get("value"));
- rainy = true;
- } else if ("ServiceType".equals(map.get("key"))) {
- rainydayParams.setServiceType(map.get("value"));
- rainy = true;
- } else if ("VNFType".equals(map.get("key"))) {
- rainydayParams.setVnfType(map.get("value"));
- rainy = true;
- }
- }
+ policyAdapter.setBlackListEntryType(blackListEntryType);
+ description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
+
+ } catch (Exception e) {
+ policyLogger.info("General error", e);
+ description = policy.getDescription();
+ }
+ policyAdapter.setPolicyDescription(description);
+ // Get the target data under policy for Action.
+ TargetType target = policy.getTarget();
+ if (target == null) {
+ rainydayParams.setTreatmentTableChoices(treatmentList);
+ policyAdapter.setRainyday(rainydayParams);
+ policyAdapter.setSettings(decisionList);
+ return;
+ }
+ // under target we have AnyOFType
+ for (AnyOfType anyOf : target.getAnyOf()) {
+ for (AllOfType allOf : anyOf.getAllOf()) {
+ int index = 0;
+ for (MatchType match : allOf.getMatch()) {
+ //
+ // 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);
+ if (value != null) {
+ value = value.replaceAll("\\(\\?i\\)", "");
}
- if (rainy) {
- policyAdapter.setRuleProvider("Rainy_Day");
+ AttributeDesignatorType designator = match.getAttributeDesignator();
+ String attributeId = designator.getAttributeId();
+ // First match in the target is OnapName, so set that value.
+ policyAdapter.setupUsingAttribute(attributeId, value);
+ // 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.
+ if (index >= 1) {
+ Map<String, String> attribute = new HashMap<>();
+ attribute.put("key", attributeId);
+ attribute.put("value", value);
+ attributeList.add(attribute);
}
+ index++;
+ }
+ policyAdapter.setAttributes(attributeList);
+ }
+ }
+ // Setting rainy day attributes to the parameters object if they exist
+ boolean rainy = false;
+ if (!attributeList.isEmpty()) {
+ for (int i = 0; i < attributeList.size(); i++) {
+ Map<String, String> map = (Map<String, String>) attributeList.get(i);
+ String key = map.get("key");
+ if ("WorkStep".equals(key)) {
+ rainydayParams.setWorkstep(map.get("value"));
+ rainy = true;
+ } else if ("BB_ID".equals(key)) {
+ rainydayParams.setBbid(map.get("value"));
+ rainy = true;
+ } else if ("ServiceType".equals(key)) {
+ rainydayParams.setServiceType(map.get("value"));
+ rainy = true;
+ } else if ("VNFType".equals(key)) {
+ rainydayParams.setVnfType(map.get("value"));
+ rainy = true;
}
+ }
+ }
+ if (rainy) {
+ policyAdapter.setRuleProvider("Rainy_Day");
+ }
- List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
- int index = 0;
- for (Object object : ruleList) {
- if (object instanceof VariableDefinitionType) {
- VariableDefinitionType variableDefinitionType = (VariableDefinitionType) object;
- Map<String, String> settings = new HashMap<>();
- settings.put("key", variableDefinitionType.getVariableId());
- JAXBElement<AttributeValueType> attributeValueTypeElement =
- (JAXBElement<AttributeValueType>) variableDefinitionType.getExpression();
- if (attributeValueTypeElement != null) {
- AttributeValueType attributeValueType = attributeValueTypeElement.getValue();
- settings.put("value", attributeValueType.getContent().get(0).toString());
+ List<Object> ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
+ int index = 0;
+ for (Object object : ruleList) {
+ if (object instanceof VariableDefinitionType) {
+ VariableDefinitionType variableDefinitionType = (VariableDefinitionType) object;
+ Map<String, String> settings = new HashMap<>();
+ settings.put("key", variableDefinitionType.getVariableId());
+ JAXBElement<AttributeValueType> attributeValueTypeElement =
+ (JAXBElement<AttributeValueType>) variableDefinitionType.getExpression();
+ if (attributeValueTypeElement != null) {
+ AttributeValueType attributeValueType = attributeValueTypeElement.getValue();
+ settings.put("value", attributeValueType.getContent().get(0).toString());
+ }
+ decisionList.add(settings);
+ } else if (object instanceof RuleType) {
+ // get the condition data under the rule for rule Algorithms.
+ if (((RuleType) object).getEffect().equals(EffectType.DENY)) {
+ if (((RuleType) object).getAdviceExpressions() != null) {
+ if ("AAF".equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
+ .getAdviceExpression().get(0).getAdviceId())) {
+ policyAdapter.setRuleProvider("AAF");
+ break;
+ } else if (GUARD_YAML.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
+ .getAdviceExpression().get(0).getAdviceId())) {
+ policyAdapter.setRuleProvider(GUARD_YAML);
+ } else if (GUARD_BL_YAML.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
+ .getAdviceExpression().get(0).getAdviceId())) {
+ policyAdapter.setRuleProvider(GUARD_BL_YAML);
+ } else if (GUARD_MIN_MAX.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
+ .getAdviceExpression().get(0).getAdviceId())) {
+ policyAdapter.setRuleProvider(GUARD_MIN_MAX);
}
- decisionList.add(settings);
- } else if (object instanceof RuleType) {
- // get the condition data under the rule for rule Algorithms.
- if (((RuleType) object).getEffect().equals(EffectType.DENY)) {
- if (((RuleType) object).getAdviceExpressions() != null) {
- if ("AAF".equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
- .getAdviceExpression().get(0).getAdviceId())) {
- policyAdapter.setRuleProvider("AAF");
- break;
- } else if (GUARD_YAML.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
- .getAdviceExpression().get(0).getAdviceId())) {
- policyAdapter.setRuleProvider(GUARD_YAML);
- } else if (GUARD_BL_YAML.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
- .getAdviceExpression().get(0).getAdviceId())) {
- policyAdapter.setRuleProvider(GUARD_BL_YAML);
- } else if (GUARD_MIN_MAX.equalsIgnoreCase(((RuleType) object).getAdviceExpressions()
- .getAdviceExpression().get(0).getAdviceId())) {
- policyAdapter.setRuleProvider(GUARD_MIN_MAX);
+ } else {
+ policyAdapter.setRuleProvider("Custom");
+ }
+ ConditionType condition = ((RuleType) object).getCondition();
+ if (condition != null) {
+ ApplyType decisionApply = (ApplyType) condition.getExpression().getValue();
+ decisionApply = (ApplyType) decisionApply.getExpression().get(0).getValue();
+ ruleAlgoirthmTracker = new LinkedList<>();
+ if (policyAdapter.getRuleProvider() != null
+ && (GUARD_YAML.equals(policyAdapter.getRuleProvider())
+ || (GUARD_BL_YAML.equals(policyAdapter.getRuleProvider()))
+ || (GUARD_MIN_MAX.equals(policyAdapter.getRuleProvider())))) {
+ YAMLParams yamlParams = new YAMLParams();
+ for (int i = 0; i < attributeList.size(); i++) {
+ Map<String, String> map = (Map<String, String>) attributeList.get(i);
+ String key = map.get("key");
+ if ("actor".equals(key)) {
+ yamlParams.setActor(map.get("value"));
+ } else if ("recipe".equals(key)) {
+ yamlParams.setRecipe(map.get("value"));
+ } else if ("target".equals(key)) {
+ yamlParams.setTargets(Arrays.asList(map.get("value").split("\\|")));
+ } else if ("clname".equals(key)) {
+ yamlParams.setClname(map.get("value"));
+ } else if ("min".equals(key)) {
+ yamlParams.setMin(map.get("value"));
+ } else if ("max".equals(key)) {
+ yamlParams.setMax(map.get("value"));
}
- } else {
- policyAdapter.setRuleProvider("Custom");
}
- ConditionType condition = ((RuleType) object).getCondition();
- if (condition != null) {
- ApplyType decisionApply = (ApplyType) condition.getExpression().getValue();
- decisionApply = (ApplyType) decisionApply.getExpression().get(0).getValue();
- ruleAlgoirthmTracker = new LinkedList<>();
- if (policyAdapter.getRuleProvider() != null
- && (GUARD_YAML.equals(policyAdapter.getRuleProvider())
- || (GUARD_BL_YAML.equals(policyAdapter.getRuleProvider()))
- || (GUARD_MIN_MAX.equals(policyAdapter.getRuleProvider())))){
- YAMLParams yamlParams = new YAMLParams();
- for (int i = 0; i < attributeList.size(); i++) {
- Map<String, String> map = (Map<String, String>) attributeList.get(i);
- if ("actor".equals(map.get("key"))) {
- yamlParams.setActor(map.get("value"));
- } else if ("recipe".equals(map.get("key"))) {
- yamlParams.setRecipe(map.get("value"));
- } else if ("target".equals(map.get("key"))) {
- yamlParams.setTargets(Arrays.asList(map.get("value").split("\\|")));
- } else if ("clname".equals(map.get("key"))) {
- yamlParams.setClname(map.get("value"));
- } else if ("min".equals(map.get("key"))) {
- yamlParams.setMin(map.get("value"));
- } else if ("max".equals(map.get("key"))) {
- yamlParams.setMax(map.get("value"));
- }
- }
- ApplyType apply =
- (ApplyType) ((ApplyType) decisionApply.getExpression().get(0).getValue())
- .getExpression().get(0).getValue();
- yamlParams.setGuardActiveStart(
- ((AttributeValueType) apply.getExpression().get(1).getValue()).getContent()
- .get(0).toString());
- yamlParams.setGuardActiveEnd(
- ((AttributeValueType) apply.getExpression().get(2).getValue()).getContent()
- .get(0).toString());
- if (GUARD_BL_YAML.equals(policyAdapter.getRuleProvider())) {
- apply = (ApplyType) ((ApplyType) ((ApplyType) decisionApply.getExpression()
- .get(0).getValue()).getExpression().get(1).getValue()).getExpression()
- .get(2).getValue();
- Iterator<JAXBElement<?>> attributes = apply.getExpression().iterator();
- List<String> blackList = new ArrayList<>();
- while (attributes.hasNext()) {
- blackList.add(((AttributeValueType) attributes.next().getValue())
- .getContent().get(0).toString());
- }
- yamlParams.setBlackList(blackList);
- if ("Use File Upload".equals(policyAdapter.getBlackListEntryType())) {
- policyAdapter.setBlackListEntries(blackList);
- }
- } else {
- ApplyType timeWindowSection = (ApplyType) ((ApplyType) decisionApply
- .getExpression().get(0).getValue()).getExpression().get(1).getValue();
- yamlParams.setLimit(((AttributeValueType) timeWindowSection.getExpression()
- .get(1).getValue()).getContent().get(0).toString());
- String timeWindow = ((AttributeDesignatorType) ((ApplyType) timeWindowSection
- .getExpression().get(0).getValue()).getExpression().get(0).getValue())
- .getIssuer();
- yamlParams.setTimeUnits(timeWindow.substring(timeWindow.lastIndexOf(':') + 1));
- yamlParams.setTimeWindow(timeWindow.substring(timeWindow.indexOf(":tw:") + 4,
- timeWindow.lastIndexOf(':')));
- }
- policyAdapter.setYamlparams(yamlParams);
- policyAdapter.setAttributes(new ArrayList<Object>());
- policyAdapter.setRuleAlgorithmschoices(new ArrayList<Object>());
- break;
+ ApplyType apply =
+ (ApplyType) ((ApplyType) decisionApply.getExpression().get(0).getValue())
+ .getExpression().get(0).getValue();
+ yamlParams.setGuardActiveStart(
+ ((AttributeValueType) apply.getExpression().get(1).getValue()).getContent()
+ .get(0).toString());
+ yamlParams.setGuardActiveEnd(
+ ((AttributeValueType) apply.getExpression().get(2).getValue()).getContent()
+ .get(0).toString());
+ if (GUARD_BL_YAML.equals(policyAdapter.getRuleProvider())) {
+ apply = (ApplyType) ((ApplyType) ((ApplyType) decisionApply.getExpression()
+ .get(0).getValue()).getExpression().get(1).getValue()).getExpression()
+ .get(2).getValue();
+ List<String> blackList = new ArrayList<>();
+ for (JAXBElement<?> attr : apply.getExpression()) {
+ blackList.add(((AttributeValueType) attr.getValue())
+ .getContent().get(0).toString());
}
- // Populating Rule Algorithms starting from compound.
- prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply);
- policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList);
+ yamlParams.setBlackList(blackList);
+ if ("Use File Upload".equals(policyAdapter.getBlackListEntryType())) {
+ policyAdapter.setBlackListEntries(blackList);
+ }
+ } else {
+ ApplyType timeWindowSection = (ApplyType) ((ApplyType) decisionApply
+ .getExpression().get(0).getValue()).getExpression().get(1).getValue();
+ yamlParams.setLimit(((AttributeValueType) timeWindowSection.getExpression()
+ .get(1).getValue()).getContent().get(0).toString());
+ String timeWindow = ((AttributeDesignatorType) ((ApplyType) timeWindowSection
+ .getExpression().get(0).getValue()).getExpression().get(0).getValue())
+ .getIssuer();
+ yamlParams.setTimeUnits(timeWindow.substring(timeWindow.lastIndexOf(':') + 1));
+ yamlParams.setTimeWindow(timeWindow.substring(timeWindow.indexOf(":tw:") + 4,
+ timeWindow.lastIndexOf(':')));
}
- } else if (policyAdapter.getRuleProvider() != null
- && "Rainy_Day".equals(policyAdapter.getRuleProvider())
- && ((RuleType) object).getEffect().equals(EffectType.PERMIT)) {
+ policyAdapter.setYamlparams(yamlParams);
+ policyAdapter.setAttributes(new ArrayList<Object>());
+ policyAdapter.setRuleAlgorithmschoices(new ArrayList<Object>());
+ break;
+ }
+ // Populating Rule Algorithms starting from compound.
+ prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply);
+ policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList);
+ }
+ } else if (policyAdapter.getRuleProvider() != null
+ && "Rainy_Day".equals(policyAdapter.getRuleProvider())
+ && ((RuleType) object).getEffect().equals(EffectType.PERMIT)) {
- TargetType ruleTarget = ((RuleType) object).getTarget();
- AdviceExpressionsType adviceExpression = ((RuleType) object).getAdviceExpressions();
+ TargetType ruleTarget = ((RuleType) object).getTarget();
+ AdviceExpressionsType adviceExpression = ((RuleType) object).getAdviceExpressions();
- String errorcode = ruleTarget.getAnyOf().get(0).getAllOf().get(0).getMatch().get(1)
- .getAttributeValue().getContent().get(0).toString();
- JAXBElement<AttributeValueType> tempTreatmentObj =
- (JAXBElement<AttributeValueType>) adviceExpression.getAdviceExpression().get(0)
- .getAttributeAssignmentExpression().get(0).getExpression();
- String treatment = tempTreatmentObj.getValue().getContent().get(0).toString();
+ String errorcode = ruleTarget.getAnyOf().get(0).getAllOf().get(0).getMatch().get(1)
+ .getAttributeValue().getContent().get(0).toString();
+ JAXBElement<AttributeValueType> tempTreatmentObj =
+ (JAXBElement<AttributeValueType>) adviceExpression.getAdviceExpression().get(0)
+ .getAttributeAssignmentExpression().get(0).getExpression();
+ String treatment = tempTreatmentObj.getValue().getContent().get(0).toString();
- prePopulateRainyDayTreatments(errorcode, treatment);
+ prePopulateRainyDayTreatments(errorcode, treatment);
- }
- }
}
}
-
- rainydayParams.setTreatmentTableChoices(treatmentList);
- policyAdapter.setRainyday(rainydayParams);
- policyAdapter.setSettings(decisionList);
}
+ rainydayParams.setTreatmentTableChoices(treatmentList);
+ policyAdapter.setRainyday(rainydayParams);
+ policyAdapter.setSettings(decisionList);
}
private void prePopulateRainyDayTreatments(String errorcode, String treatment) {
@@ -377,7 +376,6 @@ public class DecisionPolicyController extends RestrictedBaseController {
VariableReferenceType variableReference = (VariableReferenceType) jaxbDecisionTypes.get(0).getValue();
ruleMap.put("dynamicRuleAlgorithmField1", "S_" + variableReference.getVariableId());
-
// Get from Attribute Value
AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbDecisionTypes.get(1).getValue();
String attributeValue = (String) actionConditionAttributeValue.getContent().get(0);
@@ -402,36 +400,36 @@ public class DecisionPolicyController extends RestrictedBaseController {
index++;
}
}
- if (isCompoundRule) {
- // As it's compound rule, Get the Apply types
- for (JAXBElement<?> jaxbElement : jaxbDecisionTypes) {
- ApplyType innerDecisionApply = (ApplyType) jaxbElement.getValue();
- index = prePopulateDecisionCompoundRuleAlgorithm(index, innerDecisionApply);
- }
- // Populate combo box
- if (policyLogger.isDebugEnabled()) {
- policyLogger.debug("Prepopulating Compound rule algorithm: " + index);
- }
- Map<String, String> rule = new HashMap<>();
- for (String key : PolicyController.getDropDownMap().keySet()) {
- String keyValue = PolicyController.getDropDownMap().get(key);
- if (keyValue.equals(decisionApply.getFunctionId())) {
- rule.put("dynamicRuleAlgorithmCombo", key);
- break;
- }
+ if (! isCompoundRule) {
+ return index;
+ }
+ // As it's compound rule, Get the Apply types
+ for (JAXBElement<?> jaxbElement : jaxbDecisionTypes) {
+ ApplyType innerDecisionApply = (ApplyType) jaxbElement.getValue();
+ index = prePopulateDecisionCompoundRuleAlgorithm(index, innerDecisionApply);
+ }
+ // Populate combo box
+ if (policyLogger.isDebugEnabled()) {
+ policyLogger.debug("Prepopulating Compound rule algorithm: " + index);
+ }
+ Map<String, String> rule = new HashMap<>();
+ for (String key : PolicyController.getDropDownMap().keySet()) {
+ String keyValue = PolicyController.getDropDownMap().get(key);
+ if (keyValue.equals(decisionApply.getFunctionId())) {
+ rule.put("dynamicRuleAlgorithmCombo", key);
+ break;
}
-
- 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);
- ruleAlgorithmList.add(rule);
- index++;
}
- return index;
+ 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);
+ ruleAlgorithmList.add(rule);
+
+ return ++index;
}
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntries.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntries.java
index 5c2e96bb5..0c0c15f05 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntries.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntries.java
@@ -2,14 +2,14 @@
* ============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.
* 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,8 +39,10 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
+
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
@@ -59,6 +61,7 @@ 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.adapter.ReturnBlackList;
+import org.onap.policy.utils.PolicyUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.portalsdk.core.controller.RestrictedBaseController;
import org.onap.portalsdk.core.web.support.JsonMessage;
@@ -66,7 +69,6 @@ import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
-
/**
* This class is used to import and export the black list entries which were used in the Decision Blacklist Guard YAML
* Policy.
@@ -84,7 +86,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
/**
* This method is used to Export the Black List entries data from Decision BlackList Guard YAML Policy. So, user can
* update the file on adding or removing the entries, for updating the policies or using in other Environments.
- *
+ *
* @param request the request contains the policy data. So, based on that we can populate and read and write the
* entries.
* @param response after reading and writing the blacklist list entries to file, the file is copied to tmp directory
@@ -117,7 +119,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
/*
* Export FileName is the combination of BlacList+Scope+PolicyName+Version+PolicyCreatedDate.
- *
+ *
*/
SimpleDateFormat parseFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@@ -126,7 +128,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
String formatedDate = dateFormat.format(date);
String fileName = "BlackList_Scope_" + adapter.getDomainDir() + "_Name_" + adapter.getPolicyName()
- + "_Version_" + root.get("version").toString() + "_Date_" + formatedDate + ".xls";
+ + "_Version_" + root.get("version").toString() + "_Date_" + formatedDate + ".xls";
String deleteCheckPath = tmpFile + File.separator + fileName;
File deleteCheck = new File(deleteCheckPath);
@@ -145,9 +147,9 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
workBook.write(fos);
fos.flush();
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
PrintWriter out = response.getWriter();
String successMap = file.substring(file.lastIndexOf("webapps") + 8);
@@ -163,7 +165,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
/**
* This method is used to import the BlackList excel file into the system. Which is used to create Decision
* Blacklist Guard YAML Policy.
- *
+ *
* @param request the HTTP request contains file upload stream form GUI.
* @param response the response is send to the GUI after reading the file input stream.
*/
@@ -181,9 +183,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
} else {
readItems(items, errorLogs, model);
}
- JsonMessage msg = new JsonMessage(mapper.toJson(model));
- JSONObject jsonResposne = new JSONObject(msg);
- response.getWriter().write(jsonResposne.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.toJson(model))).toString());
} catch (FileUploadException | IOException e) {
policyLogger.error("Exception Occured while importing the BlackListEntry", e);
}
@@ -191,7 +191,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
/**
* This method is used to read the first item, as we expect only one entry in the file upload.
- *
+ *
* @param items The file entries which were uploaded from GUI.
* @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
* @param model Map which stores key value (blacklist and append list data)
@@ -218,7 +218,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
/**
* This method is used to read the workbook in xls file item.
- *
+ *
* @param fileName fileName as input parameter
* @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
* @param model Map which stores key value (blacklist and append list data)
@@ -246,7 +246,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
/**
* This method is used to read all the rows from imported Excel sheet and set to respective objects.
- *
+ *
* @param rowIterator Excel Sheet rows are passed as input parameters.
* @param blackListEntries the data is set to this object, which is going to be added.
* @param appendBlackListEntries the data is set to this object which is going to be removed.
@@ -266,7 +266,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
/**
* This method is used to read all the cells in the row.
- *
+ *
* @param cellIterator iterating the cells and will parse based on the cell type.
* @param blackListEntries the data is set to this object, which is going to be added.
* @param appendBlackListEntries the data is set to this object which is going to be removed.
@@ -300,7 +300,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
/**
* This method is used to read the Action cell entry.
- *
+ *
* @param cell reading the action entry cell.
* @param lineNo counts the number of the cell.
* @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
@@ -328,7 +328,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
/**
* This method is used to read the BlackList cell entry.
- *
+ *
* @param cell reading the blacklist entry cell.
* @param lineNo counts the number of the cell.
* @param errorLogs on adding all incorrect entries, we can let user know what need to fixed.
@@ -353,7 +353,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
/**
* This method is used to add the data to blacklist and append list after parsing each and every row.
- *
+ *
* @param actionEntry it has the input to add or not and holds either 0 or 1.
* @param blackListEntries list to add blacklist entries based on action entry = 1.
* @param appendBlackListEntries list to add append list entries based on action entry = 0.
@@ -370,7 +370,7 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr
/**
* This method is used to identify the header of the cell.
- *
+ *
* @param cell Excel sheet cell is passed as input parameter.
* @return the column header name value
*/
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java
index a8a427970..f2f7d57af 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java
@@ -2,14 +2,14 @@
* ============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.
* 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,9 +20,13 @@
package org.onap.policy.controller;
+import com.att.research.xacml.api.pap.PAPException;
+import com.att.research.xacml.api.pap.PDPPolicy;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
-import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
@@ -32,16 +36,17 @@ import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-
+import lombok.Getter;
+import lombok.Setter;
import org.json.JSONObject;
import org.onap.policy.admin.RESTfulPAPEngine;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.model.PDPGroupContainer;
+import org.onap.policy.utils.PolicyUtils;
import org.onap.policy.utils.UserUtils.Pair;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.policy.xacml.api.pap.OnapPDPGroup;
-import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
import org.onap.policy.xacml.std.pap.StdPDP;
import org.onap.policy.xacml.std.pap.StdPDPGroup;
import org.onap.portalsdk.core.controller.RestrictedBaseController;
@@ -51,370 +56,377 @@ import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
-import com.att.research.xacml.api.pap.PAPException;
-import com.att.research.xacml.api.pap.PDPPolicy;
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
@Controller
@RequestMapping({"/"})
public class PDPController extends RestrictedBaseController {
- private static final Logger policyLogger = FlexLogger.getLogger(PDPController.class);
-
- protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<OnapPDPGroup>());
- private PDPGroupContainer container;
-
- private static String SUPERADMIN = "super-admin";
- private static String SUPEREDITOR = "super-editor";
- private static String SUPERGUEST = "super-guest";
-
- private Set<OnapPDPGroup> groupsData;
-
- private boolean junit = false;
-
- private PolicyController policyController;
- public PolicyController getPolicyController() {
- return policyController;
- }
-
- public void setPolicyController(PolicyController policyController) {
- this.policyController = policyController;
- }
-
- public synchronized void refreshGroups(HttpServletRequest request) {
- synchronized(this.groups) {
- this.groups.clear();
- try {
- PolicyController controller = getPolicyControllerInstance();
- Set<PDPPolicy> filteredPolicies = new HashSet<>();
- Set<String> scopes;
- List<String> roles;
- String userId = isJunit() ? "Test" : 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(!junit&& controller.getPapEngine()==null){
- setPAPEngine(request);
- }
- if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ) {
- if(!junit){
- this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
- }else{
- this.groups.addAll(this.getGroupsData());
- }
- }else{
- if(!userRoles.isEmpty() && !scopes.isEmpty()){
- this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
- List<OnapPDPGroup> tempGroups = new ArrayList<>();
- if(!groups.isEmpty()){
- Iterator<OnapPDPGroup> pdpGroup = groups.iterator();
- while(pdpGroup.hasNext()){
- OnapPDPGroup group = pdpGroup.next();
- Set<PDPPolicy> policies = group.getPolicies();
- for(PDPPolicy policy : policies){
- for(String scope : scopes){
- scope = scope.replace(File.separator, ".");
- String policyName = policy.getId();
- if(policyName.contains(".Config_")){
- policyName = policyName.substring(0, policyName.lastIndexOf(".Config_"));
- }else if(policyName.contains(".Action_")){
- policyName = policyName.substring(0, policyName.lastIndexOf(".Action_"));
- }else if(policyName.contains(".Decision_")){
- policyName = policyName.substring(0, policyName.lastIndexOf(".Decision_"));
- }
- if(policyName.startsWith(scope)){
- filteredPolicies.add(policy);
- }
- }
- }
- pdpGroup.remove();
- StdPDPGroup newGroup = (StdPDPGroup) group;
- newGroup.setPolicies(filteredPolicies);
- tempGroups.add(newGroup);
- }
- groups.clear();
- groups = tempGroups;
- }
- }
- }
- } catch (PAPException e) {
- String message = "Unable to retrieve Groups from server: " + e;
- policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Pap Engine is Null" + message);
- }
- }
- }
-
- private void setPAPEngine(HttpServletRequest request) {
- String myRequestURL = request.getRequestURL().toString();
+ private static final Logger policyLogger = FlexLogger.getLogger(PDPController.class);
+
+ protected List<OnapPDPGroup> groups = Collections.synchronizedList(new ArrayList<OnapPDPGroup>());
+ private PDPGroupContainer container;
+
+ private static String SUPERADMIN = "super-admin";
+ private static String SUPEREDITOR = "super-editor";
+ private static String SUPERGUEST = "super-guest";
+
+ private Set<OnapPDPGroup> groupsData;
+
+ private boolean junit = false;
+
+ private PolicyController policyController;
+
+ public PolicyController getPolicyController() {
+ return policyController;
+ }
+
+ public void setPolicyController(PolicyController policyController) {
+ this.policyController = policyController;
+ }
+
+ /**
+ * refreshGroups.
+ *
+ * @param request HttpServletRequest
+ */
+ public synchronized void refreshGroups(HttpServletRequest request) {
+ synchronized (this.groups) {
+ this.groups.clear();
+ try {
+ PolicyController controller = getPolicyControllerInstance();
+ Set<PDPPolicy> filteredPolicies = new HashSet<>();
+ Set<String> scopes;
+ List<String> roles;
+ String userId = isJunit() ? "Test" : 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.second;
+ scopes = pair.first;
+
+ if (!junit && controller.getPapEngine() == null) {
+ setPapEngine(request);
+ }
+ if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)) {
+ if (!junit) {
+ this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
+ } else {
+ this.groups.addAll(this.getGroupsData());
+ }
+ } else {
+ if (!userRoles.isEmpty() && !scopes.isEmpty()) {
+ this.groups.addAll(controller.getPapEngine().getOnapPDPGroups());
+ List<OnapPDPGroup> tempGroups = new ArrayList<>();
+ if (!groups.isEmpty()) {
+ Iterator<OnapPDPGroup> pdpGroup = groups.iterator();
+ while (pdpGroup.hasNext()) {
+ OnapPDPGroup group = pdpGroup.next();
+ Set<PDPPolicy> policies = group.getPolicies();
+ for (PDPPolicy policy : policies) {
+ for (String scope : scopes) {
+ scope = scope.replace(File.separator, ".");
+ String policyName = policy.getId();
+ if (policyName.contains(".Config_")) {
+ policyName = policyName.substring(0, policyName.lastIndexOf(".Config_"));
+ } else if (policyName.contains(".Action_")) {
+ policyName = policyName.substring(0, policyName.lastIndexOf(".Action_"));
+ } else if (policyName.contains(".Decision_")) {
+ policyName = policyName.substring(0, policyName.lastIndexOf(".Decision_"));
+ }
+ if (policyName.startsWith(scope)) {
+ filteredPolicies.add(policy);
+ }
+ }
+ }
+ pdpGroup.remove();
+ StdPDPGroup newGroup = (StdPDPGroup) group;
+ newGroup.setPolicies(filteredPolicies);
+ tempGroups.add(newGroup);
+ }
+ groups.clear();
+ groups = tempGroups;
+ }
+ }
+ }
+ } catch (PAPException e) {
+ String message = "Unable to retrieve Groups from server: " + e;
+ policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Pap Engine is Null" + message);
+ }
+ }
+ }
+
+ private void setPapEngine(HttpServletRequest request) {
try {
//
// Set the URL for the RESTful PAP Engine
//
- PolicyController.setPapEngine((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL));
- }catch(Exception e){
- policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while loading PAP",e);
+ PolicyController.setPapEngine(new RESTfulPAPEngine(request.getRequestURL().toString()));
+ } catch (Exception e) {
+ policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception Occured while loading PAP", e);
+ }
+ }
+
+ /**
+ * getPDPGroupEntityData.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ @RequestMapping(
+ value = {"/get_PDPGroupData"},
+ method = {org.springframework.web.bind.annotation.RequestMethod.GET},
+ produces = MediaType.APPLICATION_JSON_VALUE)
+ public void getPDPGroupEntityData(HttpServletRequest request, HttpServletResponse response) {
+ try {
+ refreshGroups(request);
+ response.getWriter().write(new JSONObject(new JsonMessage(
+ new ObjectMapper().writeValueAsString(groups))).toString());
+ } catch (Exception e) {
+ policyLogger.error(
+ XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while retrieving the PDP Group data" + e);
+ }
+ }
+
+ /**
+ * savePDPGroup.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ @RequestMapping(
+ value = {"/pdp_Group/save_pdp_group"},
+ method = {org.springframework.web.bind.annotation.RequestMethod.POST})
+ public void savePDPGroup(HttpServletRequest request, HttpServletResponse response) {
+ try {
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ //
+ //
+ //
+ ObjectMapper mapper = new ObjectMapper();
+ PolicyController controller = getPolicyControllerInstance();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ this.container = new PDPGroupContainer(controller.getPapEngine());
+
+ String userId = UserUtils.getUserSession(request).getOrgUserId();
+ policyLogger.info(
+ "*******************Logging UserID for Save PDP Group Function*******************************");
+ policyLogger.info("UserId: " + userId + "PDP Group Data: " + root.get("pdpGroupData").toString());
+ policyLogger.info(
+ "********************************************************************************************");
+
+ StdPDPGroup pdpGroupData = mapper
+ .readValue(root.get("pdpGroupData").toString().replace("groupName", "name"), StdPDPGroup.class);
+ try {
+ if (pdpGroupData.getId() == null) {
+ this.container.addNewGroup(pdpGroupData.getName(), pdpGroupData.getDescription());
+ } else {
+ this.container.updateGroup(pdpGroupData);
+ }
+
+ } catch (Exception e) {
+ String message = "Unable to create Group. Reason:\n" + e.getMessage();
+ policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while creating the PDP Group"
+ + message + e);
+ }
+
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
+
+ refreshGroups(request);
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
+ } catch (Exception e) {
+ policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Saving the PDP Group" + e);
+ try {
+ response.getWriter().write(e.getMessage());
+ } catch (Exception e1) {
+ policyLogger
+ .error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Saving the PDP Group" + e1);
+ }
+ }
+ }
+
+ /**
+ * removePDPGroup.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ @RequestMapping(
+ value = {"/pdp_Group/remove_pdp_group"},
+ method = {org.springframework.web.bind.annotation.RequestMethod.POST})
+ public void removePDPGroup(HttpServletRequest request, HttpServletResponse response) {
+ try {
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ //
+ //
+ //
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ PolicyController controller = getPolicyControllerInstance();
+ this.container = new PDPGroupContainer(controller.getPapEngine());
+
+ String userId = UserUtils.getUserSession(request).getOrgUserId();
+ policyLogger.info(
+ "*********************Logging UserID for Remove PDP Group Function*******************************");
+ policyLogger.info("UserId: " + userId + "PDP Group Data: " + root.get("pdpGroupData").toString());
+ policyLogger.info(
+ "************************************************************************************************");
+
+ StdPDPGroup pdpGroupData = mapper.readValue(root.get("pdpGroupData").toString(), StdPDPGroup.class);
+ if ("Default".equals(pdpGroupData.getName())) {
+ throw new UnsupportedOperationException("You can't remove the Default Group.");
+ } else {
+ this.container.removeGroup(pdpGroupData, null);
+ }
+
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
+ refreshGroups(request);
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
+ } catch (Exception e) {
+ policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Removing the PDP Group" + e);
+ try {
+ response.getWriter().write(e.getMessage());
+ } catch (Exception e1) {
+ policyLogger.error("Exception Occured" + e1);
+ }
+ }
+ }
+
+ /**
+ * savePDPToGroup.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ @RequestMapping(
+ value = {"/pdp_Group/save_pdpTogroup"},
+ method = {org.springframework.web.bind.annotation.RequestMethod.POST})
+ public void savePDPToGroup(HttpServletRequest request, HttpServletResponse response) {
+ try {
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ //
+ //
+ //
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ PolicyController controller = getPolicyControllerInstance();
+ this.container = new PDPGroupContainer(controller.getPapEngine());
+ String update = root.get("update").toString();
+ PdpData pdpGroupData = mapper.readValue(root.get("pdpInGroup").toString(), PdpData.class);
+ StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);
+
+ String userId = UserUtils.getUserSession(request).getOrgUserId();
+ policyLogger.info(
+ "*************Logging UserID while Saving pdp in PDP Group***********************************");
+ policyLogger.info("UserId: " + userId + "PDP Group Data: " + root.get("pdpInGroup").toString()
+ + "Active Group Data: " + root.get("activePDP").toString());
+ policyLogger.info(
+ "**********************************************************************************************");
+
+ try {
+
+ if (update.contains("false")) {
+ this.container.addNewPDP(pdpGroupData.getId(), activeGroupData, pdpGroupData.getName(),
+ pdpGroupData.getDescription(), pdpGroupData.getJmxPort());
+ } else {
+ this.container.updateGroup(activeGroupData);
+ }
+ } catch (Exception e) {
+ String message = "Unable to create Group. Reason:\n" + e.getMessage();
+ policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE
+ + "Error Occured while Creating Pdp in PDP Group" + message + e);
+ }
+
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
+ refreshGroups(request);
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
+ } catch (Exception e) {
+ policyLogger
+ .error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Creating Pdp in PDP Group" + e);
+ try {
+ response.getWriter().write(e.getMessage());
+ } catch (Exception e1) {
+ policyLogger.error("Exception Occured" + e1);
+ }
}
}
- @RequestMapping(value={"/get_PDPGroupData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
- public void getPDPGroupEntityData(HttpServletRequest request, HttpServletResponse response){
- try{
- ObjectMapper mapper = new ObjectMapper();
- refreshGroups(request);
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
- }
- catch (Exception e){
- policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while retrieving the PDP Group data" + e);
- }
- }
-
- @RequestMapping(value={"/pdp_Group/save_pdp_group"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
- public void savePDPGroup(HttpServletRequest request, HttpServletResponse response){
- try {
- ObjectMapper mapper = new ObjectMapper();
- PolicyController controller = getPolicyControllerInstance();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- this.container = new PDPGroupContainer(controller.getPapEngine());
-
- String userId = UserUtils.getUserSession(request).getOrgUserId();
- policyLogger.info("****************************************Logging UserID for Save PDP Group Function*****************************************");
- policyLogger.info("UserId: " + userId + "PDP Group Data: "+ root.get("pdpGroupData").toString());
- policyLogger.info("***************************************************************************************************************************");
-
- StdPDPGroup pdpGroupData = mapper.readValue(root.get("pdpGroupData").toString().replace("groupName", "name"), StdPDPGroup.class);
- try {
- if(pdpGroupData.getId() == null){
- this.container.addNewGroup(pdpGroupData.getName(), pdpGroupData.getDescription());
- }else{
- this.container.updateGroup(pdpGroupData);
- }
-
- } catch (Exception e) {
- String message = "Unable to create Group. Reason:\n" + e.getMessage();
- policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while creating the PDP Group" + message + e);
- }
-
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
-
- PrintWriter out = response.getWriter();
- refreshGroups(request);
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
- JSONObject j = new JSONObject(msg);
- out.write(j.toString());
- }
- catch (Exception e){
- policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Saving the PDP Group" + e);
- response.setCharacterEncoding("UTF-8");
- PrintWriter out = null;
- try {
- request.setCharacterEncoding("UTF-8");
- out = response.getWriter();
- out.write(e.getMessage());
- } catch (Exception e1) {
- policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Saving the PDP Group" + e1);
- }
- }
- }
-
- @RequestMapping(value={"/pdp_Group/remove_pdp_group"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
- public void removePDPGroup(HttpServletRequest request, HttpServletResponse response){
- try{
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- PolicyController controller = getPolicyControllerInstance();
- this.container = new PDPGroupContainer(controller.getPapEngine());
-
- String userId = UserUtils.getUserSession(request).getOrgUserId();
- policyLogger.info("****************************************Logging UserID for Remove PDP Group Function*****************************************");
- policyLogger.info("UserId: " + userId + "PDP Group Data: "+ root.get("pdpGroupData").toString());
- policyLogger.info("*****************************************************************************************************************************");
-
- StdPDPGroup pdpGroupData = mapper.readValue(root.get("pdpGroupData").toString(), StdPDPGroup.class);
- if("Default".equals(pdpGroupData.getName())) {
- throw new UnsupportedOperationException("You can't remove the Default Group.");
- }else{
- this.container.removeGroup(pdpGroupData, null);
- }
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
-
- PrintWriter out = response.getWriter();
-
- refreshGroups(request);
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
- JSONObject j = new JSONObject(msg);
- out.write(j.toString());
- }
- catch (Exception e){
- policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing the PDP Group" + e);
- PrintWriter out;
- try {
- response.setCharacterEncoding("UTF-8");
- request.setCharacterEncoding("UTF-8");
- out = response.getWriter();
- out.write(e.getMessage());
- } catch (Exception e1) {
- policyLogger.error("Exception Occured"+ e1);
- }
- }
- }
-
- @RequestMapping(value={"/pdp_Group/save_pdpTogroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
- public void savePDPToGroup(HttpServletRequest request, HttpServletResponse response){
- try {
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- PolicyController controller = getPolicyControllerInstance();
- this.container = new PDPGroupContainer(controller.getPapEngine());
- String update = root.get("update").toString();
- PdpData pdpGroupData = mapper.readValue(root.get("pdpInGroup").toString(), PdpData.class);
- StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);
-
- String userId = UserUtils.getUserSession(request).getOrgUserId();
- policyLogger.info("****************************************Logging UserID while Saving pdp in PDP Group*****************************************");
- policyLogger.info("UserId: " + userId + "PDP Group Data: "+ root.get("pdpInGroup").toString() + "Active Group Data: "+ root.get("activePDP").toString());
- policyLogger.info("*******************************************************************************************************************************");
-
- try {
-
- if(update.contains("false")){
- this.container.addNewPDP(pdpGroupData.getId(), activeGroupData, pdpGroupData.getName(), pdpGroupData.getDescription(), pdpGroupData.getJmxPort());
- }else{
- this.container.updateGroup(activeGroupData);
- }
- } catch (Exception e) {
- String message = "Unable to create Group. Reason:\n" + e.getMessage();
- policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + message + e);
- }
-
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
-
- PrintWriter out = response.getWriter();
- refreshGroups(request);
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
- JSONObject j = new JSONObject(msg);
- out.write(j.toString());
- }
- catch (Exception e){
- policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + e);
- PrintWriter out;
- try {
- response.setCharacterEncoding("UTF-8");
- request.setCharacterEncoding("UTF-8");
- out = response.getWriter();
- out.write(e.getMessage());
- } catch (Exception e1) {
- policyLogger.error("Exception Occured"+ e1);
- }
- }
- }
-
- @RequestMapping(value={"/pdp_Group/remove_pdpFromGroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
- public void removePDPFromGroup(HttpServletRequest request, HttpServletResponse response){
- try{
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- PolicyController controller = getPolicyControllerInstance();
- this.container = new PDPGroupContainer(controller.getPapEngine());
- StdPDP deletePdp = mapper.readValue(root.get("data").toString(), StdPDP.class);
- StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);
-
- String userId = UserUtils.getUserSession(request).getOrgUserId();
- policyLogger.info("****************************************Logging UserID while Removing pdp from PDP Group*****************************************");
- policyLogger.info("UserId: " + userId + "Delete PDP Group Data: "+ root.get("data").toString() + "Active Group Data: "+ root.get("activePDP").toString());
- policyLogger.info("***********************************************************************************************************************************");
-
- this.container.removePDP(deletePdp, activeGroupData);
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
-
- PrintWriter out = response.getWriter();
- refreshGroups(request);
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups));
- JSONObject j = new JSONObject(msg);
- out.write(j.toString());
- }
- catch (Exception e){
- policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing Pdp from PDP Group" + e);
- PrintWriter out;
- try {
- response.setCharacterEncoding("UTF-8");
- request.setCharacterEncoding("UTF-8");
- out = response.getWriter();
- out.write(e.getMessage());
- } catch (Exception e1) {
- policyLogger.error("Exception Occured"+ e1);
- }
- }
- }
-
- private PolicyController getPolicyControllerInstance(){
- return policyController != null ? getPolicyController() : new PolicyController();
- }
-
- public boolean isJunit() {
- return junit;
- }
-
- public void setJunit(boolean junit) {
- this.junit = junit;
- }
-
- public Set<OnapPDPGroup> getGroupsData() {
- return groupsData;
- }
-
- public void setGroupsData(Set<OnapPDPGroup> groupsData) {
- this.groupsData = groupsData;
- }
+ /**
+ * removePDPFromGroup.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ */
+ @RequestMapping(
+ value = {"/pdp_Group/remove_pdpFromGroup"},
+ method = {org.springframework.web.bind.annotation.RequestMethod.POST})
+ public void removePDPFromGroup(HttpServletRequest request, HttpServletResponse response) {
+ try {
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ //
+ //
+ //
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ PolicyController controller = getPolicyControllerInstance();
+ this.container = new PDPGroupContainer(controller.getPapEngine());
+
+ String userId = UserUtils.getUserSession(request).getOrgUserId();
+ policyLogger.info(
+ "********************Logging UserID while Removing pdp from PDP Group**************************");
+ policyLogger.info("UserId: " + userId + "Delete PDP Group Data: " + root.get("data").toString()
+ + "Active Group Data: " + root.get("activePDP").toString());
+ policyLogger.info(
+ "************************************************************************************************");
+
+ StdPDP deletePdp = mapper.readValue(root.get("data").toString(), StdPDP.class);
+ StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);
+ this.container.removePDP(deletePdp, activeGroupData);
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
+
+ refreshGroups(request);
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString());
+ } catch (Exception e) {
+ policyLogger.error(
+ XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Removing Pdp from PDP Group" + e);
+ try {
+ response.getWriter().write(e.getMessage());
+ } catch (Exception e1) {
+ policyLogger.error("Exception Occured" + e1);
+ }
+ }
+ }
+
+ private PolicyController getPolicyControllerInstance() {
+ return policyController != null ? getPolicyController() : new PolicyController();
+ }
+
+ public boolean isJunit() {
+ return junit;
+ }
+
+ public void setJunit(boolean junit) {
+ this.junit = junit;
+ }
+
+ public Set<OnapPDPGroup> getGroupsData() {
+ return groupsData;
+ }
+
+ public void setGroupsData(Set<OnapPDPGroup> groupsData) {
+ this.groupsData = groupsData;
+ }
}
-class PdpData{
- String id;
- int jmxPort;
- String name;
- String description;
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- public int getJmxPort() {
- return jmxPort;
- }
- public void setJmxPort(int jmxPort) {
- this.jmxPort = jmxPort;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getDescription() {
- return description;
- }
- public void setDescription(String description) {
- this.description = description;
- }
-
+@Getter
+@Setter
+class PdpData {
+ String id;
+ int jmxPort;
+ String name;
+ String description;
}
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 700aa3a57..dbf744829 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
@@ -24,6 +24,7 @@ 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;
@@ -37,12 +38,15 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
+
import javax.annotation.PostConstruct;
import javax.script.SimpleBindings;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
+
import org.json.JSONObject;
import org.onap.policy.admin.PolicyNotificationMail;
import org.onap.policy.admin.RESTfulPAPEngine;
@@ -52,7 +56,7 @@ import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.model.PDPGroupContainer;
import org.onap.policy.model.Roles;
-import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.rest.XacmlRestProperties;
import org.onap.policy.rest.dao.CommonClassDao;
import org.onap.policy.rest.jpa.Datatype;
import org.onap.policy.rest.jpa.FunctionDefinition;
@@ -60,6 +64,7 @@ import org.onap.policy.rest.jpa.PolicyEntity;
import org.onap.policy.rest.jpa.PolicyVersion;
import org.onap.policy.rest.jpa.UserInfo;
import org.onap.policy.utils.PeCryptoUtils;
+import org.onap.policy.utils.PolicyUtils;
import org.onap.policy.utils.UserUtils.Pair;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
@@ -99,7 +104,7 @@ public class PolicyController extends RestrictedBaseController {
}
public static String getDomain() {
- return XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_DOMAIN, "urn");
+ return XACMLProperties.getProperty(XacmlRestProperties.PROP_ADMIN_DOMAIN, "urn");
}
private static final Object mapAccess = new Object();
@@ -108,8 +113,6 @@ public class PolicyController extends RestrictedBaseController {
// Constant variables used across Policy-sdk
private static final String policyData = "policyData";
- 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";
@@ -160,8 +163,8 @@ public class PolicyController extends RestrictedBaseController {
return jUnit;
}
- public static void setjUnit(boolean jUnit) {
- PolicyController.jUnit = jUnit;
+ public static void setjUnit(boolean isJunit) {
+ PolicyController.jUnit = isJunit;
}
@Autowired
@@ -183,9 +186,8 @@ 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";
}
@@ -236,19 +238,17 @@ 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
@@ -298,8 +298,7 @@ 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);
}
@@ -311,22 +310,20 @@ public class PolicyController extends RestrictedBaseController {
* @param request HttpServletRequest.
* @param response HttpServletResponse.
*/
- @RequestMapping(value = {"/get_FunctionDefinitionDataByName"},
+ @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")));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ model.put("functionDefinitionDatas",
+ mapper.writeValueAsString(commonClassDao.getDataByColumn(FunctionDefinition.class, "shortname")));
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).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);
}
}
@@ -368,7 +365,8 @@ public class PolicyController extends RestrictedBaseController {
* @param request HttpServletRequest.
* @param response HttpServletResponse.
*/
- @RequestMapping(value = {"/get_UserRolesData"},
+ @RequestMapping(
+ value = {"/get_UserRolesData"},
method = {org.springframework.web.bind.annotation.RequestMethod.GET},
produces = MediaType.APPLICATION_JSON_VALUE)
public void getUserRolesEntityData(HttpServletRequest request, HttpServletResponse response) {
@@ -377,9 +375,7 @@ public class PolicyController extends RestrictedBaseController {
Map<String, Object> model = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
model.put("userRolesDatas", mapper.writeValueAsString(getRolesOfUser(userId)));
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
- JSONObject j = new JSONObject(msg);
- response.getWriter().write(j.toString());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
policyLogger.error("Exception Occured" + e);
}
@@ -402,8 +398,7 @@ public class PolicyController extends RestrictedBaseController {
setPapEngine(new RESTfulPAPEngine(myRequestUrl));
new PDPGroupContainer(new RESTfulPAPEngine(myRequestUrl));
} catch (Exception e) {
- policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR
- + "Exception Occured while loading PAP" + e);
+ policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception Occured while loading PAP" + e);
}
Map<String, Object> model = new HashMap<>();
return new ModelAndView("policy_Editor", "model", model);
@@ -438,9 +433,8 @@ public class PolicyController extends RestrictedBaseController {
savePolicyRoles(name, filteredRole, userId);
} else {
userRoles = getRoles(userId);
- Pair<Set<String>, List<String>> pair =
- org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
- roles = pair.u;
+ Pair<Set<String>, List<String>> pair = org.onap.policy.utils.UserUtils.checkRoleAndScope(userRoles);
+ roles = pair.second;
if (!roles.contains(filteredRole)) {
savePolicyRoles(name, filteredRole, userId);
}
@@ -511,8 +505,7 @@ public class PolicyController extends RestrictedBaseController {
roles.clear();
roles.add(SUPERADMIN);
}
- if (!roles.contains(SUPERADMIN)
- || (POLICYGUEST.equalsIgnoreCase(role) && !superCheck)) {
+ if (!roles.contains(SUPERADMIN) || (POLICYGUEST.equalsIgnoreCase(role) && !superCheck)) {
if ("Policy Admin".equalsIgnoreCase(role.trim())) {
roles.add("admin");
} else if ("Policy Editor".equalsIgnoreCase(role.trim())) {
@@ -576,8 +569,7 @@ 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) {
@@ -604,11 +596,11 @@ public class PolicyController extends RestrictedBaseController {
/**
* Switch Version Policy Content.
*
- * @param pName which is used to find associated versions.
+ * @param thePolicyName which is used to find associated versions.
* @return list of available versions based on policy name.
*/
- public JSONObject switchVersionPolicyContent(String pName) {
- String policyName = pName;
+ public JSONObject switchVersionPolicyContent(String thePolicyName) {
+ String policyName = thePolicyName;
String dbCheckName = policyName.replace("/", ".");
if (dbCheckName.contains("Config_")) {
dbCheckName = dbCheckName.replace(".Config_", ":Config_");
@@ -620,25 +612,23 @@ public class PolicyController extends RestrictedBaseController {
dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
}
String[] splitDbCheckName = dbCheckName.split(":");
- String query =
- "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
+ String query = "FROM PolicyEntity where policyName like :splitDBCheckName1 and scope = :splitDBCheckName0";
SimpleBindings params = new SimpleBindings();
params.put("splitDBCheckName1", splitDbCheckName[1] + "%");
params.put("splitDBCheckName0", splitDbCheckName[0]);
- List<Object> policyEntity = commonClassDao.getDataByQuery(query, params);
List<String> av = new ArrayList<>();
- for (Object entity : policyEntity) {
- PolicyEntity pEntity = (PolicyEntity) entity;
- String removeExtension = pEntity.getPolicyName().replace(".xml", "");
+ for (Object entity : commonClassDao.getDataByQuery(query, params)) {
+ PolicyEntity policyEntity = (PolicyEntity) entity;
+ String removeExtension = policyEntity.getPolicyName().replace(".xml", "");
String version = removeExtension.substring(removeExtension.lastIndexOf('.') + 1);
- String userName = getUserId(pEntity, "@ModifiedBy:");
- av.add(version + " | " + pEntity.getModifiedDate() + " | " + userName);
+ String userName = getUserId(policyEntity, "@ModifiedBy:");
+ av.add(version + " | " + policyEntity.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);
@@ -646,13 +636,20 @@ public class PolicyController extends RestrictedBaseController {
return el;
}
+ /**
+ * getUserId.
+ *
+ * @param data PolicyEntity
+ * @param value String
+ * @return String
+ */
public String getUserId(PolicyEntity data, String value) {
String userId = "";
- String uValue = value;
+ String userValue = value; // Why?
String description = getDescription(data);
- if (description.contains(uValue)) {
- userId = description.substring(description.indexOf(uValue) + uValue.length(),
- description.lastIndexOf(uValue));
+ if (description.contains(userValue)) {
+ userId = description.substring(description.indexOf(userValue) + userValue.length(),
+ description.lastIndexOf(userValue));
}
UserInfo userInfo = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", userId);
if (userInfo == null) {
@@ -661,35 +658,43 @@ public class PolicyController extends RestrictedBaseController {
return userInfo.getUserName();
}
+ /**
+ * getDescription.
+ *
+ * @param data PolicyEntity
+ * @return String
+ */
public String getDescription(PolicyEntity data) {
- InputStream stream =
- new ByteArrayInputStream(data.getPolicyData().getBytes(StandardCharsets.UTF_8));
+ InputStream stream = new ByteArrayInputStream(data.getPolicyData().getBytes(StandardCharsets.UTF_8));
Object policy = XACMLPolicyScanner.readPolicy(stream);
if (policy instanceof PolicySetType) {
return ((PolicySetType) policy).getDescription();
} else if (policy instanceof PolicyType) {
return ((PolicyType) policy).getDescription();
- } else {
- PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE
- + "Expecting a PolicySet/Policy/Rule object. Got: "
- + policy.getClass().getCanonicalName());
- return null;
}
+ PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Expecting a PolicySet/Policy/Rule object. Got: "
+ + policy.getClass().getCanonicalName());
+ return null;
}
+ /**
+ * getUserInfo.
+ *
+ * @param data PolicyEntity
+ * @param activePolicies list of active policies
+ * @return array of String
+ */
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);
+ 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());
+ userCreate = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", polVersion.getCreatedBy());
+ userModify = (UserInfo) getEntityItem(UserInfo.class, "userLoginId", polVersion.getModifiedBy());
}
result[0] = userCreate != null ? userCreate.getUserName() : SUPERADMIN;
@@ -726,8 +731,7 @@ 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;
}
@@ -940,11 +944,11 @@ public class PolicyController extends RestrictedBaseController {
}
public static String getCharacterencoding() {
- return characterEncoding;
+ return PolicyUtils.CHARACTER_ENCODING;
}
public static String getContenttype() {
- return contentType;
+ return PolicyUtils.APPLICATION_JSON;
}
public static String getFile() {
@@ -969,17 +973,4 @@ public class PolicyController extends RestrictedBaseController {
return fileSizeLimit;
}
- /**
- * Function to convert date.
- *
- * @param dateTTL input date value.
- * @return
- */
- public String convertDate(String dateTTL) {
- String formateDate = null;
- if (dateTTL.contains("-")) {
- formateDate = dateTTL.replace("-", "/");
- }
- return formateDate;
- }
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java
index 6c7a0aff3..cf7e62b46 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 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.
@@ -38,6 +38,7 @@ import java.util.Set;
import javax.script.SimpleBindings;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
@@ -52,7 +53,7 @@ import org.onap.policy.rest.adapter.PolicyExportAdapter;
import org.onap.policy.rest.dao.CommonClassDao;
import org.onap.policy.rest.jpa.ActionBodyEntity;
import org.onap.policy.rest.jpa.ConfigurationDataEntity;
-import org.onap.policy.rest.jpa.DCAEuuid;
+import org.onap.policy.rest.jpa.DcaeUuid;
import org.onap.policy.rest.jpa.GroupPolicyScopeList;
import org.onap.policy.rest.jpa.MicroServiceConfigName;
import org.onap.policy.rest.jpa.MicroServiceLocation;
@@ -61,10 +62,12 @@ import org.onap.policy.rest.jpa.PolicyEditorScopes;
import org.onap.policy.rest.jpa.PolicyEntity;
import org.onap.policy.rest.jpa.PolicyVersion;
import org.onap.policy.rest.jpa.UserInfo;
+import org.onap.policy.utils.PolicyUtils;
import org.onap.policy.utils.UserUtils.Pair;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.portalsdk.core.controller.RestrictedBaseController;
import org.onap.portalsdk.core.web.support.UserUtils;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@@ -90,7 +93,6 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
private static final String ACTION = "Action_";
private static CommonClassDao commonClassDao;
-
private PolicyController policyController;
public PolicyController getPolicyController() {
@@ -113,14 +115,20 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
// Empty constructor
}
+ @Autowired
+ private PolicyExportAndImportController(CommonClassDao commonClassDao) {
+ PolicyExportAndImportController.commonClassDao = commonClassDao;
+ }
+
/**
* This is for downloading existing policy.
- *
+ *
* @param request HttpServletRequest
* @param response HttpServletResponse
* @throws IOException error out
*/
- @RequestMapping(value = {"/policy_download/exportPolicy.htm"},
+ @RequestMapping(
+ value = {"/policy_download/exportPolicy.htm"},
method = {org.springframework.web.bind.annotation.RequestMethod.POST})
public void exportPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException {
try (HSSFWorkbook workBook2 = new HSSFWorkbook()) {
@@ -134,9 +142,8 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
LinkedHashMap<?, ?> selected = (LinkedHashMap<?, ?>) policyId;
String policyWithScope =
selected.get(policyName).toString() + "." + selected.get("activeVersion").toString() + ".xml";
- String scope =
- policyWithScope.substring(0, policyWithScope.lastIndexOf(File.separator)).replace(
- File.separator, ".");
+ String scope = policyWithScope.substring(0, policyWithScope.lastIndexOf(File.separator))
+ .replace(File.separator, ".");
String policyNamel = policyWithScope.substring(policyWithScope.lastIndexOf(File.separator) + 1);
selectedPolicy.add(policyNamel + ":" + scope);
}
@@ -152,9 +159,8 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
headingRow.createCell(6).setCellValue(BODYSIZE);
headingRow.createCell(7).setCellValue(configurationbody);
- List<Object> entityData =
- commonClassDao.getMultipleDataOnAddingConjunction(PolicyEntity.class, "policyName:scope",
- selectedPolicy);
+ List<Object> entityData = commonClassDao.getMultipleDataOnAddingConjunction(PolicyEntity.class,
+ "policyName:scope", selectedPolicy);
processEntityData(entityData, sheet, headingRow); //
String tmp = System.getProperty("catalina.base") + File.separator + "webapps" + File.separator + "temp";
String deleteCheckPath = tmp + File.separator + "PolicyExport.xls";
@@ -173,14 +179,14 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
workBook2.write(fos);
fos.flush();
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
PrintWriter out = response.getWriter();
String successMap = file.substring(file.lastIndexOf("webapps") + 8);
String responseString = mapper.writeValueAsString(successMap);
- JSONObject j = new JSONObject("{data: " + responseString + "}");
- out.write(j.toString());
+ JSONObject json = new JSONObject("{data: " + responseString + "}");
+ out.write(json.toString());
} catch (Exception e) {
logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception Occured while Exporting Policies" + e);
}
@@ -233,8 +239,8 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
row.createCell(7).setCellValue(body.substring(index, Math.min(index + 30000, body.length())));
} else {
headingRow.createCell(7 + arraySize).setCellValue(configurationbody + arraySize);
- row.createCell(7 + arraySize).setCellValue(
- body.substring(index, Math.min(index + 30000, body.length())));
+ row.createCell(7 + arraySize)
+ .setCellValue(body.substring(index, Math.min(index + 30000, body.length())));
}
index += 30000;
arraySize += 1;
@@ -247,17 +253,15 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
return row;
}
-
-
/**
* This is to upload a policy and save it to database.
- *
+ *
* @param file String
* @param request HttpServletRequest
* @return JSONObject
* @throws IOException error out
*/
- public JSONObject importRepositoryFile(String file, HttpServletRequest request) throws IOException {
+ public String importRepositoryFile(String file, HttpServletRequest request) throws IOException {
boolean configExists = false;
boolean actionExists = false;
String configName = null;
@@ -269,14 +273,14 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
// Check if the Role and Scope Size are Null get the values from db.
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;
+ List<String> roles = pair.second;
+ Set<String> scopes = pair.first;
try (FileInputStream excelFile = new FileInputStream(new File(file));
HSSFWorkbook workbook = new HSSFWorkbook(excelFile)) {
Sheet datatypeSheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = datatypeSheet.iterator();
-
+ String sendResult = null;
while (rowIterator.hasNext()) {
finalColumn = false;
PolicyEntity policyEntity = new PolicyEntity();
@@ -291,6 +295,7 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
int bodySize = 0;
int setBodySize = 0;
boolean configurationBodySet = false;
+ boolean errorFlag = false;
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if (policyName.equalsIgnoreCase(getCellHeaderName(cell))) {
@@ -314,13 +319,18 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
configurationDataEntity =
populateConfigurationDataEntity(policyEntity, configurationDataEntity, cell);
actionBodyEntity = populateActionBodyObject(policyEntity, actionBodyEntity, cell);
- JSONObject response = validatRequiredValue(policyEntity, body, finalColumn, configurationBodySet);
- if (response != null) {
- return response;
+ String response = null;
+ response = validatRequiredValue(policyEntity, body, finalColumn, configurationBodySet);
+ if (!StringUtils.isBlank(response)) {
+ sendResult = sendResult + "\n" + response;
+ errorFlag = true;
+ }
+ if (!StringUtils.isBlank(response) && !rowIterator.hasNext()) {
+ return sendResult;
}
savePolicyEntiies(finalColumn, configurationBodySet, configurationDataEntity, policyEntity,
controller, roles, userInfo, scopes, configName, userId, configExists, actionExists,
- actionBodyEntity, body);
+ actionBodyEntity, body, errorFlag);
}
}
@@ -331,9 +341,8 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
}
private void writeConfigurationFile(ConfigurationDataEntity configurationDataEntity) {
- try (FileWriter fw =
- new FileWriter(PolicyController.getConfigHome() + File.separator
- + configurationDataEntity.getConfigurationName())) {
+ try (FileWriter fw = new FileWriter(
+ PolicyController.getConfigHome() + File.separator + configurationDataEntity.getConfigurationName())) {
BufferedWriter bw = new BufferedWriter(fw);
bw.write(configurationDataEntity.getConfigBody());
bw.close();
@@ -343,8 +352,8 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
}
private void writeActionBodyFile(ActionBodyEntity actionBodyEntity) {
- try (FileWriter fw =
- new FileWriter(PolicyController.getActionHome() + File.separator + actionBodyEntity.getActionBodyName())) {
+ try (FileWriter fw = new FileWriter(
+ PolicyController.getActionHome() + File.separator + actionBodyEntity.getActionBodyName())) {
BufferedWriter bw = new BufferedWriter(fw);
bw.write(actionBodyEntity.getActionBody());
bw.close();
@@ -360,49 +369,46 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
/**
* This is to validate all matching required fields.
- *
+ *
* @param policyName String
* @param jsonString String
* @return String
*/
public String validatMatchRequiredFields(String policyName, String jsonString) {
-
+ String errorMsg = "";
try {
JSONObject jsonObject = new JSONObject(jsonString);
- String configName = jsonObject.getString("configName");
- String uuid = jsonObject.getString("uuid");
- String erorMsg = validConfigName(configName);
- if (erorMsg != null) {
- return erorMsg;
+ String confErorMsg = validConfigName(jsonObject.getString("configName"));
+ if (!confErorMsg.isEmpty()) {
+ errorMsg = errorMsg + "\n POLICY :" + policyName + " at " + confErorMsg;
}
- erorMsg = validUuid(uuid);
- if (erorMsg != null) {
- return erorMsg;
+ String uuidErorMsg = validUuid(jsonObject.getString("uuid"));
+ if (!uuidErorMsg.isEmpty()) {
+ errorMsg = errorMsg + "\n POLICY :" + policyName + " at " + uuidErorMsg;
}
- String location = jsonObject.getString("location");
- erorMsg = validLocation(location);
- if (erorMsg != null) {
- return erorMsg;
+ String locErorMsg = validLocation(jsonObject.getString("location"));
+ if (!locErorMsg.isEmpty()) {
+ errorMsg = errorMsg + "\n POLICY :" + policyName + " at " + locErorMsg;
}
- String policyScope = jsonObject.getString("policyScope");
- erorMsg = validPolicyScope(policyScope);
- if (erorMsg != null) {
- return erorMsg;
+ String pScopeErorMsg = validPolicyScope(jsonObject.getString("policyScope"));
+ if (!pScopeErorMsg.isEmpty()) {
+ errorMsg = errorMsg + "\n POLICY :" + policyName + " at " + pScopeErorMsg;
}
String msVersion = jsonObject.getString("version");
String msService = jsonObject.getString("service");
if (!isAttributeObjectFound(msService, msVersion)) {
- return POLICY + policyName + " MS Service: " + msService + " and MS Version: " + msVersion + NOTVALID;
+ errorMsg = errorMsg + "\n POLICY :" + policyName + " at MS Service: " + msService + " and MS Version: "
+ + msVersion + NOTVALID;
}
} catch (Exception e) {
logger.error("Exception Occured While validating required fields", e);
}
- return null;
+ return errorMsg;
}
- private JSONObject validatRequiredValue(PolicyEntity policyEntity, StringBuilder body, boolean finalColumn,
+ private String validatRequiredValue(PolicyEntity policyEntity, StringBuilder body, boolean finalColumn,
boolean configurationBodySet) {
if (finalColumn && configurationBodySet && (policyEntity.getPolicyName().contains(CONFIG_MS))) {
String errorMsg = validatMatchRequiredFields(policyEntity.getPolicyName(), body.toString());
@@ -410,7 +416,7 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
logger.error("errorMsg => " + errorMsg);
JSONObject response = new JSONObject();
response.append("error", errorMsg);
- return response;
+ return errorMsg;
}
}
return null;
@@ -433,7 +439,7 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
private String validUuid(String uuid) {
String message = null;
if (uuid != null) {
- List<String> uuids = commonClassDao.getDataByColumn(DCAEuuid.class, "name");
+ List<String> uuids = commonClassDao.getDataByColumn(DcaeUuid.class, "name");
if (uuids != null && !(uuids.stream().filter(o -> o.equals(uuid)).findFirst().isPresent())) {
message = POLICY + policyName + " uuid: " + uuid + NOTVALID;
}
@@ -565,6 +571,7 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
return false;
}
+ @SuppressWarnings("rawtypes")
private boolean isContinue(List<String> roles, String scope, UserInfo userInfo, Set scopes) {
if (roles.contains(admin) || roles.contains(editor)) {
if (scopes.isEmpty()) {
@@ -605,14 +612,12 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
private void savePolicyEntity(PolicyEntity policyEntity, String configName, String userId) {
if (configName != null) {
if (configName.contains(config) || configName.contains(DECISION_MS)) {
- ConfigurationDataEntity configuration =
- (ConfigurationDataEntity) commonClassDao.getEntityItem(ConfigurationDataEntity.class,
- configurationName, configName);
+ ConfigurationDataEntity configuration = (ConfigurationDataEntity) commonClassDao
+ .getEntityItem(ConfigurationDataEntity.class, configurationName, configName);
policyEntity.setConfigurationData(configuration);
} else {
- ActionBodyEntity actionBody =
- (ActionBodyEntity) commonClassDao.getEntityItem(ActionBodyEntity.class, "actionBodyName",
- configName);
+ ActionBodyEntity actionBody = (ActionBodyEntity) commonClassDao.getEntityItem(ActionBodyEntity.class,
+ "actionBodyName", configName);
policyEntity.setActionBodyEntity(actionBody);
}
}
@@ -639,8 +644,9 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
private int getSetBodySize(PolicyEntity policyEntity, Cell cell, int setBodySize) {
int setBodySizel = setBodySize;
if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
- && ((policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName()
- .contains(DECISION_MS)) && (policyEntity.getPolicyName().contains("Config_BRMS_Param_")))) {
+ && ((policyEntity.getPolicyName().contains(config)
+ || policyEntity.getPolicyName().contains(DECISION_MS))
+ && (policyEntity.getPolicyName().contains("Config_BRMS_Param_")))) {
setBodySizel += 1;
}
return setBodySizel;
@@ -664,29 +670,28 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
boolean configurationBodySet) {
boolean configurationBodySetl = configurationBodySet;
if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
- && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS))
- && (setBodySize == bodySize)) {
+ && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS))
+ && (setBodySize == bodySize)) {
configurationBodySetl = true;
}
if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
- && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS))
- && (setBodySize == 0)) {
+ && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS))
+ && (setBodySize == 0)) {
configurationBodySetl = true;
}
return configurationBodySetl;
}
-
private boolean isConfigExists(PolicyEntity policyEntity, Cell cell, boolean configExists) {
boolean configExistsl = configExists;
if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
- && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS))) {
+ && (policyEntity.getPolicyName().contains(config)
+ || policyEntity.getPolicyName().contains(DECISION_MS))) {
configExistsl = true;
}
return configExistsl;
}
-
private boolean isActionExists(PolicyEntity policyEntity, Cell cell, boolean actionExists) {
boolean actionExistsl = actionExists;
if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
@@ -706,17 +711,18 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
private StringBuilder addCellValue(PolicyEntity policyEntity, Cell cell, StringBuilder body) {
if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
- && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS))) {
+ && (policyEntity.getPolicyName().contains(config)
+ || policyEntity.getPolicyName().contains(DECISION_MS))) {
body.append(cell.getStringCellValue());
}
return body;
}
- private ActionBodyEntity setActionBodyObject(PolicyEntity policyEntity, ActionBodyEntity actionBodyEntity,
+ private ActionBodyEntity setActionBodyObject(PolicyEntity policyEntity, ActionBodyEntity actionBodyEntity,
Cell cell) {
if (configurationbody.equalsIgnoreCase(getCellHeaderName(cell))
- && (policyEntity.getPolicyName().contains(ACTION))) {
+ && (policyEntity.getPolicyName().contains(ACTION))) {
actionBodyEntity.setActionBody(cell.getStringCellValue());
}
return actionBodyEntity;
@@ -734,7 +740,8 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
private ConfigurationDataEntity populateConfigurationDataEntity(PolicyEntity policyEntity,
ConfigurationDataEntity configurationDataEntity, Cell cell) {
if (configurationName.equalsIgnoreCase(getCellHeaderName(cell))
- && (policyEntity.getPolicyName().contains(config) || policyEntity.getPolicyName().contains(DECISION_MS))) {
+ && (policyEntity.getPolicyName().contains(config)
+ || policyEntity.getPolicyName().contains(DECISION_MS))) {
configurationDataEntity.setConfigurationName(cell.getStringCellValue());
}
return configurationDataEntity;
@@ -751,9 +758,9 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
private void savePolicyEntiies(boolean finalColumn, boolean configurationBodySet,
ConfigurationDataEntity configurationDataEntity, PolicyEntity policyEntity, PolicyController controller,
List<String> roles, UserInfo userInfo, Set<String> scopes, String configName, String userId,
- boolean configExists, boolean actionExists, ActionBodyEntity actionBodyEntity, StringBuilder body) {
+ boolean configExists, boolean actionExists, ActionBodyEntity actionBodyEntity, StringBuilder body, boolean errorFlagSent) {
- if (finalColumn && configurationBodySet) {
+ if (finalColumn && configurationBodySet && !errorFlagSent) {
configurationDataEntity.setConfigBody(body.toString());
String scope = policyEntity.getScope().replace(".", File.separator);
String query = "FROM PolicyEntity where policyName = :policyName and scope = :policyScope";
@@ -771,7 +778,7 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
saveVersion(policyEntity, scope, userId); //
// Notify Other paps regarding Export Policy.
PolicyRestController restController = new PolicyRestController();
- restController.notifyOtherPAPSToUpdateConfigurations("exportPolicy", configName, null);
+ restController.notifyOtherPapsToUpdateConfigurations("exportPolicy", configName, null);
}
}
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java
index 707bbac09..ebd24dce3 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java
@@ -2,14 +2,14 @@
* ============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.
* 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,16 @@
package org.onap.policy.controller;
-
/*
- *
+ *
* */
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+
import java.io.File;
import java.io.IOException;
-import java.io.PrintWriter;
import java.util.List;
import javax.script.SimpleBindings;
@@ -46,87 +49,87 @@ import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.node.ArrayNode;
-
@Controller
@RequestMapping({"/"})
public class PolicyNotificationController extends RestrictedBaseController {
private static Logger logger = FlexLogger.getLogger(PolicyNotificationController.class);
- @Autowired
- CommonClassDao commonClassDao;
-
- @RequestMapping(value={"/watchPolicy"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
- public ModelAndView watchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{
- StringBuilder path = new StringBuilder();
- String responseValue = "";
- try {
- String userId = UserUtils.getUserSession(request).getOrgUserId();
- logger.info("userid info: " + userId);
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- String name = root.get("watchData").get("name").toString();
- JsonNode pathList = root.get("watchData").get("path");
- String finalName;
- if(pathList.isArray()){
- ArrayNode arrayNode = (ArrayNode) pathList;
- for (int i = 0; i < arrayNode.size(); i++) {
- JsonNode individualElement = arrayNode.get(i);
- if(i == 0){
- path.append(individualElement.toString().replace("\"", "").trim());
- }else{
- path.append(File.separator + individualElement.toString().replace("\"", "").trim());
- }
- }
- }
-
- if(pathList.size() > 0){
- finalName = path + File.separator + name.replace("\"", "").trim();
- }else{
- finalName = name.replace("\"", "").trim();
- }
- if(finalName.contains("\\")){
- finalName = finalName.replace("\\", "\\\\");
- }
- String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId";
- SimpleBindings params = new SimpleBindings();
- params.put("finalName", finalName);
- params.put("userId", userId);
- List<Object> watchList = commonClassDao.getDataByQuery(query, params);
- if(watchList.isEmpty()){
- if(finalName.contains("\\\\")){
- finalName = finalName.replace("\\\\", File.separator);
- }
- WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
- watch.setPolicyName(finalName);
- watch.setLoginIds(userId);
- commonClassDao.save(watch);
- responseValue = "You have Subscribed Successfully";
- }else{
- commonClassDao.delete(watchList.get(0));
- responseValue = "You have UnSubscribed Successfully";
- }
-
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
+ @Autowired
+ CommonClassDao commonClassDao;
+
+ /**
+ * watchPolicy.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @return ModelAndView
+ * @throws IOException IOException
+ */
+ @RequestMapping(value = {"/watchPolicy"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView watchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException {
+ StringBuilder path = new StringBuilder();
+ String responseValue = "";
+ try {
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ //
+ //
+ //
+ String userId = UserUtils.getUserSession(request).getOrgUserId();
+ logger.info("userid info: " + userId);
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ JsonNode root = mapper.readTree(request.getReader());
+ String name = root.get("watchData").get("name").toString();
+ JsonNode pathList = root.get("watchData").get("path");
+ String finalName;
+ if (pathList.isArray()) {
+ ArrayNode arrayNode = (ArrayNode) pathList;
+ for (int i = 0; i < arrayNode.size(); i++) {
+ JsonNode individualElement = arrayNode.get(i);
+ if (i == 0) {
+ path.append(individualElement.toString().replace("\"", "").trim());
+ } else {
+ path.append(File.separator + individualElement.toString().replace("\"", "").trim());
+ }
+ }
+ }
+
+ if (pathList.size() > 0) {
+ finalName = path + File.separator + name.replace("\"", "").trim();
+ } else {
+ finalName = name.replace("\"", "").trim();
+ }
+ if (finalName.contains("\\")) {
+ finalName = finalName.replace("\\", "\\\\");
+ }
+ String query = "from WatchPolicyNotificationTable where POLICYNAME = :finalName and LOGINIDS = :userId";
+ SimpleBindings params = new SimpleBindings();
+ params.put("finalName", finalName);
+ params.put("userId", userId);
+ List<Object> watchList = commonClassDao.getDataByQuery(query, params);
+ if (watchList.isEmpty()) {
+ if (finalName.contains("\\\\")) {
+ finalName = finalName.replace("\\\\", File.separator);
+ }
+ WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable();
+ watch.setPolicyName(finalName);
+ watch.setLoginIds(userId);
+ commonClassDao.save(watch);
+ responseValue = "You have Subscribed Successfully";
+ } else {
+ commonClassDao.delete(watchList.get(0));
+ responseValue = "You have UnSubscribed Successfully";
+ }
+
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
- PrintWriter out = response.getWriter();
- String responseString = mapper.writeValueAsString(responseValue);
- JSONObject j = new JSONObject("{watchData: " + responseString + "}");
- out.write(j.toString());
- return null;
- }catch(Exception e){
- response.setCharacterEncoding("UTF-8");
- request.setCharacterEncoding("UTF-8");
- logger.error("Error druing watchPolicy function " + e);
- PrintWriter out = response.getWriter();
- out.write(PolicyUtils.CATCH_EXCEPTION);
- }
- return null;
- }
+ response.getWriter().write(new JSONObject("{watchData: "
+ + mapper.writeValueAsString(responseValue) + "}").toString());
+ } catch (Exception e) {
+ logger.error("Error druing watchPolicy function " + e);
+ response.getWriter().write(PolicyUtils.CATCH_EXCEPTION);
+ }
+ return null;
+ }
}
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 b02da1996..c1c784083 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
@@ -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.
@@ -20,7 +20,12 @@
package org.onap.policy.controller;
-import java.io.PrintWriter;
+import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
+import com.fasterxml.jackson.annotation.PropertyAccessor;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -28,7 +33,8 @@ import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-
+import lombok.Getter;
+import lombok.Setter;
import org.json.JSONObject;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
@@ -36,6 +42,7 @@ import org.onap.policy.rest.dao.CommonClassDao;
import org.onap.policy.rest.jpa.PolicyEditorScopes;
import org.onap.policy.rest.jpa.PolicyRoles;
import org.onap.policy.rest.jpa.UserInfo;
+import org.onap.policy.utils.PolicyUtils;
import org.onap.portalsdk.core.controller.RestrictedBaseController;
import org.onap.portalsdk.core.web.support.JsonMessage;
import org.onap.portalsdk.core.web.support.UserUtils;
@@ -45,12 +52,6 @@ import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
-import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
-import com.fasterxml.jackson.annotation.PropertyAccessor;
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
@Controller
@RequestMapping("/")
public class PolicyRolesController extends RestrictedBaseController {
@@ -69,19 +70,19 @@ public class PolicyRolesController extends RestrictedBaseController {
/**
* Gets the policy roles entity data.
*
- * @param request the request
+ * @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)
+ @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());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
LOGGER.error("Exception Occured" + e);
}
@@ -90,12 +91,13 @@ public class PolicyRolesController extends RestrictedBaseController {
/**
* Save roles and Mechid entity data.
*
- * @param request the request
+ * @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 })
+ @RequestMapping(
+ value = {"/save_NonSuperRolesData"},
+ method = {org.springframework.web.bind.annotation.RequestMethod.POST})
public ModelAndView SaveRolesEntityData(HttpServletRequest request, HttpServletResponse response) {
try {
StringBuilder scopeName = new StringBuilder();
@@ -112,11 +114,11 @@ public class PolicyRolesController extends RestrictedBaseController {
}
}
LOGGER.info(
- "****************************************Logging UserID for Roles Function********************************************************");
+ "*************************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());
@@ -125,11 +127,11 @@ public class PolicyRolesController extends RestrictedBaseController {
if (adapter.getId() == 0 && "mechid".equals(adapter.getRole())) {
// Save new mechid scopes entity data.
LOGGER.info(
- "****************************************Logging UserID for New Mechid Function***************************************************");
+ "*********************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;
@@ -146,15 +148,11 @@ public class PolicyRolesController extends RestrictedBaseController {
} 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());
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ response.getWriter().write(new JSONObject("{rolesDatas: "
+ + mapper.writeValueAsString(commonClassDao.getUserRoles()) + "}").toString());
} catch (Exception e) {
LOGGER.error("Exception Occured" + e);
}
@@ -164,11 +162,13 @@ public class PolicyRolesController extends RestrictedBaseController {
/**
* Gets the policy scopes entity data.
*
- * @param request the request
+ * @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)
+ @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<>();
@@ -177,51 +177,18 @@ public class PolicyRolesController extends RestrictedBaseController {
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());
+ response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString());
} catch (Exception e) {
LOGGER.error("Exception Occured" + e);
}
}
}
+@Setter
+@Getter
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/controller/PolicyValidationController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java
index fca1096ff..05264c8b6 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java
@@ -2,14 +2,14 @@
* ============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.
* 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,9 +20,9 @@
package org.onap.policy.controller;
+import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
-import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -40,40 +40,42 @@ import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
@Controller
@RequestMapping("/")
public class PolicyValidationController extends RestrictedBaseController {
- private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidationController.class);
+ private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidationController.class);
+
+ /**
+ * validatePolicy.
+ *
+ * @param request HttpServletRequest
+ * @param response HttpServletResponse
+ * @return ModelAndView
+ * @throws IOException IOException
+ */
+ @RequestMapping(
+ value = {"/policyController/validate_policy.htm"},
+ method = {org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView validatePolicy(HttpServletRequest request, HttpServletResponse response) throws IOException {
+ try {
- @RequestMapping(value={"/policyController/validate_policy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
- public ModelAndView validatePolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{
- try{
-
- PolicyValidation validation = new PolicyValidation();
- PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper();
- StringBuilder responseString;
- ObjectMapper mapper = new ObjectMapper();
+ PolicyValidation validation = new PolicyValidation();
+ PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper();
+ StringBuilder responseString;
+ ObjectMapper mapper = new ObjectMapper();
- PolicyRestAdapter policyData = wrapper.populateRequestParameters(request);
- responseString = validation.validatePolicy(policyData);
-
- PrintWriter out = response.getWriter();
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(responseString.toString()));
- JSONObject j = new JSONObject(msg);
- out.write(j.toString());
+ PolicyRestAdapter policyData = wrapper.populateRequestParameters(request);
+ responseString = validation.validatePolicy(policyData);
- return null;
- }
- catch (Exception e){
- LOGGER.error("Exception Occured During Policy Validation" +e);
- response.setCharacterEncoding("UTF-8");
- request.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- out.write(PolicyUtils.CATCH_EXCEPTION);
- }
- return null;
- }
-} \ No newline at end of file
+ response.getWriter().write(new JSONObject(
+ new JsonMessage(mapper.writeValueAsString(responseString.toString()))).toString());
+ } catch (Exception e) {
+ LOGGER.error("Exception Occured During Policy Validation" + e);
+ response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING);
+ response.getWriter().write(PolicyUtils.CATCH_EXCEPTION);
+ }
+ return null;
+ }
+}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/dao/SystemLogDbDao.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/dao/SystemLogDbDao.java
index 9cc6314dd..8883475b8 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/dao/SystemLogDbDao.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/dao/SystemLogDbDao.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,14 +20,12 @@
package org.onap.policy.dao;
-
import java.util.List;
-import org.onap.policy.rest.jpa.SystemLogDB;
-
-
+import org.onap.policy.rest.jpa.SystemLogDb;
public abstract interface SystemLogDbDao {
- public abstract List<SystemLogDB> getLoggingData();
- public abstract List<SystemLogDB> getSystemAlertData();
+ public abstract List<SystemLogDb> getLoggingData();
+
+ public abstract List<SystemLogDb> getSystemAlertData();
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java
index 170c30838..a4b2c88d2 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java
@@ -2,14 +2,14 @@
* ============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.
* 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.
@@ -48,368 +48,358 @@ import org.springframework.stereotype.Service;
@Service("CommonClassDao")
@Primary
-public class CommonClassDaoImpl implements CommonClassDao{
+public class CommonClassDaoImpl implements CommonClassDao {
+
+ private static final Logger LOGGER = FlexLogger.getLogger(CommonClassDaoImpl.class);
+ private static SessionFactory sessionfactory;
- private static final Logger LOGGER = FlexLogger.getLogger(CommonClassDaoImpl.class);
- private static SessionFactory sessionfactory;
-
public static SessionFactory getSessionfactory() {
- return sessionfactory;
+ return sessionfactory;
}
public static void setSessionfactory(SessionFactory sessionfactory) {
- CommonClassDaoImpl.sessionfactory = sessionfactory;
+ CommonClassDaoImpl.sessionfactory = sessionfactory;
}
@Autowired
- private CommonClassDaoImpl(SessionFactory sessionfactory){
- CommonClassDaoImpl.sessionfactory = sessionfactory;
- }
-
- public CommonClassDaoImpl(){
- //Default Constructor
+ private CommonClassDaoImpl(SessionFactory sessionfactory) {
+ CommonClassDaoImpl.sessionfactory = sessionfactory;
}
-
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @Override
- public List<Object> getData(Class className) {
- Session session = sessionfactory.openSession();
- List<Object> data = null;
- 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{
- session.close();
- }catch(Exception e){
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e);
- }
- }
- return data;
- }
-
-
- @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(":")){
- String[] columns = columnName.split(":");
- String[] keys = key.split(":");
- for(int i=0; i < columns.length; i++){
- cr.add(Restrictions.eq(columns[i], keys[i]));
- }
- }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{
- session.close();
- }catch(Exception e1){
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
- }
- }
- return data;
- }
-
- @Override
- public void save(Object entity) {
- Session session = sessionfactory.openSession();
- Transaction tx = session.beginTransaction();
- try {
- session.persist(entity);
- tx.commit();
- }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);
- }
- }
-
- }
-
- @Override
- public void delete(Object entity) {
- Session session = sessionfactory.openSession();
- Transaction tx = session.beginTransaction();
- try {
- session.delete(entity);
- tx.commit();
- }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);
- }
- }
-
- }
-
-
- @Override
- public void update(Object entity) {
- Session session = sessionfactory.openSession();
- Transaction tx = session.beginTransaction();
- try {
- session.update(entity);
- tx.commit();
- }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);
- }
- }
-
- }
-
+ public CommonClassDaoImpl() {
+ // Default Constructor
+ }
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @Override
- public List<Object> checkDuplicateEntry(String value, String columnName, Class className) {
- Session session = sessionfactory.openSession();
- Transaction tx = session.beginTransaction();
- List<Object> data = null;
- String[] columnNames = null;
- if(columnName != null && columnName.contains(":")){
- columnNames = columnName.split(":");
- }
- String[] values = null;
- 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]));
- }
- }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{
- session.close();
- }catch(Exception e1){
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
- }
- }
- return data;
- }
+ @SuppressWarnings({"unchecked", "rawtypes"})
+ @Override
+ public List<Object> getData(Class className) {
+ Session session = sessionfactory.openSession();
+ List<Object> data = null;
+ 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 {
+ session.close();
+ } catch (Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e);
+ }
+ }
+ return data;
+ }
+ @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(":")) {
+ String[] columns = columnName.split(":");
+ String[] keys = key.split(":");
+ for (int i = 0; i < columns.length; i++) {
+ cr.add(Restrictions.eq(columns[i], keys[i]));
+ }
+ } 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 {
+ session.close();
+ } catch (Exception e1) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1);
+ }
+ }
+ return data;
+ }
- @SuppressWarnings("unchecked")
- @Override
- public List<PolicyRoles> getUserRoles() {
- Session session = sessionfactory.openSession();
- Transaction tx = session.beginTransaction();
- List<PolicyRoles> rolesData = null;
- try {
- Criteria cr = session.createCriteria(PolicyRoles.class);
- Disjunction disjunction = Restrictions.disjunction();
- Conjunction conjunction1 = Restrictions.conjunction();
- conjunction1.add(Restrictions.eq("role", "admin"));
- Conjunction conjunction2 = Restrictions.conjunction();
- conjunction2.add(Restrictions.eq("role", "editor"));
- Conjunction conjunction3 = Restrictions.conjunction();
- conjunction3.add(Restrictions.eq("role", "guest"));
- disjunction.add(conjunction1);
- disjunction.add(conjunction2);
- disjunction.add(conjunction3);
- rolesData = cr.add(disjunction).list();
- tx.commit();
- } catch (Exception e) {
- 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);
- }
- }
- return rolesData;
- }
+ @Override
+ public void save(Object entity) {
+ Session session = sessionfactory.openSession();
+ Transaction tx = session.beginTransaction();
+ try {
+ session.persist(entity);
+ tx.commit();
+ } 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);
+ }
+ }
+ }
- @Override
- public List<Object> checkExistingGroupListforUpdate(String arg0, String arg1) {
- return Collections.emptyList();
- }
+ @Override
+ public void delete(Object entity) {
+ Session session = sessionfactory.openSession();
+ Transaction tx = session.beginTransaction();
+ try {
+ session.delete(entity);
+ tx.commit();
+ } 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);
+ }
+ }
+ }
- @Override
- public void deleteAll() {}
+ @Override
+ public void update(Object entity) {
+ Session session = sessionfactory.openSession();
+ Transaction tx = session.beginTransaction();
+ try {
+ session.update(entity);
+ tx.commit();
+ } 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);
+ }
+ }
-
- @SuppressWarnings("unchecked")
- @Override
- public List<Object> getDataByQuery(String query, SimpleBindings params) {
- Session session = sessionfactory.openSession();
- Transaction tx = session.beginTransaction();
- List<Object> data = null;
- try {
- Query hbquery = session.createQuery(query);
- for (Map.Entry<String, Object> paramPair : params.entrySet()) {
- if(paramPair.getValue() instanceof java.lang.Long){
- hbquery.setLong(paramPair.getKey(), (long) paramPair.getValue());
- }
- 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);
- throw e;
- }finally{
- try{
- session.close();
- }catch(HibernateException e1){
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
- }
- }
- return data;
- }
+ }
+ @SuppressWarnings({"unchecked", "rawtypes"})
+ @Override
+ public List<Object> checkDuplicateEntry(String value, String columnName, Class className) {
+ Session session = sessionfactory.openSession();
+ Transaction tx = session.beginTransaction();
+ List<Object> data = null;
+ String[] columnNames = null;
+ if (columnName != null && columnName.contains(":")) {
+ columnNames = columnName.split(":");
+ }
+ String[] values = null;
+ 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]));
+ }
+ } 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 {
+ session.close();
+ } catch (Exception e1) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1);
+ }
+ }
+ return data;
+ }
- @SuppressWarnings("rawtypes")
- @Override
- public Object getEntityItem(Class className, String columnName, String key) {
- Session session = sessionfactory.openSession();
- Transaction tx = session.beginTransaction();
- Object data = null;
- try {
- Criteria cr = session.createCriteria(className);
- if(columnName.contains(":") && key.contains(":")){
- String[] columns = columnName.split(":");
- String[] keys = key.split(":");
- for(int i=0; i < columns.length; i++){
- cr.add(Restrictions.eq(columns[i], keys[i]));
- }
- }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{
- session.close();
- }catch(Exception e1){
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
- }
- }
- return data;
- }
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<PolicyRoles> getUserRoles() {
+ Session session = sessionfactory.openSession();
+ Transaction tx = session.beginTransaction();
+ List<PolicyRoles> rolesData = null;
+ try {
+ final Criteria cr = session.createCriteria(PolicyRoles.class);
+ final Disjunction disjunction = Restrictions.disjunction();
+ Conjunction conjunction1 = Restrictions.conjunction();
+ conjunction1.add(Restrictions.eq("role", "admin"));
+ Conjunction conjunction2 = Restrictions.conjunction();
+ conjunction2.add(Restrictions.eq("role", "editor"));
+ Conjunction conjunction3 = Restrictions.conjunction();
+ conjunction3.add(Restrictions.eq("role", "guest"));
+ disjunction.add(conjunction1);
+ disjunction.add(conjunction2);
+ disjunction.add(conjunction3);
+ rolesData = cr.add(disjunction).list();
+ tx.commit();
+ } catch (Exception e) {
+ 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);
+ }
+ }
+ return rolesData;
+ }
+ @Override
+ public List<Object> checkExistingGroupListforUpdate(String arg0, String arg1) {
+ return Collections.emptyList();
+ }
- @Override
- public void updateClAlarms(String arg0, String arg1) {}
+ @Override
+ public void deleteAll() {
+ }
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<Object> getDataByQuery(String query, SimpleBindings params) {
+ Session session = sessionfactory.openSession();
+ Transaction tx = session.beginTransaction();
+ List<Object> data = null;
+ try {
+ Query hbquery = session.createQuery(query);
+ for (Map.Entry<String, Object> paramPair : params.entrySet()) {
+ if (paramPair.getValue() instanceof java.lang.Long) {
+ hbquery.setLong(paramPair.getKey(), (long) paramPair.getValue());
+ } 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);
+ throw e;
+ } finally {
+ try {
+ session.close();
+ } catch (HibernateException e1) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1);
+ }
+ }
+ return data;
+ }
- @Override
- public void updateClYaml(String arg0, String arg1) {}
+ @SuppressWarnings("rawtypes")
+ @Override
+ public Object getEntityItem(Class className, String columnName, String key) {
+ Session session = sessionfactory.openSession();
+ Transaction tx = session.beginTransaction();
+ Object data = null;
+ try {
+ Criteria cr = session.createCriteria(className);
+ if (columnName.contains(":") && key.contains(":")) {
+ String[] columns = columnName.split(":");
+ String[] keys = key.split(":");
+ for (int i = 0; i < columns.length; i++) {
+ cr.add(Restrictions.eq(columns[i], keys[i]));
+ }
+ } 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 {
+ session.close();
+ } catch (Exception e1) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1);
+ }
+ }
+ return data;
+ }
+ @Override
+ public void updateClAlarms(String arg0, String arg1) {
+ // why is there no code here?
+ }
- @Override
- public void updateQuery(String query) {
- Session session = sessionfactory.openSession();
- Transaction tx = session.beginTransaction();
- try {
- Query hbquery = session.createQuery(query);
- hbquery.executeUpdate();
- tx.commit();
- } catch (Exception e) {
- 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);
- }
- }
-
- }
+ @Override
+ public void updateClYaml(String arg0, String arg1) {
+ // why is there no code here?
+ }
+ @Override
+ public void updateQuery(String query) {
+ Session session = sessionfactory.openSession();
+ Transaction tx = session.beginTransaction();
+ try {
+ Query hbquery = session.createQuery(query);
+ hbquery.executeUpdate();
+ tx.commit();
+ } catch (Exception e) {
+ 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);
+ }
+ }
- @SuppressWarnings({ "rawtypes", "unchecked" })
- @Override
- public List<String> getDataByColumn(Class className, String columnName) {
- Session session = sessionfactory.openSession();
- List<String> data = null;
- 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{
- session.close();
- }catch(Exception e){
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e);
- }
- }
- return data;
- }
+ }
+ @SuppressWarnings({"rawtypes", "unchecked"})
+ @Override
+ public List<String> getDataByColumn(Class className, String columnName) {
+ Session session = sessionfactory.openSession();
+ List<String> data = null;
+ 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 {
+ session.close();
+ } catch (Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e);
+ }
+ }
+ return data;
+ }
- @SuppressWarnings({ "rawtypes", "unchecked" })
- @Override
- public List<Object> getMultipleDataOnAddingConjunction(Class className, String columnName, List<String> data) {
- Session session = sessionfactory.openSession();
- Transaction tx = session.beginTransaction();
- List<Object> entityData = null;
- try {
- Criteria cr = session.createCriteria(className);
- Disjunction disjunction = Restrictions.disjunction();
- List<Conjunction> conjunctionList = new ArrayList<>();
- String[] columNames = columnName.split(":");
- for(int i =0; i < data.size(); i++){
- String[] entiySplit = data.get(i).split(":");
- Conjunction conjunction = Restrictions.conjunction();
- conjunction.add(Restrictions.eq(columNames[0], entiySplit[0]));
- conjunction.add(Restrictions.eq(columNames[1], entiySplit[1]));
- conjunctionList.add(conjunction);
- }
- for(int j =0 ; j < conjunctionList.size(); j++){
- disjunction.add(conjunctionList.get(j));
- }
- entityData = cr.add(disjunction).list();
- tx.commit();
- } catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table" +className +e);
- }finally{
- try{
- session.close();
- }catch(Exception e1){
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
- }
- }
- return entityData;
- }
+ @SuppressWarnings({"rawtypes", "unchecked"})
+ @Override
+ public List<Object> getMultipleDataOnAddingConjunction(Class className, String columnName, List<String> data) {
+ Session session = sessionfactory.openSession();
+ Transaction tx = session.beginTransaction();
+ List<Object> entityData = null;
+ try {
+ Criteria cr = session.createCriteria(className);
+ Disjunction disjunction = Restrictions.disjunction();
+ List<Conjunction> conjunctionList = new ArrayList<>();
+ String[] columNames = columnName.split(":");
+ for (int i = 0; i < data.size(); i++) {
+ String[] entiySplit = data.get(i).split(":");
+ Conjunction conjunction = Restrictions.conjunction();
+ conjunction.add(Restrictions.eq(columNames[0], entiySplit[0]));
+ conjunction.add(Restrictions.eq(columNames[1], entiySplit[1]));
+ conjunctionList.add(conjunction);
+ }
+ for (int j = 0; j < conjunctionList.size(); j++) {
+ disjunction.add(conjunctionList.get(j));
+ }
+ entityData = cr.add(disjunction).list();
+ tx.commit();
+ } catch (Exception e) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table" + className + e);
+ } finally {
+ try {
+ session.close();
+ } catch (Exception e1) {
+ LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1);
+ }
+ }
+ return entityData;
+ }
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/SystemLogDbDaoImpl.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/SystemLogDbDaoImpl.java
index 1727f47c0..46aed213f 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/SystemLogDbDaoImpl.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/SystemLogDbDaoImpl.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,85 +20,83 @@
package org.onap.policy.daoImp;
-
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
-import org.springframework.stereotype.Service;
-
-import org.onap.policy.xacml.api.XACMLErrorConstants;
-
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
+import org.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.conf.HibernateSession;
import org.onap.policy.controller.PolicyController;
import org.onap.policy.dao.SystemLogDbDao;
-import org.onap.policy.rest.jpa.SystemLogDB;
-import org.onap.policy.common.logging.flexlogger.FlexLogger;
-import org.onap.policy.common.logging.flexlogger.Logger;
-
+import org.onap.policy.rest.jpa.SystemLogDb;
+import org.onap.policy.xacml.api.XACMLErrorConstants;
+import org.springframework.stereotype.Service;
@Service("SystemLogDbDao")
public class SystemLogDbDaoImpl implements SystemLogDbDao {
- private static final Logger logger = FlexLogger.getLogger(SystemLogDbDaoImpl.class);
-
- @SuppressWarnings("unchecked")
- @Override
- public List<SystemLogDB> getLoggingData() {
- Session session = HibernateSession.getSession();
- Transaction tx = session.beginTransaction();
- List<SystemLogDB> system = null;
+ private static final Logger logger = FlexLogger.getLogger(SystemLogDbDaoImpl.class);
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<SystemLogDb> getLoggingData() {
+ Session session = HibernateSession.getSession();
+ Transaction tx = session.beginTransaction();
+ List<SystemLogDb> system = null;
try {
- String sqlWhere = null;
- if(PolicyController.isjUnit()){
- sqlWhere = "";
- }else{
- sqlWhere = "date > DATE_SUB(curdate(), INTERVAL 5 DAY) ORDER BY date DESC limit "+PolicyController.getLogTableLimit()+"";
- }
- Criteria cr = session.createCriteria(SystemLogDB.class);
- cr.add(Restrictions.sqlRestriction(sqlWhere));
+ String sqlWhere = null;
+ if (PolicyController.isjUnit()) {
+ sqlWhere = "";
+ } else {
+ sqlWhere = "date > DATE_SUB(curdate(), INTERVAL 5 DAY) ORDER BY date DESC limit "
+ + PolicyController.getLogTableLimit() + "";
+ }
+ Criteria cr = session.createCriteria(SystemLogDb.class);
+ cr.add(Restrictions.sqlRestriction(sqlWhere));
system = cr.list();
- tx.commit();
- } catch (Exception e) {
- logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying SystemLogDB Table"+e);
- }finally{
- try{
- session.close();
- }catch(Exception e1){
- logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
- }
- }
- return system;
- }
+ tx.commit();
+ } catch (Exception e) {
+ logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying SystemLogDb Table" + e);
+ } finally {
+ try {
+ session.close();
+ } catch (Exception e1) {
+ logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1);
+ }
+ }
+ return system;
+ }
- @SuppressWarnings("unchecked")
- @Override
- public List<SystemLogDB> getSystemAlertData() {
- Session session = HibernateSession.getSession();
- Transaction tx = session.beginTransaction();
- List<SystemLogDB> system = null;
+ @SuppressWarnings("unchecked")
+ @Override
+ public List<SystemLogDb> getSystemAlertData() {
+ Session session = HibernateSession.getSession();
+ Transaction tx = session.beginTransaction();
+ List<SystemLogDb> system = null;
try {
- String sqlWhere = null;
- if(PolicyController.isjUnit()){
- sqlWhere = "";
- }else{
- sqlWhere = "date > DATE_SUB(curdate(), INTERVAL 5 DAY) and logtype = 'error' ORDER BY date DESC limit "+PolicyController.getSystemAlertTableLimit()+"";
- }
- Criteria cr = session.createCriteria(SystemLogDB.class);
- cr.add(Restrictions.sqlRestriction(sqlWhere));
+ String sqlWhere = null;
+ if (PolicyController.isjUnit()) {
+ sqlWhere = "";
+ } else {
+ sqlWhere = "date > DATE_SUB(curdate(), INTERVAL 5 DAY) and logtype = 'error' ORDER BY date DESC limit "
+ + PolicyController.getSystemAlertTableLimit() + "";
+ }
+ Criteria cr = session.createCriteria(SystemLogDb.class);
+ cr.add(Restrictions.sqlRestriction(sqlWhere));
system = cr.list();
- tx.commit();
- } catch (Exception e) {
- logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying SystemLogDB Table"+e);
- }finally{
- try{
- session.close();
- }catch(Exception e1){
- logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1);
- }
- }
- return system;
- }
+ tx.commit();
+ } catch (Exception e) {
+ logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying SystemLogDb Table" + e);
+ } finally {
+ try {
+ session.close();
+ } catch (Exception e1) {
+ logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1);
+ }
+ }
+ return system;
+ }
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java
index e6c375808..6c4fd7e91 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java
@@ -20,8 +20,8 @@
package org.onap.policy.model;
-
import com.att.research.xacml.api.pap.PAPException;
+
import java.awt.Checkbox;
import java.util.ArrayList;
import java.util.Collection;
@@ -29,6 +29,7 @@ import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
+
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.rest.util.PolicyContainer;
@@ -112,6 +113,9 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
return itemId instanceof OnapPDPGroup;
}
+ /**
+ * refreshGroups.
+ */
public synchronized void refreshGroups() {
synchronized (this.groups) {
this.groups.clear();
@@ -133,6 +137,11 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
return Collections.unmodifiableList(this.groups);
}
+ /**
+ * makeDefault.
+ *
+ * @param group OnapPDPGroup
+ */
public void makeDefault(OnapPDPGroup group) {
try {
this.papEngine.setDefaultGroup(group);
@@ -143,6 +152,13 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
return;
}
+ /**
+ * removeGroup.
+ *
+ * @param group OnapPDPGroup
+ * @param newGroup OnapPDPGroup
+ * @throws PAPException PAPException
+ */
public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup) throws PAPException {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("removeGroup: " + group + " new group for PDPs: " + newGroup);
@@ -158,6 +174,13 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
}
}
+ /**
+ * removePDP.
+ *
+ * @param pdp OnapPDP
+ * @param group OnapPDPGroup
+ * @throws PAPException PAPException
+ */
public void removePDP(OnapPDP pdp, OnapPDPGroup group) throws PAPException {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("removePDP: " + pdp + " from group: " + group);
@@ -170,6 +193,11 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
}
}
+ /**
+ * updatePDP.
+ *
+ * @param pdp OnapPDP
+ */
public void updatePDP(OnapPDP pdp) {
try {
papEngine.updatePDP(pdp);
@@ -178,6 +206,11 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
}
}
+ /**
+ * updateGroup.
+ *
+ * @param group OnapPDPGroup
+ */
public void updateGroup(OnapPDPGroup group) {
try {
papEngine.updateGroup(group);
@@ -216,6 +249,17 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
}
@Override
+ public List<?> getItemIds(int startIndex, int numberOfItems) {
+ synchronized (this.groups) {
+ int endIndex = startIndex + numberOfItems;
+ if (endIndex > this.groups.size()) {
+ endIndex = this.groups.size() - 1;
+ }
+ return this.groups.subList(startIndex, endIndex);
+ }
+ }
+
+ @Override
public Class<?> getType(Object propertyId) {
if (propertyId.equals(PROPERTY_ID)) {
return String.class;
@@ -268,6 +312,13 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
throw new UnsupportedOperationException("PDP Container cannot add a given item.");
}
+ /**
+ * addNewGroup.
+ *
+ * @param name String
+ * @param description String
+ * @throws PAPException PAPException
+ */
public void addNewGroup(String name, String description) throws PAPException {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("addNewGroup " + name + " " + description);
@@ -275,6 +326,16 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
this.papEngine.newGroup(name, description);
}
+ /**
+ * addNewPDP.
+ *
+ * @param id String
+ * @param group OnapPDPGroup
+ * @param name String
+ * @param description String
+ * @param jmxport int
+ * @throws PAPException PAPException
+ */
public void addNewPDP(String id, OnapPDPGroup group, String name, String description, int jmxport)
throws PAPException {
if (LOGGER.isTraceEnabled()) {
@@ -283,6 +344,12 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
this.papEngine.newPDP(id, group, name, description, jmxport);
}
+ /**
+ * movePDP.
+ *
+ * @param pdp OnapPDP
+ * @param group OnapPDPGroup
+ */
public void movePDP(OnapPDP pdp, OnapPDPGroup group) {
try {
this.papEngine.movePDP(pdp, group);
@@ -427,17 +494,6 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier
}
@Override
- public List<?> getItemIds(int startIndex, int numberOfItems) {
- synchronized (this.groups) {
- int endIndex = startIndex + numberOfItems;
- if (endIndex > this.groups.size()) {
- endIndex = this.groups.size() - 1;
- }
- return this.groups.subList(startIndex, endIndex);
- }
- }
-
- @Override
public Object addItemAt(int index) {
throw new UnsupportedOperationException("Cannot addItemAt");
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/model/Roles.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/Roles.java
index 2f051f7b4..baaecaee6 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/model/Roles.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/Roles.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,6 +20,7 @@
package org.onap.policy.model;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.io.Serializable;
@@ -31,69 +32,69 @@ import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-
@Entity
-@Table(name="Roles")
-@NamedQuery(name="Roles.findAll", query="SELECT r FROM Roles r ")
-@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
-public class Roles implements Serializable{
- private static final long serialVersionUID = 1L;
-
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
-
- @Column(name="id")
- private int id;
-
- @Column(name="loginId")
- private String loginId;
-
- private String name;
- private String scope;
- private String role;
-
- public Roles(){
- // Empty constructor
- }
-
- public int getId() {
- return this.id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
-
- public String getLoginId() {
- return this.loginId;
- }
-
- public void setLoginId(String loginId) {
- this.loginId = loginId;
-
- }
- public String getScope() {
- return this.scope;
- }
-
- public void setScope(String scope) {
- this.scope = scope;
-
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
- public String getRole() {
- return this.role;
- }
-
- public void setRole(String role) {
- this.role = role;
- }
+@Table(name = "Roles")
+@NamedQuery(name = "Roles.findAll", query = "SELECT r FROM Roles r ")
+@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
+public class Roles implements Serializable {
+ private static final long serialVersionUID = 1L;
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+
+ @Column(name = "id")
+ private int id;
+
+ @Column(name = "loginId")
+ private String loginId;
+
+ private String name;
+ private String scope;
+ private String role;
+
+ public Roles() {
+ // Empty constructor
+ }
+
+ public int getId() {
+ return this.id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public String getLoginId() {
+ return this.loginId;
+ }
+
+ public void setLoginId(String loginId) {
+ this.loginId = loginId;
+
+ }
+
+ public String getScope() {
+ return this.scope;
+ }
+
+ public void setScope(String scope) {
+ this.scope = scope;
+
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getRole() {
+ return this.role;
+ }
+
+ public void setRole(String role) {
+ this.role = role;
+ }
}
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 40c839676..f9f93c0ff 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
@@ -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.
@@ -17,6 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.utils;
import java.util.ArrayList;
@@ -35,18 +36,18 @@ public final class UserUtils {
}
public static class Pair<T, U> {
- public final T t;
- public final U u;
+ public final T first;
+ public final U second;
- public Pair(T t, U u) {
- this.t = t;
- this.u = u;
+ public Pair(T first, U second) {
+ this.first = first;
+ this.second = second;
}
}
/**
* Check Role and its Scopes.
- *
+ *
* @param userRoles list of UserRoles.
* @return return role and scope from UserRole Object.
*/
@@ -75,7 +76,7 @@ public final class UserUtils {
/**
* Get Role by Scope based on UserRole Object.
- *
+ *
* @param userRoles list of UserRoles.
* @return return the map<scope, role>.
*/
@@ -94,8 +95,8 @@ public final class UserUtils {
/**
* Read non super role scopes and add to map.
- *
- * @param userRole Role Object.
+ *
+ * @param userRole Role Object.
* @param rolesList roleList Object.
* @return return the map<scope, role>.
*/
@@ -115,7 +116,7 @@ public final class UserUtils {
/**
* Trim Scope Value.
- *
+ *
* @param scope string scope name.
* @return trim scope.
*/
diff --git a/POLICY-SDK-APP/src/main/webapp/WEB-INF/conf/system.properties b/POLICY-SDK-APP/src/main/webapp/WEB-INF/conf/system.properties
index a12eac3ce..4831802ca 100644
--- a/POLICY-SDK-APP/src/main/webapp/WEB-INF/conf/system.properties
+++ b/POLICY-SDK-APP/src/main/webapp/WEB-INF/conf/system.properties
@@ -44,9 +44,9 @@ decryption_key = AGLDdG4D04BKm2IxIWEr8o==
##########################################################################
#Mysql
db.driver = org.mariadb.jdbc.Driver
-db.connectionURL = jdbc:mariadb://localhost:3306/onapsdk1707
+db.connectionURL = jdbc:mariadb://localhost:3306/onap_sdk
db.userName = root
-db.password =
+db.password =
db.hib.dialect = org.hibernate.dialect.MySQLDialect
db.min_pool_size = 5
db.max_pool_size = 10
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/dist/js/bootstrap-modalmanager.min.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/dist/js/bootstrap-modalmanager.min.js
new file mode 100644
index 000000000..80e9597e7
--- /dev/null
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/CSS/bootstrap/dist/js/bootstrap-modalmanager.min.js
@@ -0,0 +1,341 @@
+/* ===========================================================
+ * bootstrap-modalmanager.min.js v2.2.5
+ * ===========================================================
+ * Copyright 2012 Jordan Schroter
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ========================================================== */
+
+!function(c) {
+ var a = function(f, e) {
+ this.init(f, e)
+ };
+ a.prototype = {
+ constructor : a,
+ init : function(f, e) {
+ this.$element = c(f);
+ this.options = c.extend({}, c.fn.modalmanager.defaults,
+ this.$element.data(), typeof e == "object" && e);
+ this.stack = [];
+ this.backdropCount = 0;
+ if (this.options.resize) {
+ var h, g = this;
+ c(window).on("resize.modal", function() {
+ h && clearTimeout(h);
+ h = setTimeout(function() {
+ for (var j = 0; j < g.stack.length; j++) {
+ g.stack[j].isShown && g.stack[j].layout()
+ }
+ }, 10)
+ })
+ }
+ },
+ createModal : function(f, e) {
+ c(f).modal(c.extend({
+ manager : this
+ }, e))
+ },
+ appendModal : function(f) {
+ this.stack.push(f);
+ var e = this;
+ f.$element.on("show.modalmanager",
+ b(function(h) {
+ var g = function() {
+ f.isShown = true;
+ var i = c.support.transition
+ && f.$element.hasClass("fade");
+ e.$element.toggleClass("modal-open",
+ e.hasOpenModal()).toggleClass(
+ "page-overflow",
+ c(window).height() < e.$element.height());
+ f.$parent = f.$element.parent();
+ f.$container = e.createContainer(f);
+ f.$element.appendTo(f.$container);
+ e.backdrop(f, function() {
+ f.$element.show();
+ if (i) {
+ f.$element[0].offsetWidth
+ }
+ f.layout();
+ f.$element.addClass("in").attr("aria-hidden",
+ false);
+ var j = function() {
+ e.setFocus();
+ f.$element.trigger("shown")
+ };
+ i ? f.$element.one(c.support.transition.end, j)
+ : j()
+ })
+ };
+ f.options.replace ? e.replace(g) : g()
+ }));
+ f.$element
+ .on(
+ "hidden.modalmanager",
+ b(function(g) {
+ e.backdrop(f);
+ if (!f.$element.parent().length) {
+ e.destroyModal(f)
+ } else {
+ if (f.$backdrop) {
+ var h = c.support.transition
+ && f.$element.hasClass("fade");
+ if (h) {
+ f.$element[0].offsetWidth
+ }
+ c.support.transition
+ && f.$element.hasClass("fade") ? f.$backdrop
+ .one(c.support.transition.end,
+ function() {
+ f.destroy()
+ })
+ : f.destroy()
+ } else {
+ f.destroy()
+ }
+ }
+ }));
+ f.$element.on("destroyed.modalmanager", b(function(g) {
+ e.destroyModal(f)
+ }))
+ },
+ getOpenModals : function() {
+ var f = [];
+ for (var e = 0; e < this.stack.length; e++) {
+ if (this.stack[e].isShown) {
+ f.push(this.stack[e])
+ }
+ }
+ return f
+ },
+ hasOpenModal : function() {
+ return this.getOpenModals().length > 0
+ },
+ setFocus : function() {
+ var f;
+ for (var e = 0; e < this.stack.length; e++) {
+ if (this.stack[e].isShown) {
+ f = this.stack[e]
+ }
+ }
+ if (!f) {
+ return
+ }
+ f.focus()
+ },
+ destroyModal : function(f) {
+ f.$element.off(".modalmanager");
+ if (f.$backdrop) {
+ this.removeBackdrop(f)
+ }
+ this.stack.splice(this.getIndexOfModal(f), 1);
+ var e = this.hasOpenModal();
+ this.$element.toggleClass("modal-open", e);
+ if (!e) {
+ this.$element.removeClass("page-overflow")
+ }
+ this.removeContainer(f);
+ this.setFocus()
+ },
+ getModalAt : function(e) {
+ return this.stack[e]
+ },
+ getIndexOfModal : function(f) {
+ for (var e = 0; e < this.stack.length; e++) {
+ if (f === this.stack[e]) {
+ return e
+ }
+ }
+ },
+ replace : function(g) {
+ var f;
+ for (var e = 0; e < this.stack.length; e++) {
+ if (this.stack[e].isShown) {
+ f = this.stack[e]
+ }
+ }
+ if (f) {
+ this.$backdropHandle = f.$backdrop;
+ f.$backdrop = null;
+ g && f.$element.one("hidden", b(c.proxy(g, this)));
+ f.hide()
+ } else {
+ if (g) {
+ g()
+ }
+ }
+ },
+ removeBackdrop : function(e) {
+ e.$backdrop.remove();
+ e.$backdrop = null
+ },
+ createBackdrop : function(g, f) {
+ var e;
+ if (!this.$backdropHandle) {
+ e = c(f).addClass(g).appendTo(this.$element)
+ } else {
+ e = this.$backdropHandle;
+ e.off(".modalmanager");
+ this.$backdropHandle = null;
+ this.isLoading && this.removeSpinner()
+ }
+ return e
+ },
+ removeContainer : function(e) {
+ e.$container.remove();
+ e.$container = null
+ },
+ createContainer : function(e) {
+ var f;
+ f = c('<div class="modal-scrollable">').css("z-index",
+ d("modal", this.getOpenModals().length)).appendTo(
+ this.$element);
+ if (e && e.options.backdrop != "static") {
+ f.on("click.modal", b(function(g) {
+ e.hide()
+ }))
+ } else {
+ if (e) {
+ f.on("click.modal", b(function(g) {
+ e.attention()
+ }))
+ }
+ }
+ return f
+ },
+ backdrop : function(h, j) {
+ var f = h.$element.hasClass("fade") ? "fade" : "", i = h.options.backdrop
+ && this.backdropCount < this.options.backdropLimit;
+ if (h.isShown && i) {
+ var e = c.support.transition && f && !this.$backdropHandle;
+ h.$backdrop = this
+ .createBackdrop(f, h.options.backdropTemplate);
+ h.$backdrop.css("z-index", d("backdrop",
+ this.getOpenModals().length));
+ if (e) {
+ h.$backdrop[0].offsetWidth
+ }
+ h.$backdrop.addClass("in");
+ this.backdropCount += 1;
+ e ? h.$backdrop.one(c.support.transition.end, j) : j()
+ } else {
+ if (!h.isShown && h.$backdrop) {
+ h.$backdrop.removeClass("in");
+ this.backdropCount -= 1;
+ var g = this;
+ c.support.transition && h.$element.hasClass("fade") ? h.$backdrop
+ .one(c.support.transition.end, function() {
+ g.removeBackdrop(h)
+ })
+ : g.removeBackdrop(h)
+ } else {
+ if (j) {
+ j()
+ }
+ }
+ }
+ },
+ removeSpinner : function() {
+ this.$spinner && this.$spinner.remove();
+ this.$spinner = null;
+ this.isLoading = false
+ },
+ removeLoading : function() {
+ this.$backdropHandle && this.$backdropHandle.remove();
+ this.$backdropHandle = null;
+ this.removeSpinner()
+ },
+ loading : function(h) {
+ h = h || function() {
+ };
+ this.$element.toggleClass("modal-open",
+ !this.isLoading || this.hasOpenModal()).toggleClass(
+ "page-overflow",
+ c(window).height() < this.$element.height());
+ if (!this.isLoading) {
+ this.$backdropHandle = this.createBackdrop("fade",
+ this.options.backdropTemplate);
+ this.$backdropHandle[0].offsetWidth;
+ var e = this.getOpenModals();
+ this.$backdropHandle
+ .css("z-index", d("backdrop", e.length + 1)).addClass(
+ "in");
+ var g = c(this.options.spinner).css("z-index",
+ d("modal", e.length + 1)).appendTo(this.$element)
+ .addClass("in");
+ this.$spinner = c(this.createContainer()).append(g).on(
+ "click.modalmanager", c.proxy(this.loading, this));
+ this.isLoading = true;
+ c.support.transition ? this.$backdropHandle.one(
+ c.support.transition.end, h) : h()
+ } else {
+ if (this.isLoading && this.$backdropHandle) {
+ this.$backdropHandle.removeClass("in");
+ var f = this;
+ c.support.transition ? this.$backdropHandle.one(
+ c.support.transition.end, function() {
+ f.removeLoading()
+ }) : f.removeLoading()
+ } else {
+ if (h) {
+ h(this.isLoading)
+ }
+ }
+ }
+ }
+ };
+ var d = (function() {
+ var f, e = {};
+ return function(g, j) {
+ if (typeof f === "undefined") {
+ var i = c('<div class="modal hide" />').appendTo("body"), h = c(
+ '<div class="modal-backdrop hide" />').appendTo("body");
+ e.modal = +i.css("z-index");
+ e.backdrop = +h.css("z-index");
+ f = e.modal - e.backdrop;
+ i.remove();
+ h.remove();
+ h = i = null
+ }
+ return e[g] + (f * j)
+ }
+ }());
+ function b(e) {
+ return function(f) {
+ if (f && this === f.target) {
+ return e.apply(this, arguments)
+ }
+ }
+ }
+ c.fn.modalmanager = function(f, e) {
+ return this.each(function() {
+ var h = c(this), g = h.data("modalmanager");
+ if (!g) {
+ h.data("modalmanager", (g = new a(this, f)))
+ }
+ if (typeof f === "string") {
+ g[f].apply(g, [].concat(e))
+ }
+ })
+ };
+ c.fn.modalmanager.defaults = {
+ backdropLimit : 999,
+ resize : true,
+ spinner : '<div class="loading-spinner fade" style="width: 200px; margin-left: -100px;"><div class="progress progress-striped active"><div class="bar" style="width: 100%;"></div></div></div>',
+ backdropTemplate : '<div class="modal-backdrop" />'
+ };
+ c.fn.modalmanager.Constructor = a;
+ c(function() {
+ c(document).off("show.bs.modal").off("hidden.bs.modal")
+ })
+}(jQuery); \ No newline at end of file
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/AutoPushController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/AutoPushController.js
index 4832da109..264ff567e 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/AutoPushController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/AutoPushController.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.
@@ -17,7 +17,8 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller('policyPushController', function ($scope, PolicyAppService, modalService, $modal, Notification,$filter){
+app.controller('policyPushController',
+ function ($scope, PolicyAppService, modalService, $modal, Notification,$filter){
$( "#dialog" ).hide();
$scope.isDisabled = true;
@@ -32,30 +33,24 @@ app.controller('policyPushController', function ($scope, PolicyAppService, modal
}else{
$scope.isDisabled = false;
}
- console.log($scope.data);
- },function(error){
- console.log("failed");
});
$scope.pdpdata;
PolicyAppService.getData('get_PDPGroupData').then(function (data) {
var j = data;
$scope.pdpdata = JSON.parse(j.data);
- console.log($scope.pdpdata);
$scope.pushTabPDPGrid.data = $scope.pdpdata;
- }, function (error) {
- console.log("failed");
});
$scope.getPDPData = function(){
- $scope.pushTabPDPGrid.data = $scope.pdpdata;
+ $scope.pushTabPDPGrid.data = $scope.pdpdata;
};
$scope.filterPdpGroup;
$scope.filterPDPGroupData = function() {
$scope.pushTabPDPGrid.data = $filter('filter')($scope.pdpdata, $scope.filterPdpGroup, undefined);
};
- $scope.pushTabPDPGrid = {
+ $scope.pushTabPDPGrid = {
onRegisterApi: function(gridApi) {
$scope.gridApi = gridApi;
},
@@ -78,7 +73,7 @@ app.controller('policyPushController', function ($scope, PolicyAppService, modal
Notification.error("Policy Application has been LockDown.");
}else{
var modalInstance = $modal.open({
- backdrop: 'static', keyboard: false,
+ backdrop: 'static', keyboard: false,
templateUrl: 'remove_PDPGroupPolicies_popup.html',
controller: 'removeGroupPoliciesController',
resolve: {
@@ -91,7 +86,6 @@ app.controller('policyPushController', function ($scope, PolicyAppService, modal
}
});
modalInstance.result.then(function (response) {
- console.log('response', response);
$scope.pdpdata = JSON.parse(response.data);
$scope.pushTabPDPGrid.data = $scope.pdpdata;
});
@@ -99,75 +93,66 @@ app.controller('policyPushController', function ($scope, PolicyAppService, modal
};
$scope.gridOptions = {
- data : 'policydatas',
- onRegisterApi: function(gridApi) {
- $scope.gridPolicyApi = gridApi;
- },
- enableSorting: true,
- enableFiltering: true,
- showTreeExpandNoChildren: true,
- paginationPageSizes: [10, 20, 50, 100],
- paginationPageSize: 20,
- columnDefs: [{name: 'policyName', displayName : 'Policy Name', sort: { direction: 'asc', priority: 0 }},
- {name: 'activeVersion', displayName : 'Version'},
- {name: 'modifiedDate', displayName : 'Last Modified',type: 'date', cellFilter: 'date:\'yyyy-MM-dd HH:MM:ss a\'' }]
+ data : 'policydatas',
+ onRegisterApi: function(gridApi) {
+ $scope.gridPolicyApi = gridApi;
+ },
+ enableSorting: true,
+ enableFiltering: true,
+ showTreeExpandNoChildren: true,
+ paginationPageSizes: [10, 20, 50, 100],
+ paginationPageSize: 20,
+ columnDefs: [{name: 'policyName', displayName : 'Policy Name', sort: { direction: 'asc', priority: 0 }},
+ {name: 'activeVersion', displayName : 'Version'},
+ {name: 'modifiedDate', displayName : 'Last Modified',type: 'date', cellFilter: 'date:\'yyyy-MM-dd HH:MM:ss a\'' }]
};
PolicyAppService.getData('get_AutoPushPoliciesContainerData').then(function (data) {
- $scope.loading = false;
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.policydatas =JSON.parse($scope.data.policydatas);
- console.log($scope.policydatas);
- }, function (error) {
- console.log("failed");
- });
+ $scope.loading = false;
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.policydatas =JSON.parse($scope.data.policydatas);
+ });
$scope.pushPoliciesButton = function(){
- var policySelection = $scope.gridPolicyApi.selection.getSelectedRows();
- console.log(policySelection);
- var currentSelection = $scope.gridApi.selection.getSelectedRows();
- if(policySelection.length == 0 && currentSelection.length == 0){
- Notification.error("Please Select Policy and PDP Group to Push");
- }
- if(policySelection.length == 0 && currentSelection.length != 0){
- Notification.error("Please Select Policy to Push");
- }
- if(policySelection.length != 0 && currentSelection.length == 0){
- Notification.error("Please Select PDP Group to Push");
- }
- if(policySelection.length != 0 && currentSelection.length != 0){
- var finalData = {
- "pdpDatas": currentSelection,
- "policyDatas": policySelection
- };
- console.log(finalData);
- var uuu = "auto_Push/PushPolicyToPDP.htm";
- var postData={pushTabData: finalData};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.data=data.data;
- $scope.pdpdata = JSON.parse(data.data);
- $scope.pushTabPDPGrid.data = $scope.pdpdata;
- Notification.success("Policy Pushed Successfully");
- });
- console.log($scope.data);
- },
- error : function(data){
- Notification.error("Error Occured while Pushing Policy.");
- }
- });
+ var policySelection = $scope.gridPolicyApi.selection.getSelectedRows();
+ var currentSelection = $scope.gridApi.selection.getSelectedRows();
+ if(policySelection.length == 0 && currentSelection.length == 0){
+ Notification.error("Please Select Policy and PDP Group to Push");
+ }
+ if(policySelection.length == 0 && currentSelection.length != 0){
+ Notification.error("Please Select Policy to Push");
+ }
+ if(policySelection.length != 0 && currentSelection.length == 0){
+ Notification.error("Please Select PDP Group to Push");
+ }
+ if(policySelection.length != 0 && currentSelection.length != 0){
+ var finalData = {
+ "pdpDatas": currentSelection,
+ "policyDatas": policySelection
+ };
+ var uuu = "auto_Push/PushPolicyToPDP.htm";
+ var postData={pushTabData: finalData};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.data=data.data;
+ $scope.pdpdata = JSON.parse(data.data);
+ $scope.pushTabPDPGrid.data = $scope.pdpdata;
+ Notification.success("Policy Pushed Successfully");
+ });
+ },
+ error : function(data){
+ Notification.error("Error Occured while Pushing Policy.");
+ }
+ });
- }
+ }
};
-
-
});
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/AutoPushTabController/RemovePDPGroupPoliciesController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/AutoPushTabController/RemovePDPGroupPoliciesController.js
index 62dcd65b2..b8325b316 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/AutoPushTabController/RemovePDPGroupPoliciesController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/AutoPushTabController/RemovePDPGroupPoliciesController.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.
@@ -40,11 +40,9 @@ app.controller('removeGroupPoliciesController' , function ($scope, $modalInstan
//set gridApi on scope
$scope.gridApi = gridApi;
gridApi.selection.on.rowSelectionChanged($scope,function(row){
- var msg = 'row selected ' + row.isSelected;
});
gridApi.selection.on.rowSelectionChangedBatch($scope,function(rows){
- var msg = 'rows changed ' + rows.length;
});
};
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 051a9130c..7715c779a 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
@@ -17,7 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller('editRoleController' , function ($scope, PolicyAppService, $modalInstance, message){
+app.controller('editRoleController' , function ($scope, PolicyAppService, $modalInstance, message, Notification){
if (message.editRoleData != null) {
$scope.label='Edit Role'
$scope.disableCd=true;
@@ -67,7 +67,7 @@ app.controller('editRoleController' , function ($scope, PolicyAppService, $moda
$modalInstance.close({rolesDatas:$scope.rolesDatas});
},
error : function(data){
- alert("Error while saving Role.");
+ Notification.error("Error while saving Role.");
}
});
};
@@ -90,7 +90,7 @@ app.controller('editRoleController' , function ($scope, PolicyAppService, $moda
$modalInstance.close({rolesDatas:$scope.rolesDatas});
},
error : function(data) {
- alert("Error while Creating Mechid scopes.");
+ Notification.error("Error while Creating Mechid scopes.");
}
});
};
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dashboardCRUDController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dashboardCRUDController.js
index ce1af6b1a..d3f093697 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dashboardCRUDController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dashboardCRUDController.js
@@ -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.
@@ -19,20 +19,18 @@
*/
app.controller('policyDashboardCRUDDataController', function ($scope, PolicyAppService, modalService, $modal){
- console.log("policyDashboardCRUDDataController called");
-
- $('#dashBoardAdvanceSearch').hide();
-
+
+ $('#dashBoardAdvanceSearch').hide();
+
$scope.papCRUDTableDatasTemp = [];
$scope.dashboardAdsearch = { isDelected: 'both', stage: 'both', scope: "", ttlDate_after: "", ttlDate_before: ""};
PolicyAppService.getData('get_DashboardPolicyCRUDData').then(function(data){
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.papStatusCRUDDatas =JSON.parse($scope.data.papStatusCRUDData);
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.papStatusCRUDDatas =JSON.parse($scope.data.papStatusCRUDData);
if($scope.papStatusCRUDDatas != null){
for(i = 0; i < $scope.papStatusCRUDDatas.length; i++){
$scope.papCRUDTableDatasTemp.push($scope.papStatusCRUDDatas[i].map);
@@ -40,117 +38,106 @@ app.controller('policyDashboardCRUDDataController', function ($scope, PolicyAppS
$scope.papCRUDTableDatas = $scope.papCRUDTableDatasTemp;
}
-
- },function(error){
- console.log("failed");
- });
+
+ });
- $scope.papCRUDStatusDatas = {
- data : 'papCRUDTableDatas',
- enableFiltering: true,
- columnDefs: [{ field: 'id', displayName :'id'},
- {field: 'scope', displayName :'Scope'},
- {field: 'policyName', displayName :'Policy Name'},
- {field: 'version', displayName :'Version'},
- {field: 'stage', displayName :'Stage'},
- {field: 'createdBy', displayName :'Created By'},
- {field: 'deleted', displayName :'Deleted'},
- {field: 'deleteReasonCode', displayName :'Deleted Reason'},
- {field: 'deletedBy' , displayName :'Deleted By'},
- {field: 'modifiedBy' , displayName :'Modified By'},
- {field: 'createdDate', displayName :'Created Date'},
- {field: 'modifiedDate', displayName :'Modified Date'}
- ],
+ $scope.papCRUDStatusDatas = {
+ data : 'papCRUDTableDatas',
+ enableFiltering: true,
+ columnDefs: [{ field: 'id', displayName :'id'},
+ {field: 'scope', displayName :'Scope'},
+ {field: 'policyName', displayName :'Policy Name'},
+ {field: 'version', displayName :'Version'},
+ {field: 'stage', displayName :'Stage'},
+ {field: 'createdBy', displayName :'Created By'},
+ {field: 'deleted', displayName :'Deleted'},
+ {field: 'deleteReasonCode', displayName :'Deleted Reason'},
+ {field: 'deletedBy' , displayName :'Deleted By'},
+ {field: 'modifiedBy' , displayName :'Modified By'},
+ {field: 'createdDate', displayName :'Created Date'},
+ {field: 'modifiedDate', displayName :'Modified Date'}
+ ],
onRegisterApi: function(gridApi){
- $scope.gridApi = gridApi;
+ $scope.gridApi = gridApi;
}
- };
-
+ };
+
$('#ttlDate_after').datepicker({
- dateFormat: 'yy-mm-dd',
- changeMonth: true,
- changeYear: true,
- onSelect: function(date) {
- angular.element($('#ttlDate_after')).triggerHandler('input');
- }
+ dateFormat: 'yy-mm-dd',
+ changeMonth: true,
+ changeYear: true,
+ onSelect: function(date) {
+ angular.element($('#ttlDate_after')).triggerHandler('input');
+ }
});
$('#ttlDate_before').datepicker({
- dateFormat: 'yy-mm-dd',
- changeMonth: true,
- changeYear: true,
- onSelect: function(date) {
- angular.element($('#ttlDate_before')).triggerHandler('input');
- }
+ dateFormat: 'yy-mm-dd',
+ changeMonth: true,
+ changeYear: true,
+ onSelect: function(date) {
+ angular.element($('#ttlDate_before')).triggerHandler('input');
+ }
});
$scope.refresh = function(){
- $scope.modal('advancedSearch', true);
- $scope.temp.policy = "";
+ $scope.modal('advancedSearch', true);
+ $scope.temp.policy = "";
};
- $scope.advancedSearch = function(){
+ $scope.advancedSearch = function(){
- $('#dashBoardAdvanceSearch').toggle();
- if($('#advancedSearchArrow').hasClass('arrowdown')){
- $('#advancedSearchArrow').removeClass("arrowdown");
- $('#advancedSearchArrow').addClass("arrowup");
-
- }else{
- $('#advancedSearchArrow').removeClass("arrowup");
- $('#advancedSearchArrow').addClass("arrowdown");
- }
- }
-
+ $('#dashBoardAdvanceSearch').toggle();
+ if($('#advancedSearchArrow').hasClass('arrowdown')){
+ $('#advancedSearchArrow').removeClass("arrowdown");
+ $('#advancedSearchArrow').addClass("arrowup");
+
+ }else{
+ $('#advancedSearchArrow').removeClass("arrowup");
+ $('#advancedSearchArrow').addClass("arrowdown");
+ }
+ }
+
$scope.startAdvancedSearch = function(data){
-
- console.log("startAdvancedSearch called");
- console.log(data.isDelected);
- console.log(data.stage);
- console.log(data.scope);
- console.log(data.ttlDate_after);
- console.log(data.ttlDate_before);
-
- if(data.scope == null){
- return;
- }
-
+
+
+ if(data.scope == null){
+ return;
+ }
+
var uuu = "dashboardController/dashboardAdvancedSearch.htm";
var postData={policyData: data};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- console.log("dashboardAdvancedSearch data returned: " + data);
-
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+
$scope.$apply(function(){
-
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.papStatusCRUDDatas =JSON.parse($scope.data.policyStatusCRUDData);
-
- $scope.papCRUDTableDatasTemp = [];
-
- for(i = 0; i < $scope.papStatusCRUDDatas.length; i++){
- $scope.papCRUDTableDatasTemp.push($scope.papStatusCRUDDatas[i].map);
- }
-
- $scope.papCRUDTableDatas = $scope.papCRUDTableDatasTemp;
-
- $scope.gridApi.grid.refresh();
+
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.papStatusCRUDDatas =JSON.parse($scope.data.policyStatusCRUDData);
+
+ $scope.papCRUDTableDatasTemp = [];
+
+ for(i = 0; i < $scope.papStatusCRUDDatas.length; i++){
+ $scope.papCRUDTableDatasTemp.push($scope.papStatusCRUDDatas[i].map);
+ }
+
+ $scope.papCRUDTableDatas = $scope.papCRUDTableDatasTemp;
+
+ $scope.gridApi.grid.refresh();
});
- },
- error : function(data){
- console.log("dashboardAdvancedSearch Failed: data returned as " + data);
- }
- });
+ },
+ error : function(data){
+ }
+ });
};
}); \ No newline at end of file
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSControllerDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSControllerDictController.js
index 19b473294..a6de84efa 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSControllerDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSControllerDictController.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.
@@ -66,7 +66,7 @@ app.controller('editBRMSControllerController' , function ($scope, $modalInstanc
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}else{
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSDependencyDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSDependencyDictController.js
index 25a19baeb..f1157e878 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSDependencyDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSDependencyDictController.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.
@@ -66,7 +66,7 @@ app.controller('editBRMSDependencyController', function ($scope, $modalInstance,
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}else{
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSParamDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSParamDictController.js
index 678902840..f8d6d311e 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSParamDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/BRMSParamDictController.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.
@@ -60,7 +60,6 @@ app.controller('editBRMSParamController' , function ($scope, $modalInstance, mes
if(!regex.test(brmsParamDictionaryData.ruleName)) {
Notification.error("Enter Valid Rule Name without spaces or special characters");
}else{
- var file = $scope.MyFile;
var uuu = "saveDictionary/brms_dictionary/save_BRMSParam";
var postData={brmsParamDictionaryData: brmsParamDictionaryData, userid: userid};
$.ajax({
@@ -94,4 +93,4 @@ app.controller('editBRMSParamController' , function ($scope, $modalInstance, mes
$scope.close = function() {
$modalInstance.close();
};
-}); \ No newline at end of file
+});
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLPepOptionsDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLPepOptionsDictController.js
index 9bcf8dd6f..da389a8d2 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLPepOptionsDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLPepOptionsDictController.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.
@@ -85,7 +85,7 @@ app.controller('editPEPOptionsController', function ($scope, $modalInstance, me
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLServiceDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLServiceDictController.js
index b8bc0f9d1..b3e2fe092 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLServiceDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLServiceDictController.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.
@@ -58,7 +58,7 @@ app.controller('editCLServiceController' , function ($scope, $modalInstance, me
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLSiteDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLSiteDictController.js
index a673df5a2..cd2d89630 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLSiteDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLSiteDictController.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.
@@ -58,7 +58,7 @@ app.controller('editCLSiteController', function ($scope, $modalInstance, messag
}
},
error : function(data){
- alert("Error while saving.");
+ Notofication.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVarbindDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVarbindDictController.js
index 3b2a13f4a..44d62c5d9 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVarbindDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVarbindDictController.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.
@@ -58,7 +58,7 @@ app.controller('editCLVarbindController',function ($scope, $modalInstance, messa
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVnfTypeDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVnfTypeDictController.js
index 0d033621b..eb71a10df 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVnfTypeDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVnfTypeDictController.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.
@@ -58,7 +58,7 @@ app.controller('editVnfTypeController' , function ($scope, $modalInstance, mess
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVsclActionDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVsclActionDictController.js
index 106a8240d..cb78c4a38 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVsclActionDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/CLVsclActionDictController.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.
@@ -59,7 +59,7 @@ app.controller('editVsclActionController' , function ($scope, $modalInstance, m
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DecisionRainyDayDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DecisionRainyDayDictController.js
index b50becf0b..410ef26a0 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DecisionRainyDayDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DecisionRainyDayDictController.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.
@@ -52,7 +52,6 @@ app.controller('editRainyDayDictController' , function ($scope, $modalInstance,
$scope.editRainyDayTreatment = message.rainyDayDictionaryData;
$scope.saveDecisionTreatments = function(rainyDayDictionaryData) {
- var finalData = extend(rainyDayDictionaryData, $scope.treatmentDatas[0]);
var uuu = "saveDictionary/decision_dictionary/save_RainyDay";
var postData={rainyDayDictionaryData: rainyDayDictionaryData, userid: userid};
$.ajax({
@@ -72,18 +71,11 @@ app.controller('editRainyDayDictController' , function ($scope, $modalInstance,
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
};
- function extend(obj, src) {
- for (var key in src) {
- if (src.hasOwnProperty(key)) obj[key] = src[key];
- }
- return obj;
- }
-
$scope.treatmentDatas = [{"userDataTypeValues" : $scope.treatments}];
$scope.addNewTreatment = function() {
$scope.treatments.push({});
@@ -97,4 +89,4 @@ app.controller('editRainyDayDictController' , function ($scope, $modalInstance,
$scope.close = function() {
$modalInstance.close();
};
-}); \ No newline at end of file
+});
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DecisionSettingsDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DecisionSettingsDictController.js
index fb2dd40af..99379fdd7 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DecisionSettingsDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DecisionSettingsDictController.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.
@@ -59,7 +59,7 @@ app.controller('editSettingsDictController' , function ($scope, $modalInstance,
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DescriptiveSearchDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DescriptiveSearchDictController.js
index 266532a20..39d4058d8 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DescriptiveSearchDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/DescriptiveSearchDictController.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.
@@ -86,7 +86,7 @@ app.controller('editDescriptiveScopeController' , function ($scope, $modalInstan
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/EnforcerDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/EnforcerDictController.js
index 38f8f396f..2c6a6703c 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/EnforcerDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/EnforcerDictController.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.
@@ -17,7 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-var editEnforcerTypeController = function ($scope, $modalInstance, message, UserInfoServiceDS2){
+var editEnforcerTypeController = function ($scope, $modalInstance, message, UserInfoServiceDS2, Notification){
if(message.enforcerDictionaryData==null)
$scope.label='Add Enforcing Type'
else{
@@ -25,14 +25,14 @@ var editEnforcerTypeController = function ($scope, $modalInstance, message, Use
$scope.disableCd=true;
}
$scope.editEnforcerType = message.enforcerDictionaryData;
-
- /*getting user info from session*/
- var userid = null;
- UserInfoServiceDS2.getFunctionalMenuStaticDetailSession()
- .then(function (response) {
- userid = response.userid;
- });
-
+
+ /*getting user info from session*/
+ var userid = null;
+ UserInfoServiceDS2.getFunctionalMenuStaticDetailSession()
+ .then(function (response) {
+ userid = response.userid;
+ });
+
$scope.saveEnforcerType = function(enforcerDictionaryData) {
var uuu = "saveDictionary/enforcer_dictionary/save_enforcerType";
var postData={enforcerDictionaryData: enforcerDictionaryData, userid: userid};
@@ -49,7 +49,7 @@ var editEnforcerTypeController = function ($scope, $modalInstance, message, Use
$modalInstance.close({enforcerDictionaryDatas:$scope.enforcerDictionaryDatas});
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
};
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWActionListDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWActionListDictController.js
index 1eff96376..9d09959de 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWActionListDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWActionListDictController.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.
@@ -59,7 +59,7 @@ app.controller('editFWActionListController' , function ($scope, $modalInstance,
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWAddressGroupDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWAddressGroupDictController.js
index e9e4c3f5d..442eae955 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWAddressGroupDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWAddressGroupDictController.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.
@@ -87,7 +87,7 @@ app.controller('editFWAddressGroupController' , function ($scope, $modalInstance
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWParentListDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWParentListDictController.js
index 62b4a5b79..46f99762a 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWParentListDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWParentListDictController.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.
@@ -111,7 +111,7 @@ app.controller('editFWParentListController' , function ($scope, $modalInstance,
}
},
error : function(data){
- alert("Error while saving.");
+ Notification("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWPortListDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWPortListDictController.js
index 66caf4d8a..99e543034 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWPortListDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWPortListDictController.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.
@@ -59,7 +59,7 @@ app.controller('editFWPortListController' , function ($scope, $modalInstance, me
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWPrefixListDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWPrefixListDictController.js
index 1925e5f48..485af3ab6 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWPrefixListDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWPrefixListDictController.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.
@@ -60,7 +60,7 @@ app.controller('editFWPrefixListController' , function ($scope, $modalInstance,
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}else{
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWProtocolListDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWProtocolListDictController.js
index 82b1be794..5d382c62d 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWProtocolListDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWProtocolListDictController.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.
@@ -58,7 +58,7 @@ app.controller('editFWProtocolListController' , function ($scope, $modalInstance
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWSecurityZoneDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWSecurityZoneDictController.js
index 7d8da9d2a..a5238eeb4 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWSecurityZoneDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWSecurityZoneDictController.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.
@@ -24,44 +24,44 @@ app.controller('editfwSecurityZoneController' , function ($scope, $modalInstanc
$scope.label='Edit Security Zone'
$scope.disableCd=true;
}
-
- /*getting user info from session*/
- var userid = null;
- UserInfoServiceDS2.getFunctionalMenuStaticDetailSession()
- .then(function (response) {
- userid = response.userid;
- });
-
+
+ /*getting user info from session*/
+ var userid = null;
+ UserInfoServiceDS2.getFunctionalMenuStaticDetailSession()
+ .then(function (response) {
+ userid = response.userid;
+ });
+
$scope.editSecurityZone = message.securityZoneDictionaryData;
$scope.saveSecurityZone = function(securityZoneDictionaryData) {
- var regex = new RegExp("^[a-zA-Z0-9_]*$");
- if(!regex.test(securityZoneDictionaryData.zoneName)) {
- Notification.error("Enter Valid Security Zone Name without spaces or special characters");
- }else{
- var uuu = "saveDictionary/fw_dictionary/save_securityZone";
- var postData={securityZoneDictionaryData: securityZoneDictionaryData, userid: userid};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.securityZoneDictionaryDatas=data.securityZoneDictionaryDatas;});
- if($scope.securityZoneDictionaryDatas == "Duplicate"){
- Notification.error("FW SecurityZone Dictionary exists with Same Zone Name.")
- }else{
- console.log($scope.securityZoneDictionaryDatas);
- $modalInstance.close({securityZoneDictionaryDatas:$scope.securityZoneDictionaryDatas});
- }
- },
- error : function(data){
- alert("Error while saving.");
- }
- });
- }
+ var regex = new RegExp("^[a-zA-Z0-9_]*$");
+ if(!regex.test(securityZoneDictionaryData.zoneName)) {
+ Notification.error("Enter Valid Security Zone Name without spaces or special characters");
+ }else{
+ var uuu = "saveDictionary/fw_dictionary/save_securityZone";
+ var postData={securityZoneDictionaryData: securityZoneDictionaryData, userid: userid};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.securityZoneDictionaryDatas=data.securityZoneDictionaryDatas;});
+ if($scope.securityZoneDictionaryDatas == "Duplicate"){
+ Notification.error("FW SecurityZone Dictionary exists with Same Zone Name.")
+ }else{
+ console.log($scope.securityZoneDictionaryDatas);
+ $modalInstance.close({securityZoneDictionaryDatas:$scope.securityZoneDictionaryDatas});
+ }
+ },
+ error : function(data){
+ Notification.error("Error while saving.");
+ }
+ });
+ }
};
$scope.close = function() {
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWServiceGroupDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWServiceGroupDictController.js
index 43219bab5..dc3ae6e7d 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWServiceGroupDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWServiceGroupDictController.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.
@@ -87,7 +87,7 @@ app.controller('editFWServiceGroupController' , function ($scope, $modalInstanc
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWServiceListDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWServiceListDictController.js
index 0a6e8ba64..58b7be300 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWServiceListDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWServiceListDictController.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.
@@ -104,7 +104,7 @@ app.controller('editFWServiceListController' , function ($scope, $modalInstance
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTagListDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTagListDictController.js
index c70b3dd2f..7596e07a1 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTagListDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTagListDictController.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.
@@ -75,7 +75,7 @@ app.controller('editFWTagListController' , function ($scope, $modalInstance, mes
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTagPickerListDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTagPickerListDictController.js
index ed6571d4d..d813602fc 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTagPickerListDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTagPickerListDictController.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.
@@ -121,7 +121,7 @@ app.controller('editFWTagPickerController' , function ($scope, $modalInstance,
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTermListDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTermListDictController.js
index 73084195b..98a237ae2 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTermListDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWTermListDictController.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.
@@ -142,77 +142,54 @@ app.controller('editFWTermListController' , function ($scope, $modalInstance, me
PolicyAppService.getData('getDictionary/get_PrefixListDataByName').then(function (data) {
var j = data;
$scope.data = JSON.parse(j.data);
- console.log($scope.data);
$scope.prefixListDictionaryDatas = JSON.parse($scope.data.prefixListDictionaryDatas);
- console.log($scope.prefixListDictionaryDatas);
for(i = 0; i < $scope.prefixListDictionaryDatas.length; i++){
var key = $scope.prefixListDictionaryDatas[i];
$scope.groupAddresses.push(key);
}
- }, function (error) {
- console.log("failed");
});
PolicyAppService.getData('getDictionary/get_ZoneDictionaryDataByName').then(function (data) {
var j = data;
$scope.data = JSON.parse(j.data);
- console.log($scope.data);
$scope.zoneDictionaryDatas = JSON.parse($scope.data.zoneDictionaryDatas);
- console.log($scope.zoneDictionaryDatas);
- }, function (error) {
- console.log("failed");
});
PolicyAppService.getData('getDictionary/get_AddressGroupDictionaryDataByName').then(function (data) {
var j = data;
$scope.data = JSON.parse(j.data);
- console.log($scope.data);
$scope.addressGroupDictionaryDatas = JSON.parse($scope.data.addressGroupDictionaryDatas);
- console.log($scope.addressGroupDictionaryDatas);
for(i = 0; i < $scope.addressGroupDictionaryDatas.length; i++){
var key = $scope.addressGroupDictionaryDatas[i];
$scope.groupAddresses.push(key);
}
- }, function (error) {
- console.log("failed");
});
PolicyAppService.getData('getDictionary/get_ServiceListDictionaryDataByName').then(function (data) {
var j = data;
$scope.data = JSON.parse(j.data);
- console.log($scope.data);
$scope.serviceListDictionaryDatas = JSON.parse($scope.data.serviceListDictionaryDatas);
- console.log($scope.serviceListDictionaryDatas);
for(i = 0; i < $scope.serviceListDictionaryDatas.length; i++){
var key = $scope.serviceListDictionaryDatas[i];
$scope.groupServices.push(key);
}
- }, function (error) {
- console.log("failed");
});
PolicyAppService.getData('getDictionary/get_ServiceGroupDictionaryDataByName').then(function (data) {
var j = data;
$scope.data = JSON.parse(j.data);
- console.log($scope.data);
$scope.serviceGroupDictionaryDatas = JSON.parse($scope.data.serviceGroupDictionaryDatas);
- console.log($scope.serviceGroupDictionaryDatas);
for(i = 0; i < $scope.serviceGroupDictionaryDatas.length; i++){
var key = $scope.serviceGroupDictionaryDatas[i];
$scope.groupServices.push(key);
}
}, function (error) {
- console.log("failed");
});
PolicyAppService.getData('getDictionary/get_ActionListDictionaryDataByName').then(function (data) {
var j = data;
$scope.data = JSON.parse(j.data);
- console.log($scope.data);
$scope.actionListDictionaryDatas = JSON.parse($scope.data.actionListDictionaryDatas);
- console.log($scope.actionListDictionaryDatas);
- }, function (error) {
- console.log("failed");
});
@@ -251,12 +228,11 @@ app.controller('editFWTermListController' , function ($scope, $modalInstance, me
if($scope.termListDictionaryDatas == "Duplicate"){
Notification.error("FW TermList Dictionary exists with Same Term Name.")
}else{
- console.log($scope.termListDictionaryDatas);
$modalInstance.close({termListDictionaryDatas:$scope.termListDictionaryDatas});
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWZoneDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWZoneDictController.js
index bdb10f55e..4d1e6057b 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWZoneDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/FWZoneDictController.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.
@@ -58,7 +58,7 @@ app.controller('editFWZoneController' , function ($scope, $modalInstance, messa
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSConfigNameDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSConfigNameDictController.js
index a1b703880..743681afd 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSConfigNameDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSConfigNameDictController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-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.
@@ -59,7 +59,7 @@ app.controller('editMSConfigController' , function ($scope, $modalInstance, mes
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSDcaeUUIDDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSDcaeUUIDDictController.js
index 6fbb9b3e5..cd9a78525 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSDcaeUUIDDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSDcaeUUIDDictController.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.
@@ -58,7 +58,7 @@ app.controller('editDCAEuuidController' , function ($scope, $modalInstance, mess
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSDictionaryController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSDictionaryController.js
index 21b89697d..a3a9349c5 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSDictionaryController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSDictionaryController.js
@@ -59,7 +59,7 @@ app.controller('editMSDictController' , function ($scope, $modalInstance, messa
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSHeaderDefaultValuesDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSHeaderDefaultValuesDictController.js
index 960d76bd4..ce84afd84 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSHeaderDefaultValuesDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSHeaderDefaultValuesDictController.js
@@ -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.
@@ -17,118 +17,91 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller('editMSHeaderDefaultValuesController' , function ($scope, $modalInstance, message, PolicyAppService, UserInfoServiceDS2, Notification){
- if(message.modelAttributeDictionaryData==null)
- $scope.label='Set Header Default Values'
- else{
- $scope.label='Edit Header Default Values'
- $scope.disableCd=true;
- }
+app.controller('editMSHeaderDefaultValuesController' ,
+ function ($scope, $modalInstance, message, PolicyAppService, UserInfoServiceDS2, Notification){
+ if(message.modelAttributeDictionaryData==null)
+ $scope.label='Set Header Default Values'
+ else{
+ $scope.label='Edit Header Default Values'
+ $scope.disableCd=true;
+ }
- PolicyAppService.getData('getDictionary/get_MicroServiceHeaderDefaultsData').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.microServiceHeaderDefaultDatas = JSON.parse($scope.data.microServiceHeaderDefaultDatas);
- console.log("microServiceHeaderDefaultDatas:" + $scope.microServiceHeaderDefaultDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_MicroServiceHeaderDefaultsData').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.microServiceHeaderDefaultDatas = JSON.parse($scope.data.microServiceHeaderDefaultDatas);
+ });
- PolicyAppService.getData('getDictionary/get_MicroServiceModelsDataServiceVersion').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.microServiceModelsDictionaryDatas = JSON.parse($scope.data.microServiceModelsDictionaryDatas);
- console.log($scope.microServiceModelsDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
-
- PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log("riskTypeDictionaryDatas = " + $scope.data);
- $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
- console.log($scope.riskTypeDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_MicroServiceModelsDataServiceVersion').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.microServiceModelsDictionaryDatas = JSON.parse($scope.data.microServiceModelsDictionaryDatas);
+ });
+
+ PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
+ });
- PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log("riskTypeDictionaryDatas: " + $scope.data);
- $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
- console.log($scope.riskTypeDictionaryDatas);
- }, function (error) {
- 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);
- console.log($scope.onapNameDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
+ });
+
+ PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
+ });
- PolicyAppService.getData('get_DCAEPriorityValues').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.priorityDatas = JSON.parse($scope.data.priorityDatas);
- console.log($scope.priorityDatas);
- }, function (error) {
- console.log("failed");
- });
-
- /*getting user info from session*/
- var userid = null;
- UserInfoServiceDS2.getFunctionalMenuStaticDetailSession()
- .then(function (response) {
- userid = response.userid;
- });
-
- $scope.editHeaderDefaults = message.modelAttributeDictionaryData;
- $scope.editModelAttribute1 = {microservice: []};
- if($scope.edit){
- if(message.modelAttributeDictionaryData.groupList != null){
- var splitValue = message.modelAttributeDictionaryData.groupList.split(",");
- console.log(splitValue);
- }
- }
- $scope.saveHeaderDefaults = function(editHeaderDefaultsData) {
- console.log("editHeaderDefaultsData :" + editHeaderDefaultsData);
- var uuu = "saveDictionary/ms_dictionary/save_headerDefaults";
- var postData={modelAttributeDictionaryData: editHeaderDefaultsData, userid: userid};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.microServiceHeaderDefaultDatas=data.microServiceHeaderDefaultDatas;});
- console.log("microServiceHeaderDefaultDatas returned after saved: " + $scope.microServiceHeaderDefaultDatas);
- if($scope.microServiceAttributeDictionaryDatas == "Duplicate"){
- Notification.error("Model Attribute Dictionary exists with Same Attribute Name.")
- }else{
- console.log($scope.microServiceHeaderDefaultDatas);
- $modalInstance.close({microServiceHeaderDefaultDatas:$scope.microServiceHeaderDefaultDatas});
- }
- },
- error : function(data){
- alert("Error while saving.");
- }
- });
-
- };
+ PolicyAppService.getData('get_DCAEPriorityValues').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.priorityDatas = JSON.parse($scope.data.priorityDatas);
+ });
+
+ /*getting user info from session*/
+ var userid = null;
+ UserInfoServiceDS2.getFunctionalMenuStaticDetailSession()
+ .then(function (response) {
+ userid = response.userid;
+ });
+
+ $scope.editHeaderDefaults = message.modelAttributeDictionaryData;
+ $scope.editModelAttribute1 = {microservice: []};
+ if($scope.edit){
+ if(message.modelAttributeDictionaryData.groupList != null){
+ var splitValue = message.modelAttributeDictionaryData.groupList.split(",");
+ }
+ }
+ $scope.saveHeaderDefaults = function(editHeaderDefaultsData) {
+ var uuu = "saveDictionary/ms_dictionary/save_headerDefaults";
+ var postData={modelAttributeDictionaryData: editHeaderDefaultsData, userid: userid};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.microServiceHeaderDefaultDatas=data.microServiceHeaderDefaultDatas;});
+ if($scope.microServiceAttributeDictionaryDatas == "Duplicate"){
+ Notification.error("Model Attribute Dictionary exists with Same Attribute Name.")
+ }else{
+ $modalInstance.close({microServiceHeaderDefaultDatas:$scope.microServiceHeaderDefaultDatas});
+ }
+ },
+ error : function(data){
+ Notification.error("Error while saving.");
+ }
+ });
+
+ };
- $scope.close = function() {
- $modalInstance.close();
- };
- }); \ No newline at end of file
+ $scope.close = function() {
+ $modalInstance.close();
+ };
+ }); \ No newline at end of file
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSLocationDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSLocationDictController.js
index fbd8e35e2..198ea480e 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSLocationDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/MSLocationDictController.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.
@@ -58,7 +58,7 @@ app.controller('editMSLocationController' , function ($scope, $modalInstance, m
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/ModelAttributeDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/ModelAttributeDictController.js
index 242615e09..c03c7de1e 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/ModelAttributeDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/ModelAttributeDictController.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.
@@ -84,7 +84,7 @@ app.controller('editModelAttributeController' , function ($scope, $modalInstanc
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSClosedLoopDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSClosedLoopDictController.js
index 8377a87f9..d2357ba8b 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSClosedLoopDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSClosedLoopDictController.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.
@@ -58,7 +58,7 @@ app.controller('editPSClosedLoopController' , function ($scope, $modalInstance,
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSGroupPolicyScopeDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSGroupPolicyScopeDictController.js
index b456c57a0..6b65a5938 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSGroupPolicyScopeDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSGroupPolicyScopeDictController.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.
@@ -17,8 +17,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller('editPSGroupPolicyScopeController' , function ($scope, $modalInstance, message, PolicyAppService, UserInfoServiceDS2, Notification){
- $scope.edit = false;
+app.controller('editPSGroupPolicyScopeController' ,
+ function ($scope, $modalInstance, message, PolicyAppService, UserInfoServiceDS2, Notification){
+ $scope.edit = false;
if(message.groupPolicyScopeListData==null)
$scope.label='Add New Group Policy Scope'
else{
@@ -26,108 +27,89 @@ app.controller('editPSGroupPolicyScopeController' , function ($scope, $modalIns
$scope.disableCd=true;
$scope.edit = true;
}
-
+
PolicyAppService.getData('getDictionary/get_PSServiceDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.psServiceDictionaryDatas = JSON.parse($scope.data.psServiceDictionaryDatas);
- console.log($scope.psServiceDictionaryDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.psServiceDictionaryDatas = JSON.parse($scope.data.psServiceDictionaryDatas);
});
PolicyAppService.getData('getDictionary/get_PSTypeDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.psTypeDictionaryDatas = JSON.parse($scope.data.psTypeDictionaryDatas);
- console.log($scope.psTypeDictionaryDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.psTypeDictionaryDatas = JSON.parse($scope.data.psTypeDictionaryDatas);
});
PolicyAppService.getData('getDictionary/get_PSResourceDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.psResourceDictionaryDatas = JSON.parse($scope.data.psResourceDictionaryDatas);
- console.log($scope.psResourceDictionaryDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.psResourceDictionaryDatas = JSON.parse($scope.data.psResourceDictionaryDatas);
});
PolicyAppService.getData('getDictionary/get_PSClosedLoopDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.psClosedLoopDictionaryDatas = JSON.parse($scope.data.psClosedLoopDictionaryDatas);
- console.log($scope.psClosedLoopDictionaryDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.psClosedLoopDictionaryDatas = JSON.parse($scope.data.psClosedLoopDictionaryDatas);
});
-
- /*getting user info from session*/
- var userid = null;
- UserInfoServiceDS2.getFunctionalMenuStaticDetailSession()
- .then(function (response) {
- userid = response.userid;
- });
+
+ /*getting user info from session*/
+ var userid = null;
+ UserInfoServiceDS2.getFunctionalMenuStaticDetailSession()
+ .then(function (response) {
+ userid = response.userid;
+ });
$scope.editPSGroupPolicyScope = message.groupPolicyScopeListData;
$scope.editPSGroupPolicyScope1 = {resource: [], type:[], service: [], closedloop: []};
if($scope.edit){
- if(message.groupPolicyScopeListData.groupList != null){
- var splitValue = message.groupPolicyScopeListData.groupList.split(",");
- console.log(splitValue);
- $scope.splittedGroupListValues = [];
- var splitResource = splitValue[0].split("=");
- $scope.editPSGroupPolicyScope1.resource.push(splitResource[1]);
- var splitType = splitValue[1].split("=");
- $scope.editPSGroupPolicyScope1.type.push(splitType[1]);
- var splitService = splitValue[2].split("=");
- $scope.editPSGroupPolicyScope1.service.push(splitService[1]);
- var splitCloop = splitValue[3].split("=");
- $scope.editPSGroupPolicyScope1.closedloop.push(splitCloop[1]);
- }
+ if(message.groupPolicyScopeListData.groupList != null){
+ var splitValue = message.groupPolicyScopeListData.groupList.split(",");
+ $scope.splittedGroupListValues = [];
+ var splitResource = splitValue[0].split("=");
+ $scope.editPSGroupPolicyScope1.resource.push(splitResource[1]);
+ var splitType = splitValue[1].split("=");
+ $scope.editPSGroupPolicyScope1.type.push(splitType[1]);
+ var splitService = splitValue[2].split("=");
+ $scope.editPSGroupPolicyScope1.service.push(splitService[1]);
+ var splitCloop = splitValue[3].split("=");
+ $scope.editPSGroupPolicyScope1.closedloop.push(splitCloop[1]);
+ }
}
$scope.savePSGroupPolicyScope = function(groupPolicyScopeListData, groupPolicyScopeListData1) {
- var regex = new RegExp("^[a-zA-Z0-9_]*$");
- if(!regex.test(groupPolicyScopeListData.groupName)) {
- Notification.error("Enter Valid Policy Scope Group Name without spaces or special characters");
- }else{
- console.log(groupPolicyScopeListData1);
- if(groupPolicyScopeListData1.resource[0] != undefined && groupPolicyScopeListData1.type[0] != undefined && groupPolicyScopeListData1.service[0] != undefined && groupPolicyScopeListData1.closedloop[0] != undefined){
- var uuu = "saveDictionary/ps_dictionary/save_psGroupPolicyScope";
- var postData={groupPolicyScopeListData: groupPolicyScopeListData,
- groupPolicyScopeListData1: groupPolicyScopeListData1, userid: userid};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.groupPolicyScopeListDatas=data.groupPolicyScopeListDatas;});
- if($scope.groupPolicyScopeListDatas == "Duplicate"){
- Notification.error("GroupPolicyScope Dictionary exists with Same Group Name.")
- }else if($scope.groupPolicyScopeListDatas == "DuplicateGroup"){
- Notification.error("GroupPolicyScope Dictionary exists with Same Group List.")
- }else{
- console.log($scope.groupPolicyScopeListDatas);
- $modalInstance.close({groupPolicyScopeListDatas:$scope.groupPolicyScopeListDatas});
- }
- },
- error : function(data){
- Notification.error("Error while saving.");
- }
- });
- }else{
- Notification.error("Please Select all the required fields to Save");
- }
- }
+ var regex = new RegExp("^[a-zA-Z0-9_]*$");
+ if(!regex.test(groupPolicyScopeListData.groupName)) {
+ Notification.error("Enter Valid Policy Scope Group Name without spaces or special characters");
+ }else{
+ if(groupPolicyScopeListData1.resource[0] != undefined && groupPolicyScopeListData1.type[0] != undefined && groupPolicyScopeListData1.service[0] != undefined && groupPolicyScopeListData1.closedloop[0] != undefined){
+ var uuu = "saveDictionary/ps_dictionary/save_psGroupPolicyScope";
+ var postData={groupPolicyScopeListData: groupPolicyScopeListData,
+ groupPolicyScopeListData1: groupPolicyScopeListData1, userid: userid};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.groupPolicyScopeListDatas=data.groupPolicyScopeListDatas;});
+ if($scope.groupPolicyScopeListDatas == "Duplicate"){
+ Notification.error("GroupPolicyScope Dictionary exists with Same Group Name.")
+ }else if($scope.groupPolicyScopeListDatas == "DuplicateGroup"){
+ Notification.error("GroupPolicyScope Dictionary exists with Same Group List.")
+ }else{
+ $modalInstance.close({groupPolicyScopeListDatas:$scope.groupPolicyScopeListDatas});
+ }
+ },
+ error : function(data){
+ Notification.error("Error while saving.");
+ }
+ });
+ }else{
+ Notification.error("Please Select all the required fields to Save");
+ }
+ }
};
$scope.close = function() {
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSResourceDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSResourceDictController.js
index 7aa028397..1afdcd6eb 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSResourceDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSResourceDictController.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.
@@ -58,7 +58,7 @@ app.controller('editPSResourceController' , function ($scope, $modalInstance, me
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSServiceDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSServiceDictController.js
index 53c6776f5..7946a145f 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSServiceDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSServiceDictController.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.
@@ -58,7 +58,7 @@ app.controller('editPSServiceController' , function ($scope, $modalInstance, mes
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSTypeDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSTypeDictController.js
index 9305e23e2..de87f130b 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSTypeDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/PSTypeDictController.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.
@@ -59,7 +59,7 @@ app.controller('editPSTypeController' , function ($scope, $modalInstance, messag
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/RiskTypeDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/RiskTypeDictController.js
index 48ff66339..565091977 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/RiskTypeDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/RiskTypeDictController.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.
@@ -58,7 +58,7 @@ app.controller('editRiskTypeController', function ($scope, $modalInstance, messa
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/SafePolicyWarningDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/SafePolicyWarningDictController.js
index e07262298..53810283c 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/SafePolicyWarningDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/SafePolicyWarningDictController.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.
@@ -91,7 +91,7 @@ app.controller('editSafePolicyWarningController' , function ($scope, $modalInst
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/actionPolicyDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/actionPolicyDictController.js
index 572211997..4614ed5f4 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/actionPolicyDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/actionPolicyDictController.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.
@@ -84,7 +84,7 @@ app.controller('editActionPolicyDictController', function ($scope, $modalInstanc
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/attributeDictController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/attributeDictController.js
index 4ca3b2266..3e54dd339 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/attributeDictController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/attributeDictController.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.
@@ -55,7 +55,6 @@ app.controller('editAttributeController' ,function ($scope, $modalInstance, mess
if(!regex.test(attributeDictionaryData.xacmlId)) {
Notification.error("Enter Valid Attribute Name without spaces or special characters");
}else{
- var finalData = extend(attributeDictionaryData, $scope.attributeDatas[0]);
var uuu = "saveDictionary/attribute_dictionary/save_attribute";
var postData={attributeDictionaryData: attributeDictionaryData, userid: userid};
$.ajax({
@@ -75,7 +74,7 @@ app.controller('editAttributeController' ,function ($scope, $modalInstance, mess
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
@@ -101,4 +100,4 @@ app.controller('editAttributeController' ,function ($scope, $modalInstance, mess
$scope.close = function() {
$modalInstance.close();
};
-}); \ No newline at end of file
+});
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/onapNameEditorController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/onapNameEditorController.js
index 2a2e743fb..c6ae5fffe 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/onapNameEditorController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryController/onapNameEditorController.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.
@@ -58,7 +58,7 @@ app.controller('editOnapNameController' , function ($scope, $modalInstance, mes
}
},
error : function(data){
- alert("Error while saving.");
+ Notification.error("Error while saving.");
}
});
}
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/BRMSParamDictGridController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/BRMSParamDictGridController.js
index 50e14ea26..af1c34607 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/BRMSParamDictGridController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/BRMSParamDictGridController.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.
@@ -17,7 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller('brmsParamDictGridController', function ($scope, PolicyAppService,modalService, $modal){
+app.controller('brmsParamDictGridController', function ($scope, PolicyAppService,modalService, $modal, Notification){
$( "#dialog" ).hide();
PolicyAppService.getData('getDictionary/get_BRMSParamData').then(function (data) {
@@ -164,7 +164,7 @@ app.controller('brmsParamDictGridController', function ($scope, PolicyAppService
})}
},
error : function(data){
- alert("Error while Searching.");
+ Notification.error("Error while Searching.");
}
});
};
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLPepOptionsDictGridController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLPepOptionsDictGridController.js
index cb79d6d44..1292139c6 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLPepOptionsDictGridController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLPepOptionsDictGridController.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.
@@ -17,7 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller('pepOptionsDictGridController', function ($scope, PolicyAppService, modalService, $modal){
+app.controller('pepOptionsDictGridController', function ($scope, PolicyAppService, modalService, $modal, Notification){
$( "#dialog" ).hide();
@@ -189,7 +189,7 @@ app.controller('pepOptionsDictGridController', function ($scope, PolicyAppServic
})}
},
error : function(data){
- alert("Error while Searching.");
+ Notification.error("Error while Searching.");
}
});
};
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLServiceDictGridController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLServiceDictGridController.js
index de692a4f4..d41e940b6 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLServiceDictGridController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLServiceDictGridController.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.
@@ -17,7 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller('serviceDictGridController', function ($scope, PolicyAppService, modalService, $modal){
+app.controller('serviceDictGridController', function ($scope, PolicyAppService, modalService, $modal, Notification){
$( "#dialog" ).hide();
PolicyAppService.getData('getDictionary/get_ClosedLoopServicesData').then(function (data) {
@@ -187,7 +187,7 @@ app.controller('serviceDictGridController', function ($scope, PolicyAppService,
})}
},
error : function(data){
- alert("Error while Searching.");
+ Notification.error("Error while Searching.");
}
});
};
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLSiteDictGridController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLSiteDictGridController.js
index abf44f86a..f72375246 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLSiteDictGridController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLSiteDictGridController.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.
@@ -17,7 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller('siteDictGridController', function ($scope, PolicyAppService, modalService, $modal){
+app.controller('siteDictGridController', function ($scope, PolicyAppService, modalService, $modal, Notification){
$( "#dialog" ).hide();
PolicyAppService.getData('getDictionary/get_ClosedLoopSiteData').then(function (data) {
@@ -187,7 +187,7 @@ app.controller('siteDictGridController', function ($scope, PolicyAppService, mod
})}
},
error : function(data){
- alert("Error while Searching.");
+ Notification.error("Error while Searching.");
}
});
};
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVarbindDictGridController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVarbindDictGridController.js
index 4e13b9779..e2a69bd8d 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVarbindDictGridController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVarbindDictGridController.js
@@ -17,7 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller('varbindDictGridController', function ($scope, PolicyAppService, modalService, $modal){
+app.controller('varbindDictGridController', function ($scope, PolicyAppService, modalService, $modal, Notification){
$( "#dialog" ).hide();
PolicyAppService.getData('getDictionary/get_VarbindDictionaryData').then(function (data) {
@@ -188,7 +188,7 @@ app.controller('varbindDictGridController', function ($scope, PolicyAppService,
})}
},
error : function(data){
- alert("Error while Searching.");
+ Notification.error("Error while Searching.");
}
});
};
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVnfTypeDictGridController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVnfTypeDictGridController.js
index 90b77e45d..22978ba19 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVnfTypeDictGridController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVnfTypeDictGridController.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.
@@ -17,7 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller('vnfTypeDictGridController', function ($scope, PolicyAppService, modalService, $modal){
+app.controller('vnfTypeDictGridController', function ($scope, PolicyAppService, modalService, $modal, Notification){
$( "#dialog" ).hide();
PolicyAppService.getData('getDictionary/get_VNFTypeData').then(function (data) {
@@ -187,7 +187,7 @@ app.controller('vnfTypeDictGridController', function ($scope, PolicyAppService,
})}
},
error : function(data){
- alert("Error while Searching.");
+ Notification.error("Error while Searching.");
}
});
};
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVsclActionDictGridController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVsclActionDictGridController.js
index 1c26c21b0..7077bc5e6 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVsclActionDictGridController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVsclActionDictGridController.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.
@@ -17,7 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller('vsclActionDictGridController', function ($scope, PolicyAppService, modalService, $modal){
+app.controller('vsclActionDictGridController', function ($scope, PolicyAppService, modalService, $modal, Notification){
$( "#dialog" ).hide();
PolicyAppService.getData('getDictionary/get_VSCLActionData').then(function (data) {
@@ -188,7 +188,7 @@ app.controller('vsclActionDictGridController', function ($scope, PolicyAppServic
})}
},
error : function(data){
- alert("Error while Searching.");
+ Notification.error("Error while Searching.");
}
});
};
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/MSHeaderDefaultValuesDictGridController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/MSHeaderDefaultValuesDictGridController.js
index 4e6b9696b..e12db92c7 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/MSHeaderDefaultValuesDictGridController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/MSHeaderDefaultValuesDictGridController.js
@@ -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.
@@ -23,51 +23,31 @@ app.controller('msHeaderDefaultValuesDictGridController', function ($scope, Poli
PolicyAppService.getData('getDictionary/get_MicroServiceHeaderDefaultsData').then(function (data) {
var j = data;
$scope.data = JSON.parse(j.data);
- console.log($scope.data);
$scope.microServiceHeaderDefaultDatas = JSON.parse($scope.data.microServiceHeaderDefaultDatas);
- console.log("microServiceHeaderDefaultDatas: " + $scope.microServiceHeaderDefaultDatas);
- }, function (error) {
- console.log("failed");
});
PolicyAppService.getData('getDictionary/get_MicroServiceModelsDataByName').then(function (data) {
var j = data;
$scope.data = JSON.parse(j.data);
- console.log($scope.data);
$scope.microServiceModelsDictionaryDatas = JSON.parse($scope.data.microServiceModelsDictionaryDatas);
- console.log($scope.microServiceModelsDictionaryDatas);
- }, function (error) {
- console.log("failed");
});
PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
var j = data;
$scope.data = JSON.parse(j.data);
- console.log("riskTypeDictionaryDatas: " + $scope.data);
$scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
- console.log($scope.riskTypeDictionaryDatas);
- }, function (error) {
- 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);
- console.log($scope.onapNameDictionaryDatas);
- }, function (error) {
- console.log("failed");
});
PolicyAppService.getData('get_DCAEPriorityValues').then(function (data) {
var j = data;
$scope.data = JSON.parse(j.data);
- console.log($scope.data);
$scope.priorityDatas = JSON.parse($scope.data.priorityDatas);
- console.log($scope.priorityDatas);
- }, function (error) {
- console.log("failed");
});
PolicyAppService.getData('get_LockDownData').then(function(data){
@@ -81,8 +61,6 @@ app.controller('msHeaderDefaultValuesDictGridController', function ($scope, Poli
$scope.msHeaderDefaultValuesDictionaryGrid.columnDefs[0].visible = true;
$scope.gridApi.grid.refresh();
}
- },function(error){
- console.log("failed");
});
$scope.msHeaderDefaultValuesDictionaryGrid = {
@@ -116,7 +94,6 @@ app.controller('msHeaderDefaultValuesDictGridController', function ($scope, Poli
}
});
modalInstance.result.then(function(response){
- console.log('response', response);
$scope.microServiceHeaderDefaultDatas=response.microServiceHeaderDefaultDatas;
});
};
@@ -137,7 +114,6 @@ app.controller('msHeaderDefaultValuesDictGridController', function ($scope, Poli
}
});
modalInstance.result.then(function(response){
- console.log('response', response);
$scope.modelAttributeDictionaryDataa = response.modelAttributeDictionaryDatas;
});
};
@@ -157,7 +133,6 @@ app.controller('msHeaderDefaultValuesDictGridController', function ($scope, Poli
$scope.$apply(function(){$scope.microServiceHeaderDefaultDatas=data.microServiceHeaderDefaultDatas;});
},
error : function(data){
- console.log(data);
modalService.showFailure("Fail","Error while deleting: "+ data.responseText);
}
});
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/attributeDictGridController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/attributeDictGridController.js
index 760418553..7459bd6e7 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/attributeDictGridController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/attributeDictGridController.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.
@@ -17,7 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller('attributeDictGridController', function ($scope, PolicyAppService, modalService, $modal){
+app.controller('attributeDictGridController', function ($scope, PolicyAppService, modalService, $modal, Notification){
$( "#dialog" ).hide();
PolicyAppService.getData('getDictionary/get_AttributeData').then(function (data) {
@@ -198,7 +198,7 @@ app.controller('attributeDictGridController', function ($scope, PolicyAppService
})}
},
error : function(data){
- alert("Error while Searching.");
+ Notification.error("Error while Searching.");
}
});
};
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/onapNameDictGridController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/onapNameDictGridController.js
index 4dd1df8c3..6727a7a30 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/onapNameDictGridController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/onapNameDictGridController.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.
@@ -17,7 +17,7 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller('onapNameDictGridController', function ($scope, PolicyAppService, modalService, $modal, uiGridConstants,Grid){
+app.controller('onapNameDictGridController', function ($scope, PolicyAppService, modalService, $modal, uiGridConstants,Grid, Notification){
$( "#dialog" ).hide();
PolicyAppService.getData('getDictionary/get_OnapNameData').then(function (data) {
@@ -58,7 +58,7 @@ app.controller('onapNameDictGridController', function ($scope, PolicyAppService,
'<button type="button" class="btn btn-primary" ng-click="grid.appScope.editOnapNameWindow(row.entity)"><i class="fa fa-pencil-square-o"></i></button> ' +
'<button type="button" class="btn btn-danger" ng-click="grid.appScope.deleteOnapName(row.entity)" ><i class="fa fa-trash-o"></i></button> ', width: '8%'
},
- { field: 'onapName', displayName : 'Onap Name', sort: { direction: 'asc', priority: 0 } },
+ { field: 'name', displayName : 'Onap Name', sort: { direction: 'asc', priority: 0 } },
{ field: 'description', width: '20%' },
{field: 'userCreatedBy.userName', displayName : 'Created By'},
{field: 'userModifiedBy.userName', displayName : 'Modified By' },
@@ -189,7 +189,7 @@ app.controller('onapNameDictGridController', function ($scope, PolicyAppService,
})}
},
error : function(data){
- alert("Error while Searching.");
+ Notification.error("Error while Searching.");
}
});
};
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/policyAdminTabController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/policyAdminTabController.js
index 4fabc458d..a0de546d9 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/policyAdminTabController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/policyAdminTabController.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.
@@ -17,50 +17,54 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-app.controller("policyAdminController", function($scope, PolicyAppService, modalService, $modal, Notification){
- $( "#dialog" ).hide();
-
+app.controller("policyAdminController", function($scope, PolicyAppService, modalService, $modal, Notification) {
+ $("#dialog").hide();
+
$scope.isDisabled = true;
- PolicyAppService.getData('get_LockDownData').then(function(data){
+ 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;
- }
+ if ($scope.lockdowndata[0].lockdown == true) {
+ $scope.isDisabled = true;
+ } else {
+ $scope.isDisabled = false;
+ }
console.log($scope.data);
- },function(error){
+ }, function(error) {
console.log("failed");
});
-
- $scope.saveLockDownValue = function(lockdownValue){
- console.log(lockdownValue);
- if(lockdownValue == true){
- Notification.success("Policy Application has been Locked Successfully");
- $scope.isDisabled = true;
- }else{
- Notification.success("Policy Application has been UnLocked Successfully");
- $scope.isDisabled = false;
- }
- var uuu = "adminTabController/save_LockDownValue.htm";
- var postData={lockdowndata: {lockdown : lockdownValue}};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.data=data.data;
- });
- console.log($scope.data);
- },
- error : function(data){
- alert("Error Occured while saving Lockdown Value.");
- }
- });
- };
+
+ $scope.saveLockDownValue = function(lockdownValue) {
+ console.log(lockdownValue);
+ if (lockdownValue == true) {
+ Notification.success("Policy Application has been Locked Successfully");
+ $scope.isDisabled = true;
+ } else {
+ Notification.success("Policy Application has been UnLocked Successfully");
+ $scope.isDisabled = false;
+ }
+ var uuu = "adminTabController/save_LockDownValue.htm";
+ var postData = {
+ lockdowndata : {
+ lockdown : lockdownValue
+ }
+ };
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType : 'json',
+ contentType : 'application/json',
+ data : JSON.stringify(postData),
+ success : function(data) {
+ $scope.$apply(function() {
+ $scope.data = data.data;
+ });
+ console.log($scope.data);
+ },
+ error : function(data) {
+ Notification.error("Error Occured while saving Lockdown Value.");
+ }
+ });
+ };
}); \ No newline at end of file
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/main/modalPopupController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/main/modalPopupController.js
index 7eb2b450e..7b3eca291 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/main/modalPopupController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/main/modalPopupController.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.
@@ -17,24 +17,24 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-appDS2.controller('modalpopupController' , function ($scope, $modalInstance, message){
-
- $scope.message = message;
-
-
- $scope.hello = function () {
+appDS2.controller('modalpopupController' , function ($scope, $modalInstance, message, Notification){
+
+ $scope.message = message;
+
+
+ $scope.hello = function () {
$modalInstance.close($scope.digitPattern);
};
- $modalInstance.ok = function() {
+ $modalInstance.ok = function() {
//add the ok functionality
- alert("Logout");
+ Notification.error("Logout");
};
$modalInstance.cancel = function() {
//add the cancel functionality
- alert("Keep Log in");
+ Notification.error("Keep Log in");
};
$modalInstance.cancelbutton = function() {
//add the cancel functionality
- alert("Modal Waring popup close event");
+ Notification.error("Modal Waring popup close event");
};
}); \ No newline at end of file
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/main/policyEditor.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/main/policyEditor.html
index 6efb8b637..0493afce1 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/main/policyEditor.html
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/main/policyEditor.html
@@ -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.
@@ -20,272 +20,273 @@
<!DOCTYPE html>
<html>
<head>
- <meta charset="ISO-8859-1">
- <title>Policy</title>
+ <meta charset="ISO-8859-1">
+ <title>Policy</title>
- <!-- Resources -->
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css">
- <!---------------------------AngularJs-------------------------------->
- <script src= "app/fusion/external/angular-1.4.8/angular.js"></script>
- <script src= "app/fusion/external/angular-1.4.8/angular.min.js"></script>
- <script src= "app/policyApp/libs/bower_components/angular-translate/angular-translate.min.js"></script>
- <script src= "app/policyApp/libs/bower_components/ng-file-upload/ng-file-upload.min.js"></script>
- <script src= "app/fusion/external/angular-1.4.8/angular-messages.js"></script>
- <script src= "app/fusion/external/angular-1.4.8/angular-touch.js"></script>
- <script src= "//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.js"></script>
- <script src= "app/fusion/external/angular-1.4.8/angular-sanitize.min.js"></script>
- <script src= "app/fusion/external/angular-1.4.8/angular-route.min.js"></script>
- <script src= "app/fusion/external/angular-1.4.8/angular-cookies.min.js"></script>
-
- <script src= "app/fusion/external/b2b/js/b2b-angular/b2b-library.min.js"></script>
- <script src= "app/fusion/external/jquery/dist/jquery.min.js"></script>
- <script src= "app/policyApp/libs/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
- <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
- <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
-
- <!---------------------------Angular Gridster-------------------------------->
- <link rel="stylesheet" href="app/fusion/external/angular-gridster/dist/angular-gridster.min.css">
- <link rel="stylesheet" href= "app/fusion/external/angular-bootstrap/ui-bootstrap-csp.css">
- <script src= "app/fusion/external/javascript-detect-element-resize/jquery.resize.js"></script>
- <script src= "app/fusion/external/angular-bootstrap/ui-bootstrap-tpls.min.js"></script>
- <script src= "app/fusion/external/angular-gridster/dist/angular-gridster.min.js"></script>
+ <!-- Resources -->
+ <link rel="stylesheet" href="app/policyApp/CSS/font-awesome.min.css">
+ <!---------------------------AngularJs-------------------------------->
+ <script src= "app/fusion/external/angular-1.4.13/angular.js"></script>
+ <script src= "app/fusion/external/angular-1.4.13/angular.min.js"></script>
+ <script src= "app/policyApp/libs/bower_components/angular-translate/angular-translate.min.js"></script>
+ <script src= "app/policyApp/libs/bower_components/ng-file-upload/ng-file-upload.min.js"></script>
+ <script src= "app/fusion/external/angular-1.4.13/angular-messages.js"></script>
+ <script src= "app/fusion/external/angular-1.4.13/angular-touch.js"></script>
+ <script src= "app/fusion/external/angular-1.4.13/angular-animate.js"></script>
+ <script src= "app/fusion/external/angular-1.4.13/angular-sanitize.min.js"></script>
+ <script src= "app/fusion/external/angular-1.4.13/angular-route.min.js"></script>
+ <script src= "app/fusion/external/angular-1.4.13/angular-cookies.min.js"></script>
- <!---------------------------Policy App CSS-------------------------------->
- <link rel="stylesheet" href="app/policyApp/CSS/font-awesome.min.css">
- <link rel="stylesheet" href="app/policyApp/CSS/Notification/angular-csp.css">
- <link rel="stylesheet" href="app/policyApp/CSS/Notification/angular-ui-notification.min.css">
- <link rel="stylesheet" href="app/policyApp/CSS/lockdownIcon.css">
- <link rel="stylesheet" href="app/policyApp/CSS/w3.css">
- <link rel="stylesheet" href="app/policyApp/CSS/select.css">
- <link rel="stylesheet" href="app/policyApp/policy-models/Editor/css/normalize.css">
- <link rel="stylesheet" href="app/policyApp/policy-models/Editor/css/animations.css">
- <link rel="stylesheet" href="app/policyApp/policy-models/Editor/css/dialogs.css">
- <link rel="stylesheet" href="app/policyApp/policy-models/Editor/css/main.css">
- <link rel="stylesheet" href="app/policyApp/policy-models/Editor/css/styles.css">
- <script src= "app/policyApp/CSS/Notification/angular-ui-notification.min.js"></script>
-
- <script src= "app/policyApp/CSS/UIGrid/ui-grid.js"></script>
- <link rel="stylesheet" href="app/policyApp/CSS/UIGrid/ui-grid.css">
-
- <script src= "app/fusion/external/ds2/js/appDS2.js"></script>
+ <script src= "app/fusion/external/b2b/js/b2b-angular/b2b-library.min.js"></script>
+ <script src= "app/fusion/external/jquery/dist/jquery.min.js"></script>
+ <script src= "app/policyApp/CSS/bootstrap/dist/js/bootstrap-modalmanager.min.js"></script>
+ <script src= "app/policyApp/CSS/bootstrap/dist/js/bootstrap.min.js"></script>
+ <!-- <link rel="stylesheet" href="app/fusion/styles/jquery-ui.css"> -->
+ <script src= "static/js/jquery-ui.js"></script>
- <script src= "app/fusion/scripts/DS2-services/headerServiceDS2.js"></script>
- <script src= "app/fusion/scripts/DS2-services/leftMenuServiceDS2.js"></script>
- <script src= "app/fusion/scripts/DS2-services/manifestService.js"></script>
- <script src= "app/fusion/scripts/DS2-directives/footer.js"></script>
- <script src= "app/fusion/scripts/DS2-directives/ds2Header.js"></script>
- <script src= "app/fusion/scripts/DS2-directives/ds2LeftMenu.js"></script>
- <script src="app/fusion/scripts/DS2-directives/b2b-leftnav-ext.js"></script>
- <!-- /*<script src= "app/fusion/scripts/DS2-services/userInfoServiceDS2.js"></script>*/ -->
- <script src= "app/policyApp/service/userInfoServiceDS2.js"></script>
-
- <!---------------------------Policy Editor js-------------------------------->
- <script src= "app/policyApp/policy-models/Editor/js/app.js"></script>
- <script src= "app/policyApp/service/PolicyAppService.js"></script>
- <script src= "app/policyApp/main/modalPopupController.js"></script>
- <script src= "app/policyApp/service/modalService.js"></script>
- <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/ExportPolicyController.js"></script>
- <script src= "app/policyApp/policy-models/Editor/js/directives/directives.js"></script>
- <script src= "app/policyApp/policy-models/Editor/js/filters/filters.js"></script>
- <script src= "app/policyApp/policy-models/Editor/js/providers/config.js"></script>
- <script src= "app/policyApp/policy-models/Editor/js/entities/item.js"></script>
- <script src= "app/policyApp/policy-models/Editor/js/services/policynavigator.js"></script>
- <script src= "app/policyApp/policy-models/Editor/js/services/policyuploader.js"></script>
- <script src= "app/policyApp/policy-models/Editor/js/controllers/policyManager.js"></script>
- <script src= "app/policyApp/policy-models/Editor/js/controllers/policySearchManager.js"></script>
- <script src= "app/policyApp/policy-models/Editor/js/controllers/selector-controller.js"></script>
- <script src= "app/policyApp/controller/policyController.js"></script>
-
- <!---------------------------Policy Left Menu Controllers-------------------------------->
- <script src= "app/policyApp/controller/policyAdminTabController.js"></script>
- <script src= "app/policyApp/controller/dashboard_Logging_Controller.js"></script>
- <script src= "app/policyApp/controller/dashboardController.js"></script>
+ <!---------------------------Angular Gridster-------------------------------->
+ <link rel="stylesheet" href="app/fusion/external/angular-gridster/dist/angular-gridster.min.css">
+ <link rel="stylesheet" href= "app/fusion/external/angular-bootstrap/ui-bootstrap-csp.css">
+ <script src= "app/fusion/external/javascript-detect-element-resize/jquery.resize.js"></script>
+ <script src= "app/fusion/external/angular-bootstrap/ui-bootstrap-tpls.min.js"></script>
+ <script src= "app/fusion/external/angular-gridster/dist/angular-gridster.min.js"></script>
+
+ <!---------------------------Policy App CSS-------------------------------->
+ <link rel="stylesheet" href="app/policyApp/CSS/font-awesome.min.css">
+ <link rel="stylesheet" href="app/policyApp/CSS/Notification/angular-csp.css">
+ <link rel="stylesheet" href="app/policyApp/CSS/Notification/angular-ui-notification.min.css">
+ <link rel="stylesheet" href="app/policyApp/CSS/lockdownIcon.css">
+ <link rel="stylesheet" href="app/policyApp/CSS/w3.css">
+ <link rel="stylesheet" href="app/policyApp/CSS/select.css">
+ <link rel="stylesheet" href="app/policyApp/policy-models/Editor/css/normalize.css">
+ <link rel="stylesheet" href="app/policyApp/policy-models/Editor/css/animations.css">
+ <link rel="stylesheet" href="app/policyApp/policy-models/Editor/css/dialogs.css">
+ <link rel="stylesheet" href="app/policyApp/policy-models/Editor/css/main.css">
+ <link rel="stylesheet" href="app/policyApp/policy-models/Editor/css/styles.css">
+ <script src= "app/policyApp/CSS/Notification/angular-ui-notification.min.js"></script>
+
+ <script src= "app/policyApp/CSS/UIGrid/ui-grid.js"></script>
+ <link rel="stylesheet" href="app/policyApp/CSS/UIGrid/ui-grid.css">
+
+ <script src= "app/fusion/external/ds2/js/appDS2.js"></script>
+
+ <script src= "app/fusion/scripts/DS2-services/headerServiceDS2.js"></script>
+ <script src= "app/fusion/scripts/DS2-services/leftMenuServiceDS2.js"></script>
+ <script src= "app/fusion/scripts/DS2-services/manifestService.js"></script>
+ <script src= "app/fusion/scripts/DS2-directives/footer.js"></script>
+ <script src= "app/fusion/scripts/DS2-directives/ds2Header.js"></script>
+ <script src= "app/fusion/scripts/DS2-directives/ds2LeftMenu.js"></script>
+ <script src="app/fusion/scripts/DS2-directives/b2b-leftnav-ext.js"></script>
+ <!-- /*<script src= "app/fusion/scripts/DS2-services/userInfoServiceDS2.js"></script>*/ -->
+ <script src= "app/policyApp/service/userInfoServiceDS2.js"></script>
+
+ <!---------------------------Policy Editor js-------------------------------->
+ <script src= "app/policyApp/policy-models/Editor/js/app.js"></script>
+ <script src= "app/policyApp/service/PolicyAppService.js"></script>
+ <script src= "app/policyApp/main/modalPopupController.js"></script>
+ <script src= "app/policyApp/service/modalService.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/ExportPolicyController.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/js/directives/directives.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/js/filters/filters.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/js/providers/config.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/js/entities/item.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/js/services/policynavigator.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/js/services/policyuploader.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/js/controllers/policyManager.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/js/controllers/policySearchManager.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/js/controllers/selector-controller.js"></script>
+ <script src= "app/policyApp/controller/policyController.js"></script>
+
+ <!---------------------------Policy Left Menu Controllers-------------------------------->
+ <script src= "app/policyApp/controller/policyAdminTabController.js"></script>
+ <script src= "app/policyApp/controller/dashboard_Logging_Controller.js"></script>
+ <script src= "app/policyApp/controller/dashboardController.js"></script>
<script src= "app/policyApp/controller/dashboardCRUDController.js"></script>
- <script src= "app/policyApp/controller/pdpController.js"></script>
- <script src= "app/policyApp/controller/pdpGroupPopUpController.js"></script>
- <script src= "app/policyApp/controller/DictionaryController.js"></script>
- <script src= "app/policyApp/controller/PolicyRolesController.js"></script>
- <script src= "app/policyApp/controller/PolicyAddScopeRoleController.js"></script>
- <script src= "app/policyApp/controller/AutoPushController.js"></script>
- <script src= "app/policyApp/controller/ImportDictionaryController.js"></script>
- <script src= "app/policyApp/controller/PDPTabController/AddorEditPdpInGroup.js"></script>
- <script src= "app/policyApp/controller/PDPTabController/PDPGroupStatusController.js"></script>
- <script src= "app/policyApp/controller/AutoPushTabController/RemovePDPGroupPoliciesController.js"></script>
-
- <!---------------------------Policy Creation resources-------------------------------->
- <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/BaseConfigPolicyController.js"></script>
- <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopFaultController.js"></script>
- <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopPMController.js"></script>
- <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/ActionPolicyController.js"></script>
- <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/DecisionPolicyController.js"></script>
- <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/FirewallPolicyController.js"></script>
- <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/DCAEMicroServicePolicyController.js"></script>
- <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/OptimizationPolicyController.js"></script>
- <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSRawPolicyController.js"></script>
- <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSParamPolicyController.js"></script>
-
- <!--------------------------Dictionary resources--------------------------------->
- <script src= "app/policyApp/controller/dictionaryGridController/actionPolicyDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/attributeDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/onapNameDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/BRMSParamDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/BRMSDependencyDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/BRMSControllerDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/CLPepOptionsDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/CLServiceDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/CLSiteDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/CLVarbindDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/CLVnfTypeDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/CLVsclActionDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/DecisionSettingsDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/DecisionRainyDayDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/DescriptiveScopeDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/EnforcerTypeDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/FWActionListDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/FWAddressGroupDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/FWParentListDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/FWPortListDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/FWPrefixListDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/FWProtocolListDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/FWSecurityZoneDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/FWServiceGroupDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/FWServiceListDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/FWTermListDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/FWTagListDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/FWTagPickerListDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/FWZoneDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/MSConfigNameDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/MSHeaderDefaultValuesDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/MSDcaeUUIDDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/MSLocationDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/MSModelDictionaryDataController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/MSModelDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/ModelAttributeDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/OptimizationModelDictGridController.js"></script>
-
- <script src= "app/policyApp/controller/dictionaryGridController/PSClosedLoopDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/PSGroupPolicyScopeDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/PSResourceDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/PSServiceDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/PSTypeDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/RiskTypeDictGridController.js"></script>
- <script src= "app/policyApp/controller/dictionaryGridController/SafePolicyWarningDictGridController.js"></script>
+ <script src= "app/policyApp/controller/pdpController.js"></script>
+ <script src= "app/policyApp/controller/pdpGroupPopUpController.js"></script>
+ <script src= "app/policyApp/controller/DictionaryController.js"></script>
+ <script src= "app/policyApp/controller/PolicyRolesController.js"></script>
+ <script src= "app/policyApp/controller/PolicyAddScopeRoleController.js"></script>
+ <script src= "app/policyApp/controller/AutoPushController.js"></script>
+ <script src= "app/policyApp/controller/ImportDictionaryController.js"></script>
+ <script src= "app/policyApp/controller/PDPTabController/AddorEditPdpInGroup.js"></script>
+ <script src= "app/policyApp/controller/PDPTabController/PDPGroupStatusController.js"></script>
+ <script src= "app/policyApp/controller/AutoPushTabController/RemovePDPGroupPoliciesController.js"></script>
+
+ <!---------------------------Policy Creation resources-------------------------------->
+ <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/BaseConfigPolicyController.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopFaultController.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopPMController.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/ActionPolicyController.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/DecisionPolicyController.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/FirewallPolicyController.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/DCAEMicroServicePolicyController.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/OptimizationPolicyController.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSRawPolicyController.js"></script>
+ <script src= "app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSParamPolicyController.js"></script>
+
+ <!--------------------------Dictionary resources--------------------------------->
+ <script src= "app/policyApp/controller/dictionaryGridController/actionPolicyDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/attributeDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/onapNameDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/BRMSParamDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/BRMSDependencyDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/BRMSControllerDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/CLPepOptionsDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/CLServiceDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/CLSiteDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/CLVarbindDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/CLVnfTypeDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/CLVsclActionDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/DecisionSettingsDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/DecisionRainyDayDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/DescriptiveScopeDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/EnforcerTypeDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/FWActionListDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/FWAddressGroupDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/FWParentListDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/FWPortListDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/FWPrefixListDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/FWProtocolListDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/FWSecurityZoneDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/FWServiceGroupDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/FWServiceListDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/FWTermListDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/FWTagListDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/FWTagPickerListDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/FWZoneDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/MSConfigNameDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/MSHeaderDefaultValuesDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/MSDcaeUUIDDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/MSLocationDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/MSModelDictionaryDataController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/MSModelDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/ModelAttributeDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/OptimizationModelDictGridController.js"></script>
+
+ <script src= "app/policyApp/controller/dictionaryGridController/PSClosedLoopDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/PSGroupPolicyScopeDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/PSResourceDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/PSServiceDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/PSTypeDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/RiskTypeDictGridController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryGridController/SafePolicyWarningDictGridController.js"></script>
+
+ <script src= "app/policyApp/controller/dictionaryController/actionPolicyDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/attributeDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/onapNameEditorController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/BRMSParamDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/BRMSDependencyDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/BRMSControllerDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/CLPepOptionsDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/CLServiceDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/CLSiteDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/CLVarbindDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/CLVnfTypeDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/CLVsclActionDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/DecisionSettingsDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/DecisionRainyDayDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/DescriptiveSearchDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/EnforcerDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/FWActionListDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/FWAddressGroupDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/FWParentListDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/FWPortListDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/FWPrefixListDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/FWProtocolListDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/FWSecurityZoneDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/FWServiceGroupDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/FWServiceListDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/FWTermListDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/FWTagListDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/FWTagPickerListDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/FWZoneDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/MSHeaderDefaultValuesDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/MSConfigNameDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/MSDictionaryController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/MSDcaeUUIDDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/MSLocationDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/MSModelsDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/ModelAttributeDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/OptimizationModelsDictController.js"></script>
+
+ <script src= "app/policyApp/controller/dictionaryController/PSClosedLoopDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/PSGroupPolicyScopeDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/PSResourceDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/PSServiceDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/PSTypeDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/RiskTypeDictController.js"></script>
+ <script src= "app/policyApp/controller/dictionaryController/SafePolicyWarningDictController.js"></script>
+
+ <script src= "app/policyApp/controller/ImportDictionaryController.js"></script>
+
+ <!---------------------------DS2 styles-------------------------------->
+ <link rel="stylesheet" href="app/policyApp/CSS/b2b-angular.css">
+ <link rel="stylesheet" href="app/fusion/external/b2b/css/b2b-angular/font_icons.css">
+ <link rel="stylesheet" href="app/policyApp/CSS/bootstrap/dist/css/bootstrap.min.css">
+
+ <!---------------------------DS2 ICONS-------------------------------->
+ <link rel="stylesheet" href="app/fusion/external/ds2/css/digital-ng-library/ionicons.css">
+ <link rel="stylesheet" href="app/fusion/styles/ecomp.css">
+ <link rel="stylesheet" href="app/fusion/external/angular-gridster/dist/angular-gridster.min.css">
- <script src= "app/policyApp/controller/dictionaryController/actionPolicyDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/attributeDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/onapNameEditorController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/BRMSParamDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/BRMSDependencyDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/BRMSControllerDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/CLPepOptionsDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/CLServiceDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/CLSiteDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/CLVarbindDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/CLVnfTypeDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/CLVsclActionDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/DecisionSettingsDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/DecisionRainyDayDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/DescriptiveSearchDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/EnforcerDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/FWActionListDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/FWAddressGroupDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/FWParentListDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/FWPortListDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/FWPrefixListDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/FWProtocolListDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/FWSecurityZoneDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/FWServiceGroupDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/FWServiceListDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/FWTermListDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/FWTagListDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/FWTagPickerListDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/FWZoneDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/MSHeaderDefaultValuesDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/MSConfigNameDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/MSDictionaryController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/MSDcaeUUIDDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/MSLocationDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/MSModelsDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/ModelAttributeDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/OptimizationModelsDictController.js"></script>
-
- <script src= "app/policyApp/controller/dictionaryController/PSClosedLoopDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/PSGroupPolicyScopeDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/PSResourceDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/PSServiceDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/PSTypeDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/RiskTypeDictController.js"></script>
- <script src= "app/policyApp/controller/dictionaryController/SafePolicyWarningDictController.js"></script>
-
- <script src= "app/policyApp/controller/ImportDictionaryController.js"></script>
-
- <!---------------------------DS2 styles-------------------------------->
- <link rel="stylesheet" href="app/policyApp/CSS/b2b-angular.css">
- <link rel="stylesheet" href="app/fusion/external/b2b/css/b2b-angular/font_icons.css">
- <link rel="stylesheet" href="app/policyApp/CSS/bootstrap/dist/css/bootstrap.min.css">
-
- <!---------------------------DS2 ICONS-------------------------------->
- <link rel="stylesheet" href="app/fusion/external/ds2/css/digital-ng-library/ionicons.css">
- <link rel="stylesheet" href="app/fusion/styles/ecomp.css">
- <link rel="stylesheet" href="app/fusion/external/angular-gridster/dist/angular-gridster.min.css">
-
</head>
- <body class="appBody" ng-app="abs" style="padding-top: 0px;">
- <div ds2-Header class="header-container" ></div>
- <div ds2-menu id="menuContainer" class="menu-container" ></div>
- <div ng-view id="rightContentProfile" class="content-container">
- </div>
- <!-- Dictionary Windows -->
- <div ng-include src="'app/policyApp/Windows/Dictionary/ActionPolicyDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/AttributeDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/BRMSParamDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/BRMSDependencyDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/BRMSControllerDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/CLPepOptionsDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/CLServiceTypeDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/CLSiteDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/CLVarbindDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/CLVnfTypeDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/CLVsclActionDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/DecisionSettingsDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/DecisionRainyDayDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/DescriptiveScopeDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/OnapNameDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/EnforcerTypeDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/FWActionListDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/FWAddressGroupDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/FWParentListDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/FWPortListDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/FWPrefixListDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/FWProtocolListDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/FWSecurityZoneDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/FWServiceGroupDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/FWServiceListDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/FWTag.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/FWTagPicker.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/FWTermListDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/FWZoneDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/MSConfigNameDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/MSHeaderDefaultValuesDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/MSDCAEUUIDDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/MSLocationDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/MSModelsDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/MSModelDictionaryData.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/ModelAttributeDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/OptimizationModelsDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/PSClosedLoopDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/PSGroupPolicyScopeDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/PSResourceDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/PSServiceDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/PSTypeDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/RiskTypeDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/RiskTypeDictionary.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Dictionary/SafePolicyWarningDictionary.html'"></div>
-
- <div ng-include src="'app/policyApp/Windows/PDPTabWindows/PdpStatusWindow.html'"></div>
- <div ng-include src="'app/policyApp/Windows/Edit_Roles_Window.html'"></div>
- <div ng-include src="'app/policyApp/Windows/PushtabWindow/removeGroupPoliciesWindow.html'"></div>
- <div ng-include src="'app/policyApp/Windows/popup_modal.html'"></div>
- <div ds2-Footer class="footer-container"></div>
- </body>
+ <body class="appBody" ng-app="abs" style="padding-top: 0px;">
+ <div ds2-Header class="header-container" ></div>
+ <div ds2-menu id="menuContainer" class="menu-container" ></div>
+ <div ng-view id="rightContentProfile" class="content-container">
+ </div>
+ <!-- Dictionary Windows -->
+ <div ng-include src="'app/policyApp/Windows/Dictionary/ActionPolicyDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/AttributeDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/BRMSParamDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/BRMSDependencyDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/BRMSControllerDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/CLPepOptionsDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/CLServiceTypeDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/CLSiteDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/CLVarbindDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/CLVnfTypeDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/CLVsclActionDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/DecisionSettingsDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/DecisionRainyDayDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/DescriptiveScopeDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/OnapNameDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/EnforcerTypeDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/FWActionListDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/FWAddressGroupDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/FWParentListDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/FWPortListDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/FWPrefixListDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/FWProtocolListDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/FWSecurityZoneDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/FWServiceGroupDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/FWServiceListDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/FWTag.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/FWTagPicker.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/FWTermListDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/FWZoneDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/MSConfigNameDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/MSHeaderDefaultValuesDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/MSDCAEUUIDDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/MSLocationDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/MSModelsDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/MSModelDictionaryData.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/ModelAttributeDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/OptimizationModelsDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/PSClosedLoopDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/PSGroupPolicyScopeDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/PSResourceDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/PSServiceDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/PSTypeDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/RiskTypeDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/RiskTypeDictionary.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Dictionary/SafePolicyWarningDictionary.html'"></div>
+
+ <div ng-include src="'app/policyApp/Windows/PDPTabWindows/PdpStatusWindow.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/Edit_Roles_Window.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/PushtabWindow/removeGroupPoliciesWindow.html'"></div>
+ <div ng-include src="'app/policyApp/Windows/popup_modal.html'"></div>
+ <div ds2-Footer class="footer-container"></div>
+ </body>
</html>
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ActionPolicyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ActionPolicyController.js
index a9097d559..80c11463f 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ActionPolicyController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ActionPolicyController.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.
@@ -28,7 +28,7 @@ app.controller('actionPolicyController', ['$scope', 'PolicyAppService', 'policyN
$scope.temp.policy = {
policyType : "Action"
}
- };
+ }
$scope.refresh = function(){
if($scope.refreshCheck){
@@ -36,7 +36,7 @@ app.controller('actionPolicyController', ['$scope', 'PolicyAppService', 'policyN
}
$scope.modal('createNewPolicy', true);
$scope.temp.policy = "";
- };
+ }
$scope.modal = function(id, hide) {
return $('#' + id).modal(hide ? 'hide' : 'show');
@@ -71,13 +71,6 @@ app.controller('actionPolicyController', ['$scope', 'PolicyAppService', 'policyN
}, function (error) {
console.log("failed");
});
-
- function extend(obj, src) {
- for (var key in src) {
- if (src.hasOwnProperty(key)) obj[key] = src[key];
- }
- return obj;
- }
$scope.saveActionPolicy = function(policy){
if(policy.itemContent != undefined){
@@ -191,4 +184,4 @@ app.controller('actionPolicyController', ['$scope', 'PolicyAppService', 'policyN
$scope.temp.policy.ruleAlgorithmschoices.splice(lastItem);
};
-}]); \ No newline at end of file
+}]);
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSParamPolicyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSParamPolicyController.js
index 22511c5a7..35fb3cb81 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSParamPolicyController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSParamPolicyController.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.
@@ -17,7 +17,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-angular.module('abs').controller('brmsParamPolicyController', ['$scope', '$window', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', function ($scope, $window, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) {
+angular.module('abs').controller('brmsParamPolicyController',
+ ['$scope', '$window', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification',
+ function ($scope, $window, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) {
$("#dialog").hide();
$scope.policyNavigator;
@@ -25,18 +27,18 @@ angular.module('abs').controller('brmsParamPolicyController', ['$scope', '$windo
$scope.refreshCheck = false;
if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
- $scope.temp.policy = {
- policyType : "Config",
- configPolicyType : "BRMS_Param"
- }
- };
+ $scope.temp.policy = {
+ policyType : "Config",
+ configPolicyType : "BRMS_Param"
+ }
+ }
$scope.refresh = function(){
- if($scope.refreshCheck){
- $scope.policyNavigator.refresh();
- }
- $scope.modal('createNewPolicy', true);
- $scope.temp.policy = "";
+ if($scope.refreshCheck){
+ $scope.policyNavigator.refresh();
+ }
+ $scope.modal('createNewPolicy', true);
+ $scope.temp.policy = "";
};
$scope.modal = function(id, hide) {
@@ -44,66 +46,49 @@ angular.module('abs').controller('brmsParamPolicyController', ['$scope', '$windo
};
$('#ttlDate').datepicker({
- dateFormat: 'dd/mm/yy',
- changeMonth: true,
- changeYear: true,
- onSelect: function(date) {
- angular.element($('#ttlDate')).triggerHandler('input');
- }
+ dateFormat: 'dd/mm/yy',
+ changeMonth: true,
+ changeYear: true,
+ onSelect: function(date) {
+ angular.element($('#ttlDate')).triggerHandler('input');
+ }
});
$scope.validateSuccess = true;
var readValue = $scope.temp.policy.readOnly;
if(readValue){
- $scope.validateSuccess = false;
+ $scope.validateSuccess = false;
}
PolicyAppService.getData('getDictionary/get_BRMSControllerDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.brmsControllerDatas = JSON.parse($scope.data.brmsControllerDictionaryDatas);
- console.log($scope.brmsControllerDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.brmsControllerDatas = JSON.parse($scope.data.brmsControllerDictionaryDatas);
});
PolicyAppService.getData('getDictionary/get_BRMSDependencyDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.brmsDependencyDatas = JSON.parse($scope.data.brmsDependencyDictionaryDatas);
- console.log($scope.brmsDependencyDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.brmsDependencyDatas = JSON.parse($scope.data.brmsDependencyDictionaryDatas);
});
PolicyAppService.getData('getDictionary/get_BRMSParamDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.brmsParamDictionaryDatas = JSON.parse($scope.data.brmsParamDictionaryDatas);
- console.log($scope.brmsParamDictionaryDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.brmsParamDictionaryDatas = JSON.parse($scope.data.brmsParamDictionaryDatas);
});
PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
- console.log($scope.riskTypeDictionaryDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
});
$scope.temp.policy.dynamicLayoutMap = {};
$scope.addDataToFields = function(ruleName){
- console.log(ruleName);
if(ruleName != null){
- var uuu = "policyController/getBRMSTemplateData.htm";
- var postData={policyData: ruleName};
+ var uuu = "policyController/getBRMSTemplateData.htm";
+ var postData={policyData: ruleName};
$.ajax({
type : 'POST',
url : uuu,
@@ -112,12 +97,11 @@ angular.module('abs').controller('brmsParamPolicyController', ['$scope', '$windo
data: JSON.stringify(postData),
success : function(data){
$scope.$apply(function(){
- $scope.temp.policy.dynamicLayoutMap = data.policyData;
+ $scope.temp.policy.dynamicLayoutMap = data.policyData;
});
- console.log( $scope.temp.policy.dynamicLayoutMap);
},
error : function(data){
- alert("Error While Retriving the Template Layout Pattren.");
+ Notification.error("Error While Retriving the Template Layout Pattren.");
}
});
}
@@ -126,7 +110,6 @@ angular.module('abs').controller('brmsParamPolicyController', ['$scope', '$windo
$scope.showbrmsrule = true;
$scope.ShowRule = function(policy){
- console.log(policy);
var uuu = "policyController/ViewBRMSParamPolicyRule.htm";
var postData={policyData: policy};
$.ajax({
@@ -136,30 +119,30 @@ angular.module('abs').controller('brmsParamPolicyController', ['$scope', '$windo
contentType: 'application/json',
data: JSON.stringify(postData),
success : function(data){
- $scope.showbrmsrule = false;
- $scope.validateSuccess = true;
+ $scope.showbrmsrule = false;
+ $scope.validateSuccess = true;
$scope.$apply(function(){
- $scope.datarule = data.policyData;
+ $scope.datarule = data.policyData;
});
},
error : function(data){
- Notification.error("Error Occured while Showing Rule.");
+ Notification.error("Error Occured while Showing Rule.");
}
});
};
$scope.hideRule = function(){
- $scope.showbrmsrule = true;
- $scope.validateSuccess = false;
- $scope.apply();
+ $scope.showbrmsrule = true;
+ $scope.validateSuccess = false;
+ $scope.apply();
};
$scope.saveBrmsParamPolicy = function(policy){
- if(policy.itemContent != undefined){
- $scope.refreshCheck = true;
- $scope.policyNavigator = policy.itemContent;
- policy.itemContent = "";
- }
+ if(policy.itemContent != undefined){
+ $scope.refreshCheck = true;
+ $scope.policyNavigator = policy.itemContent;
+ policy.itemContent = "";
+ }
$scope.savebutton = false;
var uuu = "policycreation/save_policy";
var postData={policyData: policy};
@@ -173,83 +156,73 @@ angular.module('abs').controller('brmsParamPolicyController', ['$scope', '$windo
$scope.$apply(function(){
$scope.data=data.policyData;
if($scope.data == 'success'){
- $scope.temp.policy.readOnly = 'true';
- $scope.safetyChecker = data.policyData.split("#")[2];
- if ($scope.safetyChecker!=undefined) {
- Notification.success($scope.safetyChecker);
- }
- Notification.success("Policy Saved Successfully.");
+ $scope.temp.policy.readOnly = 'true';
+ $scope.safetyChecker = data.policyData.split("#")[2];
+ if ($scope.safetyChecker!=undefined) {
+ Notification.success($scope.safetyChecker);
+ }
+ Notification.success("Policy Saved Successfully.");
}else if ($scope.data == 'PolicyExists'){
- $scope.savebutton = true;
- Notification.error("Policy Already Exists with Same Name in Scope.");
- }
+ $scope.savebutton = true;
+ Notification.error("Policy Already Exists with Same Name in Scope.");
+ }
});
- console.log($scope.data);
},
error : function(data){
- Notification.error("Error Occured while saving Policy.");
- $scope.savebutton = true;
+ Notification.error("Error Occured while saving Policy.");
+ $scope.savebutton = true;
}
});
};
$scope.validatePolicy = function(policy){
- console.log(policy);
- document.getElementById("validate").innerHTML = "";
+ document.getElementById("validate").innerHTML = "";
var uuu = "policyController/validate_policy.htm";
- var postData={policyData: policy};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.validateData = data.data.replace(/\"/g, "");
- $scope.data=data.data.substring(1,8);
- var size = data.data.length;
- if($scope.data == 'success'){
- Notification.success("Validation Success.");
- $scope.savebutton = false;
- if (size > 18){
- var displayWarning = data.data.substring(19,size);
- document.getElementById("validate").innerHTML = "Safe Policy Warning Message : "+displayWarning;
- document.getElementById("validate").style.color = "white";
- document.getElementById("validate").style.backgroundColor = "skyblue";
- }
- $scope.validateSuccess = false;
- }else{
- Notification.error("Validation Failed.");
- document.getElementById("validate").innerHTML = $scope.validateData;
- document.getElementById("validate").style.color = "white";
- document.getElementById("validate").style.backgroundColor = "red";
- $scope.savebutton = true;
- }
-
- });
- console.log($scope.data);
- },
- error : function(data){
- Notification.error("Validation Failed.");
- $scope.savebutton = true;
- }
- });
+ var postData={policyData: policy};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.validateData = data.data.replace(/\"/g, "");
+ $scope.data=data.data.substring(1,8);
+ var size = data.data.length;
+ if($scope.data == 'success'){
+ Notification.success("Validation Success.");
+ $scope.savebutton = false;
+ if (size > 18){
+ var displayWarning = data.data.substring(19,size);
+ document.getElementById("validate").innerHTML = "Safe Policy Warning Message : "+displayWarning;
+ document.getElementById("validate").style.color = "white";
+ document.getElementById("validate").style.backgroundColor = "skyblue";
+ }
+ $scope.validateSuccess = false;
+ }else{
+ Notification.error("Validation Failed.");
+ document.getElementById("validate").innerHTML = $scope.validateData;
+ document.getElementById("validate").style.color = "white";
+ document.getElementById("validate").style.backgroundColor = "red";
+ $scope.savebutton = true;
+ }
+
+ });
+ },
+ error : function(data){
+ Notification.error("Validation Failed.");
+ $scope.savebutton = true;
+ }
+ });
};
- function extend(obj, src) {
- for (var key in src) {
- if (src.hasOwnProperty(key)) obj[key] = src[key];
- }
- return obj;
- }
-
if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
- $scope.temp.policy.attributes = [];
+ $scope.temp.policy.attributes = [];
}else{
- if($scope.temp.policy.attributes.length == 0){
- $scope.temp.policy.attributes = [];
- }
+ if($scope.temp.policy.attributes.length == 0){
+ $scope.temp.policy.attributes = [];
+ }
}
$scope.attributeDatas = [{"attributes" : $scope.temp.policy.attributes}];
@@ -261,4 +234,4 @@ angular.module('abs').controller('brmsParamPolicyController', ['$scope', '$windo
var lastItem = $scope.temp.policy.attributes.length-1;
$scope.temp.policy.attributes.splice(lastItem);
};
-}]); \ No newline at end of file
+}]);
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSRawPolicyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSRawPolicyController.js
index 6061b1ef8..695cb423d 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSRawPolicyController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BRMSRawPolicyController.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.
@@ -17,7 +17,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-angular.module('abs').controller('brmsRawPolicyController', ['$scope', '$window', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', function ($scope, $window, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) {
+angular.module('abs').controller('brmsRawPolicyController',
+ ['$scope', '$window', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification',
+ function ($scope, $window, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) {
$("#dialog").hide();
$scope.policyNavigator;
@@ -25,18 +27,18 @@ angular.module('abs').controller('brmsRawPolicyController', ['$scope', '$window'
$scope.refreshCheck = false;
if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
- $scope.temp.policy = {
- policyType : "Config",
- configPolicyType : "BRMS_Raw"
- }
- };
+ $scope.temp.policy = {
+ policyType : "Config",
+ configPolicyType : "BRMS_Raw"
+ }
+ }
$scope.refresh = function(){
- if($scope.refreshCheck){
- $scope.policyNavigator.refresh();
- }
- $scope.modal('createNewPolicy', true);
- $scope.temp.policy = "";
+ if($scope.refreshCheck){
+ $scope.policyNavigator.refresh();
+ }
+ $scope.modal('createNewPolicy', true);
+ $scope.temp.policy = "";
};
$scope.modal = function(id, hide) {
@@ -44,134 +46,112 @@ angular.module('abs').controller('brmsRawPolicyController', ['$scope', '$window'
};
$('#ttlDate').datepicker({
- dateFormat: 'dd/mm/yy',
- changeMonth: true,
- changeYear: true,
- onSelect: function(date) {
- angular.element($('#ttlDate')).triggerHandler('input');
- }
+ dateFormat: 'dd/mm/yy',
+ changeMonth: true,
+ changeYear: true,
+ onSelect: function(date) {
+ angular.element($('#ttlDate')).triggerHandler('input');
+ }
});
PolicyAppService.getData('getDictionary/get_BRMSControllerDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.brmsControllerDatas = JSON.parse($scope.data.brmsControllerDictionaryDatas);
- console.log($scope.brmsControllerDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.brmsControllerDatas = JSON.parse($scope.data.brmsControllerDictionaryDatas);
});
PolicyAppService.getData('getDictionary/get_BRMSDependencyDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.brmsDependencyDatas = JSON.parse($scope.data.brmsDependencyDictionaryDatas);
- console.log($scope.brmsDependencyDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.brmsDependencyDatas = JSON.parse($scope.data.brmsDependencyDictionaryDatas);
});
PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
- console.log($scope.riskTypeDictionaryDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
});
$scope.saveBrmsRawPolicy = function(policy){
- if(policy.itemContent != undefined){
- $scope.refreshCheck = true;
- $scope.policyNavigator = policy.itemContent;
- policy.itemContent = "";
- }
+ if(policy.itemContent != undefined){
+ $scope.refreshCheck = true;
+ $scope.policyNavigator = policy.itemContent;
+ policy.itemContent = "";
+ }
$scope.savebutton = false;
var uuu = "policycreation/save_policy";
- var postData={policyData: policy};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.data=data.policyData;
- if($scope.data == 'success'){
- $scope.temp.policy.readOnly = 'true';
- Notification.success("Policy Saved Successfully.");
- }else if ($scope.data == 'PolicyExists'){
- $scope.savebutton = true;
- Notification.error("Policy Already Exists with Same Name in Scope.");
- }
- });
- console.log($scope.data);
- },
- error : function(data){
- Notification.error("Error Occured while saving Policy.");
- $scope.savebutton = true;
- }
- });
+ var postData={policyData: policy};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.data=data.policyData;
+ if($scope.data == 'success'){
+ $scope.temp.policy.readOnly = 'true';
+ Notification.success("Policy Saved Successfully.");
+ }else if ($scope.data == 'PolicyExists'){
+ $scope.savebutton = true;
+ Notification.error("Policy Already Exists with Same Name in Scope.");
+ }
+ });
+ },
+ error : function(data){
+ Notification.error("Error Occured while saving Policy.");
+ $scope.savebutton = true;
+ }
+ });
};
$scope.validatePolicy = function(policy){
- console.log(policy);
- document.getElementById("validate").innerHTML = "";
+ document.getElementById("validate").innerHTML = "";
var uuu = "policyController/validate_policy.htm";
- var postData={policyData: policy};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.validateData = data.data.replace(/\"/g, "");
- $scope.data=data.data.substring(1,8);
- var size = data.data.length;
- if($scope.data == 'success'){
- Notification.success("Validation Success.");
- $scope.savebutton = false;
- if (size > 18){
- var displayWarning = data.data.substring(19,size);
- document.getElementById("validate").innerHTML = "Safe Policy Warning Message : "+displayWarning;
- document.getElementById("validate").style.color = "white";
- document.getElementById("validate").style.backgroundColor = "skyblue";
- }
- }else{
- Notification.error("Validation Failed.");
- document.getElementById("validate").innerHTML = $scope.validateData;
- document.getElementById("validate").style.color = "white";
- document.getElementById("validate").style.backgroundColor = "red";
- $scope.savebutton = true;
- }
-
- });
- console.log($scope.data);
- },
- error : function(data){
- Notification.error("Validation Failed.");
- }
- });
+ var postData={policyData: policy};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.validateData = data.data.replace(/\"/g, "");
+ $scope.data=data.data.substring(1,8);
+ var size = data.data.length;
+ if($scope.data == 'success'){
+ Notification.success("Validation Success.");
+ $scope.savebutton = false;
+ if (size > 18){
+ var displayWarning = data.data.substring(19,size);
+ document.getElementById("validate").innerHTML = "Safe Policy Warning Message : "+displayWarning;
+ document.getElementById("validate").style.color = "white";
+ document.getElementById("validate").style.backgroundColor = "skyblue";
+ }
+ }else{
+ Notification.error("Validation Failed.");
+ document.getElementById("validate").innerHTML = $scope.validateData;
+ document.getElementById("validate").style.color = "white";
+ document.getElementById("validate").style.backgroundColor = "red";
+ $scope.savebutton = true;
+ }
+
+ });
+ },
+ error : function(data){
+ Notification.error("Validation Failed.");
+ }
+ });
};
- function extend(obj, src) {
- for (var key in src) {
- if (src.hasOwnProperty(key)) obj[key] = src[key];
- }
- return obj;
- }
-
if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
- $scope.temp.policy.attributes = [];
+ $scope.temp.policy.attributes = [];
}else{
- if($scope.temp.policy.attributes.length == 0){
- $scope.temp.policy.attributes = [];
- }
+ if($scope.temp.policy.attributes.length == 0){
+ $scope.temp.policy.attributes = [];
+ }
}
$scope.attributeDatas = [{"attributes" : $scope.temp.policy.attributes}];
$scope.addNewChoice = function() {
@@ -182,4 +162,4 @@ angular.module('abs').controller('brmsRawPolicyController', ['$scope', '$window'
var lastItem = $scope.temp.policy.attributes.length-1;
$scope.temp.policy.attributes.splice(lastItem);
};
-}]); \ No newline at end of file
+}]);
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BaseConfigPolicyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BaseConfigPolicyController.js
index 02e10bddd..f950e7434 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BaseConfigPolicyController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/BaseConfigPolicyController.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,7 +30,7 @@ app.controller('baseConfigController', ['$scope', 'PolicyAppService', 'policyNav
policyType : "Config",
configPolicyType : "Base"
}
- };
+ }
$scope.refresh = function(){
if($scope.refreshCheck){
@@ -177,4 +177,4 @@ app.controller('baseConfigController', ['$scope', 'PolicyAppService', 'policyNav
var lastItem = $scope.temp.policy.attributes.length-1;
$scope.temp.policy.attributes.splice(lastItem);
};
-}]); \ No newline at end of file
+}]);
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopFaultController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopFaultController.js
index ebc9001ab..a8368a05e 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopFaultController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopFaultController.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.
@@ -17,26 +17,28 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-angular.module("abs").controller('clFaultController', ['$scope', '$window', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', function($scope, $window, PolicyAppService, PolicyNavigator, modalService, $modal, Notification){
- $("#dialog").hide();
+angular.module("abs").controller('clFaultController',
+ ['$scope', '$window', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification',
+ function($scope, $window, PolicyAppService, PolicyNavigator, modalService, $modal, Notification){
+ $("#dialog").hide();
- $scope.policyNavigator;
- $scope.savebutton = true;
- $scope.refreshCheck = false;
+ $scope.policyNavigator;
+ $scope.savebutton = true;
+ $scope.refreshCheck = false;
- if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
- $scope.temp.policy = {
- policyType : "Config",
- configPolicyType : "ClosedLoop_Fault"
- }
- };
+ if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
+ $scope.temp.policy = {
+ policyType : "Config",
+ configPolicyType : "ClosedLoop_Fault"
+ }
+ }
$scope.refresh = function(){
- if($scope.refreshCheck){
- $scope.policyNavigator.refresh();
- }
- $scope.modal('createNewPolicy', true);
- $scope.temp.policy = "";
+ if($scope.refreshCheck){
+ $scope.policyNavigator.refresh();
+ }
+ $scope.modal('createNewPolicy', true);
+ $scope.temp.policy = "";
};
$scope.modal = function(id, hide) {
@@ -44,784 +46,749 @@ angular.module("abs").controller('clFaultController', ['$scope', '$window', 'Pol
};
$('#ttlDate').datepicker({
- dateFormat: 'dd/mm/yy',
- changeMonth: true,
- changeYear: true,
- onSelect: function(date) {
- angular.element($('#ttlDate')).triggerHandler('input');
- }
+ dateFormat: 'dd/mm/yy',
+ changeMonth: true,
+ changeYear: true,
+ onSelect: function(date) {
+ angular.element($('#ttlDate')).triggerHandler('input');
+ }
});
-
- if($scope.temp.policy.triggerTrapSignatures == undefined){
- $scope.temp.policy.triggerTrapSignatures = [];
- $scope.temp.policy.triggerfaultSignatures = [];
- }
- var trapCollection = [];
- var faultCollection = [];
- if($scope.varbindDictionaryDatas == undefined){
- $scope.varbindDictionaryDatas = [];
- }
-
- $scope.init = function(data){
- if(data != undefined && $scope.temp.policy.triggerTrapSignatures.length == 0){
- $scope.jsonData = data;
- if($scope.jsonData.triggerSignaturesUsedForUI != null){
- if($scope.jsonData.triggerSignaturesUsedForUI.signatures != null){
- $scope.temp.policy.triggerTrapSignatures = {Trap1 : [], Trap2 : [], Trap3 : [], Trap4 : [], Trap5 : [], Trap6 : []};
- var splitTraps = $scope.jsonData.triggerSignaturesUsedForUI.signatures.split("#!?!");
- if(splitTraps.length > 1){
- $scope.triggerdisabled = false;
- var indexId = "Trap1";
- trapCollection.push(indexId);
- $scope.temp.policy.triggerTrapSignatures[indexId.replace(/['"]+/g, '')] = [];
- $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+1});
- var splitTrap1 = splitTraps[0];
- var splitEachTrap = splitTrap1.split("#!");
- for(i = 0 ; i < splitEachTrap.length; i++){
- var splitEachRow = splitEachTrap[i].split("@!");
- var count = i +1;
- if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
- var notBox = splitEachRow[0];
- var trigger1 = splitEachRow[1];
- var operatorBox = splitEachRow[2];
- var trigger2 = splitEachRow[3];
- }else{
- var notBox = '';
- var trigger1 = splitEachRow[0];
- var operatorBox = splitEachRow[1];
- var trigger2 = splitEachRow[2];
- }
- $scope.varbindDictionaryDatas.push('A'+count);
- $scope.temp.policy.triggerTrapSignatures["Trap1"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
- }
- }
- if(splitTraps.length > 2){
- var indexId = "Trap2";
- trapCollection.push(indexId);
- $scope.temp.policy.triggerTrapSignatures[indexId.replace(/['"]+/g, '')] = [];
- $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+2});
- var splitTrap1 = splitTraps[1];
- var splitEachTrap = splitTrap1.split("#!");
- for(i = 0 ; i < splitEachTrap.length; i++){
- var splitEachRow = splitEachTrap[i].split("@!");
- var count = i +1;
- if(splitEachRow[0] == 'NOT' || splitEachRow[0] == ''){
- var notBox = splitEachRow[0];
- var trigger1 = splitEachRow[1];
- var operatorBox = splitEachRow[2];
- var trigger2 = splitEachRow[3];
- }else{
- var notBox = '';
- var trigger1 = splitEachRow[0];
- var operatorBox = splitEachRow[1];
- var trigger2 = splitEachRow[2];
- }
- $scope.varbindDictionaryDatas.push('A'+count);
- $scope.temp.policy.triggerTrapSignatures["Trap2"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
- }
- }
- if(splitTraps.length > 3){
- var indexId = "Trap3";
- trapCollection.push(indexId);
- $scope.temp.policy.triggerTrapSignatures[indexId.replace(/['"]+/g, '')] = [];
- $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+3});
- var splitTrap1 = splitTraps[2];
- var splitEachTrap = splitTrap1.split("#!");
- for(i = 0 ; i < splitEachTrap.length; i++){
- var splitEachRow = splitEachTrap[i].split("@!");
- var count = i +1;
- if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
- var notBox = splitEachRow[0];
- var trigger1 = splitEachRow[1];
- var operatorBox = splitEachRow[2];
- var trigger2 = splitEachRow[3];
- }else{
- var notBox = '';
- var trigger1 = splitEachRow[0];
- var operatorBox = splitEachRow[1];
- var trigger2 = splitEachRow[2];
- }
- $scope.varbindDictionaryDatas.push('A'+count);
- $scope.temp.policy.triggerTrapSignatures["Trap3"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
- }
- }
- if(splitTraps.length > 4){
- var indexId = "Trap4";
- trapCollection.push(indexId);
- $scope.temp.policy.triggerTrapSignatures[indexId.replace(/['"]+/g, '')] = [];
- $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+4});
- var splitTrap1 = splitTraps[3];
- var splitEachTrap = splitTrap1.split("#!");
- for(i = 0 ; i < splitEachTrap.length; i++){
- var splitEachRow = splitEachTrap[i].split("@!");
- var count = i +1;
- if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
- var notBox = splitEachRow[0];
- var trigger1 = splitEachRow[1];
- var operatorBox = splitEachRow[2];
- var trigger2 = splitEachRow[3];
- }else{
- var notBox = '';
- var trigger1 = splitEachRow[0];
- var operatorBox = splitEachRow[1];
- var trigger2 = splitEachRow[2];
- }
- $scope.varbindDictionaryDatas.push('A'+count);
- $scope.temp.policy.triggerTrapSignatures["Trap4"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
- }
- }
- if(splitTraps.length > 5){
- var indexId = "Trap5";
- trapCollection.push(indexId);
- $scope.temp.policy.triggerTrapSignatures[indexId.replace(/['"]+/g, '')] = [];
- $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+5});
- var splitTrap1 = splitTraps[4];
- var splitEachTrap = splitTrap1.split("#!");
- for(i = 0 ; i < splitEachTrap.length; i++){
- var splitEachRow = splitEachTrap[i].split("@!");
- var count = i +1;
- if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
- var notBox = splitEachRow[0];
- var trigger1 = splitEachRow[1];
- var operatorBox = splitEachRow[2];
- var trigger2 = splitEachRow[3];
- }else{
- var notBox = '';
- var trigger1 = splitEachRow[0];
- var operatorBox = splitEachRow[1];
- var trigger2 = splitEachRow[2];
- }
- $scope.varbindDictionaryDatas.push('A'+count);
- $scope.temp.policy.triggerTrapSignatures["Trap5"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
- }
- }
- if(splitTraps.length > 6){
- var indexId = "Trap6";
- trapCollection.push(indexId);
- $scope.temp.policy.triggerTrapSignatures[indexId.replace(/['"]+/g, '')] = [];
- $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+6});
- var splitTrap1 = splitTraps[5];
- var splitEachTrap = splitTrap1.split("#!");
- for(i = 0 ; i < splitEachTrap.length; i++){
- var splitEachRow = splitEachTrap[i].split("@!");
- var count = i +1;
- if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
- var notBox = splitEachRow[0];
- var trigger1 = splitEachRow[1];
- var operatorBox = splitEachRow[2];
- var trigger2 = splitEachRow[3];
- }else{
- var notBox = '';
- var trigger1 = splitEachRow[0];
- var operatorBox = splitEachRow[1];
- var trigger2 = splitEachRow[2];
- }
- $scope.varbindDictionaryDatas.push('A'+count);
- $scope.temp.policy.triggerTrapSignatures["Trap6"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
- }
- }
- if($scope.jsonData.triggerSignaturesUsedForUI.connectSignatures != null){
- var splitConnectTraps = $scope.jsonData.triggerSignaturesUsedForUI.connectSignatures.split("#!?!");
- for(i=0; i < splitConnectTraps.length; i++){
- if(splitConnectTraps[i] != ""){
- var newConnectTrapItemNo = i+1;
- var connects = splitConnectTraps[i].split("@!");
- if(connects[0] == 'NOT' || connects[0] ==''){
- var notBox = connects[0];
- var connectTrap1 = connects[1];
- var trapCount1 = connects[2];
- var operatorBox = connects[3];
- var connectTrap2 = connects[4];
- var trapCount2 = connects[5];
- }else{
- var notBox = '';
- var connectTrap1 = connects[0];
- var trapCount1 = connects[1];
- var operatorBox = connects[2];
- var connectTrap2 = connects[3];
- var trapCount2 = connects[4];
- }
- $scope.temp.policy.connecttriggerSignatures.push({'id':'C'+newConnectTrapItemNo,'notBox' : notBox , 'connectTrap1': connectTrap1,'trapCount1' : trapCount1,
- 'operatorBox': operatorBox, 'connectTrap2': connectTrap2,'trapCount2' : trapCount2});
- }
- }
- }
- }
- }
- if($scope.jsonData.verificationSignaturesUsedForUI != null){
- if($scope.jsonData.verificationSignaturesUsedForUI.signatures != null){
- $scope.temp.policy.triggerfaultSignatures = {Fault1 : [], Fault2 : [], Fault3 : [], Fault4 : [], Fault5 : [], Fault6 : []};
- var splitTraps = $scope.jsonData.verificationSignaturesUsedForUI.signatures.split("#!?!");
- if(splitTraps.length > 1){
- $scope.verificationdisabled = false;
- var indexId = "Fault1";
- faultCollection.push(indexId);
- $scope.temp.policy.triggerfaultSignatures[indexId.replace(/['"]+/g, '')] = [];
- $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+1});
- var splitTrap1 = splitTraps[0];
- var splitEachTrap = splitTrap1.split("#!");
- for(i = 0 ; i < splitEachTrap.length; i++){
- var splitEachRow = splitEachTrap[i].split("@!");
- var count = i +1;
- if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
- var notBox = splitEachRow[0];
- var trigger1 = splitEachRow[1];
- var operatorBox = splitEachRow[2];
- var trigger2 = splitEachRow[3];
- }else{
- var notBox = '';
- var trigger1 = splitEachRow[0];
- var operatorBox = splitEachRow[1];
- var trigger2 = splitEachRow[2];
- }
- $scope.varbindDictionaryDatas.push('A'+count);
- $scope.temp.policy.triggerfaultSignatures["Fault1"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
- }
- }
- if(splitTraps.length > 2){
- var indexId = "Fault2";
- faultCollection.push(indexId);
- $scope.temp.policy.triggerfaultSignatures[indexId.replace(/['"]+/g, '')] = [];
- $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+2});
- var splitTrap1 = splitTraps[1];
- var splitEachTrap = splitTrap1.split("#!");
- for(i = 0 ; i < splitEachTrap.length; i++){
- var splitEachRow = splitEachTrap[i].split("@!");
- var count = i +1;
- if(splitEachRow[0] == 'NOT' || splitEachRow[0] == ''){
- var notBox = splitEachRow[0];
- var trigger1 = splitEachRow[1];
- var operatorBox = splitEachRow[2];
- var trigger2 = splitEachRow[3];
- }else{
- var notBox = '';
- var trigger1 = splitEachRow[0];
- var operatorBox = splitEachRow[1];
- var trigger2 = splitEachRow[2];
- }
- $scope.varbindDictionaryDatas.push('A'+count);
- $scope.temp.policy.triggerfaultSignatures["Fault2"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
- }
- }
- if(splitTraps.length > 3){
- var indexId = "Fault3";
- faultCollection.push(indexId);
- $scope.temp.policy.triggerfaultSignatures[indexId.replace(/['"]+/g, '')] = [];
- $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+3});
- var splitTrap1 = splitTraps[2];
- var splitEachTrap = splitTrap1.split("#!");
- for(i = 0 ; i < splitEachTrap.length; i++){
- var splitEachRow = splitEachTrap[i].split("@!");
- var count = i +1;
- if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
- var notBox = splitEachRow[0];
- var trigger1 = splitEachRow[1];
- var operatorBox = splitEachRow[2];
- var trigger2 = splitEachRow[3];
- }else{
- var notBox = '';
- var trigger1 = splitEachRow[0];
- var operatorBox = splitEachRow[1];
- var trigger2 = splitEachRow[2];
- }
- $scope.varbindDictionaryDatas.push('A'+count);
- $scope.temp.policy.triggerfaultSignatures["Fault3"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
- }
- }
- if(splitTraps.length > 4){
- var indexId = "Fault4";
- faultCollection.push(indexId);
- $scope.temp.policy.triggerfaultSignatures[indexId.replace(/['"]+/g, '')] = [];
- $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+4});
- var splitTrap1 = splitTraps[3];
- var splitEachTrap = splitTrap1.split("#!");
- for(i = 0 ; i < splitEachTrap.length; i++){
- var splitEachRow = splitEachTrap[i].split("@!");
- var count = i +1;
- if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
- var notBox = splitEachRow[0];
- var trigger1 = splitEachRow[1];
- var operatorBox = splitEachRow[2];
- var trigger2 = splitEachRow[3];
- }else{
- var notBox = '';
- var trigger1 = splitEachRow[0];
- var operatorBox = splitEachRow[1];
- var trigger2 = splitEachRow[2];
- }
- $scope.varbindDictionaryDatas.push('A'+count);
- $scope.temp.policy.triggerfaultSignatures["Fault4"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
- }
- }
- if(splitTraps.length > 5){
- var indexId = "Fault5";
- faultCollection.push(indexId);
- $scope.temp.policy.triggerfaultSignatures[indexId.replace(/['"]+/g, '')] = [];
- $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+5});
- var splitTrap1 = splitTraps[4];
- var splitEachTrap = splitTrap1.split("#!");
- for(i = 0 ; i < splitEachTrap.length; i++){
- var splitEachRow = splitEachTrap[i].split("@!");
- var count = i +1;
- if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
- var notBox = splitEachRow[0];
- var trigger1 = splitEachRow[1];
- var operatorBox = splitEachRow[2];
- var trigger2 = splitEachRow[3];
- }else{
- var notBox = '';
- var trigger1 = splitEachRow[0];
- var operatorBox = splitEachRow[1];
- var trigger2 = splitEachRow[2];
- }
- $scope.varbindDictionaryDatas.push('A'+count);
- $scope.temp.policy.triggerfaultSignatures["Fault5"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
- }
- }
- if(splitTraps.length > 6){
- var indexId = "Fault6";
- faultCollection.push(indexId);
- $scope.temp.policy.triggerfaultSignatures[indexId.replace(/['"]+/g, '')] = [];
- $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+6});
- var splitTrap1 = splitTraps[5];
- var splitEachTrap = splitTrap1.split("#!");
- for(i = 0 ; i < splitEachTrap.length; i++){
- var splitEachRow = splitEachTrap[i].split("@!");
- var count = i +1;
- if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
- var notBox = splitEachRow[0];
- var trigger1 = splitEachRow[1];
- var operatorBox = splitEachRow[2];
- var trigger2 = splitEachRow[3];
- }else{
- var notBox = '';
- var trigger1 = splitEachRow[0];
- var operatorBox = splitEachRow[1];
- var trigger2 = splitEachRow[2];
- }
- $scope.varbindDictionaryDatas.push('A'+count);
- $scope.temp.policy.triggerfaultSignatures["Fault6"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
- }
- }
+
+ if($scope.temp.policy.triggerTrapSignatures == undefined){
+ $scope.temp.policy.triggerTrapSignatures = [];
+ $scope.temp.policy.triggerfaultSignatures = [];
+ }
+ var trapCollection = [];
+ var faultCollection = [];
+ if($scope.varbindDictionaryDatas == undefined){
+ $scope.varbindDictionaryDatas = [];
+ }
+
+ $scope.init = function(data){
+ if(data != undefined && $scope.temp.policy.triggerTrapSignatures.length == 0){
+ $scope.jsonData = data;
+ if($scope.jsonData.triggerSignaturesUsedForUI != null){
+ if($scope.jsonData.triggerSignaturesUsedForUI.signatures != null){
+ $scope.temp.policy.triggerTrapSignatures = {Trap1 : [], Trap2 : [], Trap3 : [], Trap4 : [], Trap5 : [], Trap6 : []};
+ var splitTraps = $scope.jsonData.triggerSignaturesUsedForUI.signatures.split("#!?!");
+ if(splitTraps.length > 1){
+ $scope.triggerdisabled = false;
+ var indexId = "Trap1";
+ trapCollection.push(indexId);
+ $scope.temp.policy.triggerTrapSignatures[indexId.replace(/['"]+/g, '')] = [];
+ $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+1});
+ var splitTrap1 = splitTraps[0];
+ var splitEachTrap = splitTrap1.split("#!");
+ for(i = 0 ; i < splitEachTrap.length; i++){
+ var splitEachRow = splitEachTrap[i].split("@!");
+ var count = i +1;
+ if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
+ var notBox = splitEachRow[0];
+ var trigger1 = splitEachRow[1];
+ var operatorBox = splitEachRow[2];
+ var trigger2 = splitEachRow[3];
+ }else{
+ var notBox = '';
+ var trigger1 = splitEachRow[0];
+ var operatorBox = splitEachRow[1];
+ var trigger2 = splitEachRow[2];
+ }
+ $scope.varbindDictionaryDatas.push('A'+count);
+ $scope.temp.policy.triggerTrapSignatures["Trap1"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
+ }
+ }
+ if(splitTraps.length > 2){
+ var indexId = "Trap2";
+ trapCollection.push(indexId);
+ $scope.temp.policy.triggerTrapSignatures[indexId.replace(/['"]+/g, '')] = [];
+ $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+2});
+ var splitTrap1 = splitTraps[1];
+ var splitEachTrap = splitTrap1.split("#!");
+ for(i = 0 ; i < splitEachTrap.length; i++){
+ var splitEachRow = splitEachTrap[i].split("@!");
+ var count = i +1;
+ if(splitEachRow[0] == 'NOT' || splitEachRow[0] == ''){
+ var notBox = splitEachRow[0];
+ var trigger1 = splitEachRow[1];
+ var operatorBox = splitEachRow[2];
+ var trigger2 = splitEachRow[3];
+ }else{
+ var notBox = '';
+ var trigger1 = splitEachRow[0];
+ var operatorBox = splitEachRow[1];
+ var trigger2 = splitEachRow[2];
+ }
+ $scope.varbindDictionaryDatas.push('A'+count);
+ $scope.temp.policy.triggerTrapSignatures["Trap2"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
+ }
+ }
+ if(splitTraps.length > 3){
+ var indexId = "Trap3";
+ trapCollection.push(indexId);
+ $scope.temp.policy.triggerTrapSignatures[indexId.replace(/['"]+/g, '')] = [];
+ $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+3});
+ var splitTrap1 = splitTraps[2];
+ var splitEachTrap = splitTrap1.split("#!");
+ for(i = 0 ; i < splitEachTrap.length; i++){
+ var splitEachRow = splitEachTrap[i].split("@!");
+ var count = i +1;
+ if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
+ var notBox = splitEachRow[0];
+ var trigger1 = splitEachRow[1];
+ var operatorBox = splitEachRow[2];
+ var trigger2 = splitEachRow[3];
+ }else{
+ var notBox = '';
+ var trigger1 = splitEachRow[0];
+ var operatorBox = splitEachRow[1];
+ var trigger2 = splitEachRow[2];
+ }
+ $scope.varbindDictionaryDatas.push('A'+count);
+ $scope.temp.policy.triggerTrapSignatures["Trap3"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
+ }
+ }
+ if(splitTraps.length > 4){
+ var indexId = "Trap4";
+ trapCollection.push(indexId);
+ $scope.temp.policy.triggerTrapSignatures[indexId.replace(/['"]+/g, '')] = [];
+ $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+4});
+ var splitTrap1 = splitTraps[3];
+ var splitEachTrap = splitTrap1.split("#!");
+ for(i = 0 ; i < splitEachTrap.length; i++){
+ var splitEachRow = splitEachTrap[i].split("@!");
+ var count = i +1;
+ if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
+ var notBox = splitEachRow[0];
+ var trigger1 = splitEachRow[1];
+ var operatorBox = splitEachRow[2];
+ var trigger2 = splitEachRow[3];
+ }else{
+ var notBox = '';
+ var trigger1 = splitEachRow[0];
+ var operatorBox = splitEachRow[1];
+ var trigger2 = splitEachRow[2];
+ }
+ $scope.varbindDictionaryDatas.push('A'+count);
+ $scope.temp.policy.triggerTrapSignatures["Trap4"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
+ }
+ }
+ if(splitTraps.length > 5){
+ var indexId = "Trap5";
+ trapCollection.push(indexId);
+ $scope.temp.policy.triggerTrapSignatures[indexId.replace(/['"]+/g, '')] = [];
+ $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+5});
+ var splitTrap1 = splitTraps[4];
+ var splitEachTrap = splitTrap1.split("#!");
+ for(i = 0 ; i < splitEachTrap.length; i++){
+ var splitEachRow = splitEachTrap[i].split("@!");
+ var count = i +1;
+ if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
+ var notBox = splitEachRow[0];
+ var trigger1 = splitEachRow[1];
+ var operatorBox = splitEachRow[2];
+ var trigger2 = splitEachRow[3];
+ }else{
+ var notBox = '';
+ var trigger1 = splitEachRow[0];
+ var operatorBox = splitEachRow[1];
+ var trigger2 = splitEachRow[2];
+ }
+ $scope.varbindDictionaryDatas.push('A'+count);
+ $scope.temp.policy.triggerTrapSignatures["Trap5"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
+ }
+ }
+ if(splitTraps.length > 6){
+ var indexId = "Trap6";
+ trapCollection.push(indexId);
+ $scope.temp.policy.triggerTrapSignatures[indexId.replace(/['"]+/g, '')] = [];
+ $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+6});
+ var splitTrap1 = splitTraps[5];
+ var splitEachTrap = splitTrap1.split("#!");
+ for(i = 0 ; i < splitEachTrap.length; i++){
+ var splitEachRow = splitEachTrap[i].split("@!");
+ var count = i +1;
+ if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
+ var notBox = splitEachRow[0];
+ var trigger1 = splitEachRow[1];
+ var operatorBox = splitEachRow[2];
+ var trigger2 = splitEachRow[3];
+ }else{
+ var notBox = '';
+ var trigger1 = splitEachRow[0];
+ var operatorBox = splitEachRow[1];
+ var trigger2 = splitEachRow[2];
+ }
+ $scope.varbindDictionaryDatas.push('A'+count);
+ $scope.temp.policy.triggerTrapSignatures["Trap6"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
+ }
+ }
+ if($scope.jsonData.triggerSignaturesUsedForUI.connectSignatures != null){
+ var splitConnectTraps = $scope.jsonData.triggerSignaturesUsedForUI.connectSignatures.split("#!?!");
+ for(i=0; i < splitConnectTraps.length; i++){
+ if(splitConnectTraps[i] != ""){
+ var newConnectTrapItemNo = i+1;
+ var connects = splitConnectTraps[i].split("@!");
+ if(connects[0] == 'NOT' || connects[0] ==''){
+ var notBox = connects[0];
+ var connectTrap1 = connects[1];
+ var trapCount1 = connects[2];
+ var operatorBox = connects[3];
+ var connectTrap2 = connects[4];
+ var trapCount2 = connects[5];
+ }else{
+ var notBox = '';
+ var connectTrap1 = connects[0];
+ var trapCount1 = connects[1];
+ var operatorBox = connects[2];
+ var connectTrap2 = connects[3];
+ var trapCount2 = connects[4];
+ }
+ $scope.temp.policy.connecttriggerSignatures.push({'id':'C'+newConnectTrapItemNo,'notBox' : notBox , 'connectTrap1': connectTrap1,'trapCount1' : trapCount1,
+ 'operatorBox': operatorBox, 'connectTrap2': connectTrap2,'trapCount2' : trapCount2});
+ }
+ }
+ }
+ }
+ }
+ if($scope.jsonData.verificationSignaturesUsedForUI != null){
+ if($scope.jsonData.verificationSignaturesUsedForUI.signatures != null){
+ $scope.temp.policy.triggerfaultSignatures = {Fault1 : [], Fault2 : [], Fault3 : [], Fault4 : [], Fault5 : [], Fault6 : []};
+ var splitTraps = $scope.jsonData.verificationSignaturesUsedForUI.signatures.split("#!?!");
+ if(splitTraps.length > 1){
+ $scope.verificationdisabled = false;
+ var indexId = "Fault1";
+ faultCollection.push(indexId);
+ $scope.temp.policy.triggerfaultSignatures[indexId.replace(/['"]+/g, '')] = [];
+ $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+1});
+ var splitTrap1 = splitTraps[0];
+ var splitEachTrap = splitTrap1.split("#!");
+ for(i = 0 ; i < splitEachTrap.length; i++){
+ var splitEachRow = splitEachTrap[i].split("@!");
+ var count = i +1;
+ if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
+ var notBox = splitEachRow[0];
+ var trigger1 = splitEachRow[1];
+ var operatorBox = splitEachRow[2];
+ var trigger2 = splitEachRow[3];
+ }else{
+ var notBox = '';
+ var trigger1 = splitEachRow[0];
+ var operatorBox = splitEachRow[1];
+ var trigger2 = splitEachRow[2];
+ }
+ $scope.varbindDictionaryDatas.push('A'+count);
+ $scope.temp.policy.triggerfaultSignatures["Fault1"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
+ }
+ }
+ if(splitTraps.length > 2){
+ var indexId = "Fault2";
+ faultCollection.push(indexId);
+ $scope.temp.policy.triggerfaultSignatures[indexId.replace(/['"]+/g, '')] = [];
+ $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+2});
+ var splitTrap1 = splitTraps[1];
+ var splitEachTrap = splitTrap1.split("#!");
+ for(i = 0 ; i < splitEachTrap.length; i++){
+ var splitEachRow = splitEachTrap[i].split("@!");
+ var count = i +1;
+ if(splitEachRow[0] == 'NOT' || splitEachRow[0] == ''){
+ var notBox = splitEachRow[0];
+ var trigger1 = splitEachRow[1];
+ var operatorBox = splitEachRow[2];
+ var trigger2 = splitEachRow[3];
+ }else{
+ var notBox = '';
+ var trigger1 = splitEachRow[0];
+ var operatorBox = splitEachRow[1];
+ var trigger2 = splitEachRow[2];
+ }
+ $scope.varbindDictionaryDatas.push('A'+count);
+ $scope.temp.policy.triggerfaultSignatures["Fault2"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
+ }
+ }
+ if(splitTraps.length > 3){
+ var indexId = "Fault3";
+ faultCollection.push(indexId);
+ $scope.temp.policy.triggerfaultSignatures[indexId.replace(/['"]+/g, '')] = [];
+ $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+3});
+ var splitTrap1 = splitTraps[2];
+ var splitEachTrap = splitTrap1.split("#!");
+ for(i = 0 ; i < splitEachTrap.length; i++){
+ var splitEachRow = splitEachTrap[i].split("@!");
+ var count = i +1;
+ if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
+ var notBox = splitEachRow[0];
+ var trigger1 = splitEachRow[1];
+ var operatorBox = splitEachRow[2];
+ var trigger2 = splitEachRow[3];
+ }else{
+ var notBox = '';
+ var trigger1 = splitEachRow[0];
+ var operatorBox = splitEachRow[1];
+ var trigger2 = splitEachRow[2];
+ }
+ $scope.varbindDictionaryDatas.push('A'+count);
+ $scope.temp.policy.triggerfaultSignatures["Fault3"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
+ }
+ }
+ if(splitTraps.length > 4){
+ var indexId = "Fault4";
+ faultCollection.push(indexId);
+ $scope.temp.policy.triggerfaultSignatures[indexId.replace(/['"]+/g, '')] = [];
+ $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+4});
+ var splitTrap1 = splitTraps[3];
+ var splitEachTrap = splitTrap1.split("#!");
+ for(i = 0 ; i < splitEachTrap.length; i++){
+ var splitEachRow = splitEachTrap[i].split("@!");
+ var count = i +1;
+ if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
+ var notBox = splitEachRow[0];
+ var trigger1 = splitEachRow[1];
+ var operatorBox = splitEachRow[2];
+ var trigger2 = splitEachRow[3];
+ }else{
+ var notBox = '';
+ var trigger1 = splitEachRow[0];
+ var operatorBox = splitEachRow[1];
+ var trigger2 = splitEachRow[2];
+ }
+ $scope.varbindDictionaryDatas.push('A'+count);
+ $scope.temp.policy.triggerfaultSignatures["Fault4"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
+ }
+ }
+ if(splitTraps.length > 5){
+ var indexId = "Fault5";
+ faultCollection.push(indexId);
+ $scope.temp.policy.triggerfaultSignatures[indexId.replace(/['"]+/g, '')] = [];
+ $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+5});
+ var splitTrap1 = splitTraps[4];
+ var splitEachTrap = splitTrap1.split("#!");
+ for(i = 0 ; i < splitEachTrap.length; i++){
+ var splitEachRow = splitEachTrap[i].split("@!");
+ var count = i +1;
+ if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
+ var notBox = splitEachRow[0];
+ var trigger1 = splitEachRow[1];
+ var operatorBox = splitEachRow[2];
+ var trigger2 = splitEachRow[3];
+ }else{
+ var notBox = '';
+ var trigger1 = splitEachRow[0];
+ var operatorBox = splitEachRow[1];
+ var trigger2 = splitEachRow[2];
+ }
+ $scope.varbindDictionaryDatas.push('A'+count);
+ $scope.temp.policy.triggerfaultSignatures["Fault5"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
+ }
+ }
+ if(splitTraps.length > 6){
+ var indexId = "Fault6";
+ faultCollection.push(indexId);
+ $scope.temp.policy.triggerfaultSignatures[indexId.replace(/['"]+/g, '')] = [];
+ $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+6});
+ var splitTrap1 = splitTraps[5];
+ var splitEachTrap = splitTrap1.split("#!");
+ for(i = 0 ; i < splitEachTrap.length; i++){
+ var splitEachRow = splitEachTrap[i].split("@!");
+ var count = i +1;
+ if(splitEachRow[0] == 'NOT' || splitEachRow[0] ==''){
+ var notBox = splitEachRow[0];
+ var trigger1 = splitEachRow[1];
+ var operatorBox = splitEachRow[2];
+ var trigger2 = splitEachRow[3];
+ }else{
+ var notBox = '';
+ var trigger1 = splitEachRow[0];
+ var operatorBox = splitEachRow[1];
+ var trigger2 = splitEachRow[2];
+ }
+ $scope.varbindDictionaryDatas.push('A'+count);
+ $scope.temp.policy.triggerfaultSignatures["Fault6"].push({'id':'A'+count, 'notBox' : notBox , 'trigger1': trigger1 , 'operatorBox' : operatorBox, 'trigger2': trigger2});
+ }
+ }
- if($scope.jsonData.verificationSignaturesUsedForUI.connectSignatures != null){
- var splitConnectTraps = $scope.jsonData.verificationSignaturesUsedForUI.connectSignatures.split("#!?!");
- for(i=0; i < splitConnectTraps.length; i++){
- if(splitConnectTraps[i] != ""){
- var newConnectTrapItemNo = i+1;
- var connects = splitConnectTraps[i].split("@!");
- if(connects[0] == 'NOT' || connects[0] ==''){
- var notBox = connects[0];
- var connectTrap1 = connects[1];
- var trapCount1 = connects[2];
- var operatorBox = connects[3];
- var connectTrap2 = connects[4];
- var trapCount2 = connects[5];
- }else{
- var notBox = '';
- var connectTrap1 = connects[0];
- var trapCount1 = connects[1];
- var operatorBox = connects[2];
- var connectTrap2 = connects[3];
- var trapCount2 = connects[4];
- }
- $scope.temp.policy.connectVerificationSignatures.push({'id':'C'+newConnectTrapItemNo,'notBox' : notBox , 'connectTrap1': connectTrap1,'trapCount1' : trapCount1,
- 'operatorBox': operatorBox, 'connectTrap2': connectTrap2,'trapCount2' : trapCount2});
- }
- }
- }
- }
- }
- }
+ if($scope.jsonData.verificationSignaturesUsedForUI.connectSignatures != null){
+ var splitConnectTraps = $scope.jsonData.verificationSignaturesUsedForUI.connectSignatures.split("#!?!");
+ for(i=0; i < splitConnectTraps.length; i++){
+ if(splitConnectTraps[i] != ""){
+ var newConnectTrapItemNo = i+1;
+ var connects = splitConnectTraps[i].split("@!");
+ if(connects[0] == 'NOT' || connects[0] ==''){
+ var notBox = connects[0];
+ var connectTrap1 = connects[1];
+ var trapCount1 = connects[2];
+ var operatorBox = connects[3];
+ var connectTrap2 = connects[4];
+ var trapCount2 = connects[5];
+ }else{
+ var notBox = '';
+ var connectTrap1 = connects[0];
+ var trapCount1 = connects[1];
+ var operatorBox = connects[2];
+ var connectTrap2 = connects[3];
+ var trapCount2 = connects[4];
+ }
+ $scope.temp.policy.connectVerificationSignatures.push({'id':'C'+newConnectTrapItemNo,'notBox' : notBox , 'connectTrap1': connectTrap1,'trapCount1' : trapCount1,
+ 'operatorBox': operatorBox, 'connectTrap2': connectTrap2,'trapCount2' : trapCount2});
+ }
+ }
+ }
+ }
+ }
+ }
- };
+ };
- if($scope.temp.policy.readOnly){
- $scope.triggerdisabled = true;
- $scope.verificationdisabled = true;
- }else{
- $scope.triggerdisabled = false;
- $scope.verificationdisabled = false;
- }
-
+ if($scope.temp.policy.readOnly){
+ $scope.triggerdisabled = true;
+ $scope.verificationdisabled = true;
+ }else{
+ $scope.triggerdisabled = false;
+ $scope.verificationdisabled = false;
+ }
+
- 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);
- console.log($scope.onapNameDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
+ });
- PolicyAppService.getData('getDictionary/get_PEPOptionsDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.pepOptionsDictionaryDatas = JSON.parse($scope.data.pepOptionsDictionaryDatas);
- console.log($scope.pepOptionsDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_PEPOptionsDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.pepOptionsDictionaryDatas = JSON.parse($scope.data.pepOptionsDictionaryDatas);
+ });
- PolicyAppService.getData('getDictionary/get_PEPOptionsData').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.pepOptionsDictionaryDataEntity = JSON.parse($scope.data.pepOptionsDictionaryDatas);
- console.log($scope.pepOptionsDictionaryDataEntity);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_PEPOptionsData').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.pepOptionsDictionaryDataEntity = JSON.parse($scope.data.pepOptionsDictionaryDatas);
+ });
- PolicyAppService.getData('getDictionary/get_VarbindDictionaryDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.varbindDictionaryDatas = JSON.parse($scope.data.varbindDictionaryDatas);
- console.log($scope.varbindDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_VarbindDictionaryDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.varbindDictionaryDatas = JSON.parse($scope.data.varbindDictionaryDatas);
+ });
- 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);
- console.log($scope.vnfTypeDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_VNFTypeDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.vnfTypeDictionaryDatas = JSON.parse($scope.data.vnfTypeDictionaryDatas);
+ });
- 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);
- console.log($scope.vsclActionDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_VSCLActionDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.vsclActionDictionaryDatas = JSON.parse($scope.data.vsclActionDictionaryDatas);
+ });
- PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
- console.log($scope.riskTypeDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
+ });
- $scope.pepActionDictionaryDatas = [];
-
- $scope.getPepActionValues = function(pepOptionValue){
- for (var i = 0; i < $scope.pepOptionsDictionaryDataEntity.length; ++i) {
- var obj = $scope.pepOptionsDictionaryDataEntity[i];
- if (obj.pepName == pepOptionValue){
- var splitAlarm = obj.actions.split(':#@');
- for (var j = 0; j < splitAlarm.length; ++j) {
- $scope.pepActionDictionaryDatas.push(splitAlarm[j].split('=#@')[0]);
- }
- }
- }
- };
+ $scope.pepActionDictionaryDatas = [];
- function trapData(){
- var data = {};
- if($scope.temp.policy.triggerTrapSignatures.length == 1 || $scope.temp.policy.triggerTrapSignatures["Trap1"] != null){
- data = {trap1 : $scope.temp.policy.triggerTrapSignatures.Trap1 }
- }
- if($scope.temp.policy.triggerTrapSignatures.length == 2 || $scope.temp.policy.triggerTrapSignatures["Trap2"] != null){
- data = {trap1 : $scope.temp.policy.triggerTrapSignatures.Trap1, trap2 : $scope.temp.policy.triggerTrapSignatures.Trap2}
- }
- if($scope.temp.policy.triggerTrapSignatures.length == 3 || $scope.temp.policy.triggerTrapSignatures["Trap3"] != null){
- data = {trap1 : $scope.temp.policy.triggerTrapSignatures.Trap1, trap2 : $scope.temp.policy.triggerTrapSignatures.Trap2,
- trap3 : $scope.temp.policy.triggerTrapSignatures.Trap3}
- }
- if($scope.temp.policy.triggerTrapSignatures.length == 4 || $scope.temp.policy.triggerTrapSignatures["Trap4"] != null){
- data = {trap1 : $scope.temp.policy.triggerTrapSignatures.Trap1, trap2 : $scope.temp.policy.triggerTrapSignatures.Trap2,
- trap3 : $scope.temp.policy.triggerTrapSignatures.Trap3, trap4 : $scope.temp.policy.triggerTrapSignatures.Trap4}
- }
- if($scope.temp.policy.triggerTrapSignatures.length == 5 || $scope.temp.policy.triggerTrapSignatures["Trap5"] != null){
- data = {trap1 : $scope.temp.policy.triggerTrapSignatures.Trap1, trap2 : $scope.temp.policy.triggerTrapSignatures.Trap2,
- trap3 : $scope.temp.policy.triggerTrapSignatures.Trap3, trap4 : $scope.temp.policy.triggerTrapSignatures.Trap4,
- trap5 : $scope.temp.policy.triggerTrapSignatures.Trap5}
- }
- if($scope.temp.policy.triggerTrapSignatures.length == 6 || $scope.temp.policy.triggerTrapSignatures["Trap6"] != null){
- data = {trap1 : $scope.temp.policy.triggerTrapSignatures.Trap1, trap2 : $scope.temp.policy.triggerTrapSignatures.Trap2,
- trap3 : $scope.temp.policy.triggerTrapSignatures.Trap3, trap4 : $scope.temp.policy.triggerTrapSignatures.Trap4,
- trap5 : $scope.temp.policy.triggerTrapSignatures.Trap5, trap6 : $scope.temp.policy.triggerTrapSignatures.Trap6}
- }
- return data;
- }
-
- function faultDatas(){
- var faultData = {};
- if($scope.temp.policy.triggerfaultSignatures.length == 1 || $scope.temp.policy.triggerfaultSignatures["Fault1"] != null){
- faultData = {trap1 : $scope.temp.policy.triggerfaultSignatures.Fault1 }
- }
- if($scope.temp.policy.triggerfaultSignatures.length == 2 || $scope.temp.policy.triggerfaultSignatures["Fault2"] != null){
- faultData = {trap1 : $scope.temp.policy.triggerfaultSignatures.Fault1, trap2 : $scope.temp.policy.triggerfaultSignatures.Fault2}
- }
- if($scope.temp.policy.triggerfaultSignatures.length == 3 || $scope.temp.policy.triggerfaultSignatures["Fault3"] != null){
- faultData = {trap1 : $scope.temp.policy.triggerfaultSignatures.Fault1, trap2 : $scope.temp.policy.triggerfaultSignatures.Fault2,
- trap3 : $scope.temp.policy.triggerfaultSignatures.Fault3}
- }
- if($scope.temp.policy.triggerTrapSignatures.length == 4 || $scope.temp.policy.triggerfaultSignatures["Fault4"] != null){
- faultData = {trap1 : $scope.temp.policy.triggerfaultSignatures.Fault1, trap2 : $scope.temp.policy.triggerfaultSignatures.Fault2,
- trap3 : $scope.temp.policy.triggerfaultSignatures.Fault3, trap4 : $scope.temp.policy.triggerfaultSignatures.Fault4}
- }
- if($scope.temp.policy.triggerfaultSignatures.length == 5 || $scope.temp.policy.triggerfaultSignatures["Fault5"] != null){
- faultData = {trap1 : $scope.temp.policy.triggerfaultSignatures.Fault1, trap2 : $scope.temp.policy.triggerfaultSignatures.Fault2,
- trap3 : $scope.temp.policy.triggerfaultSignatures.Fault3, trap4 : $scope.temp.policy.triggerfaultSignatures.Fault4,
- trap5 : $scope.temp.policy.triggerfaultSignatures.Fault5}
- }
- if($scope.temp.policy.triggerfaultSignatures.length == 6 || $scope.temp.policy.triggerfaultSignatures["Fault6"] != null){
- faultData = {trap1 : $scope.temp.policy.triggerfaultSignatures.Fault1, trap2 : $scope.temp.policy.triggerfaultSignatures.Fault2,
- trap3 : $scope.temp.policy.triggerfaultSignatures.Fault3, trap4 : $scope.temp.policy.triggerfaultSignatures.Fault4,
- trap5 : $scope.temp.policy.triggerfaultSignatures.Fault5, trap6 : $scope.temp.policy.triggerfaultSignatures.Fault6}
- }
- return faultData;
- }
-
- $scope.saveFaultPolicy = function(policy){
- if(policy.itemContent != undefined){
- $scope.refreshCheck = true;
- $scope.policyNavigator = policy.itemContent;
- policy.itemContent = "";
- }
- $scope.savebutton = false;
- var data = trapData();
- var faultData = faultDatas();
- var uuu = "policycreation/save_policy";
- var postData={policyData: policy,
- trapData : data,
- faultData : faultData
- };
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.data=data.policyData;
- if($scope.data == 'success'){
- $scope.temp.policy.readOnly = 'true';
- $scope.pushStatus=data.policyData.split("&")[1];
- if($scope.pushStatus=="successPush"){
- Notification.success("Policy pushed successfully");
- }
- $scope.triggerdisabled = true;
- $scope.verificationdisabled = true;
- Notification.success("Policy Saved Successfully.");
- }else if ($scope.data == 'PolicyExists'){
- $scope.savebutton = true;
- Notification.error("Policy Already Exists with Same Name in Scope.");
- }
- });
- console.log($scope.data);
- },
- error : function(data){
- Notification.error("Error Occured while saving Policy.");
- }
- });
- };
-
- $scope.validatePolicy = function(policy){
- console.log(policy);
- document.getElementById("validate").innerHTML = "";
- var uuu = "policyController/validate_policy.htm";
- var data = trapData();
- var faultData = faultDatas();
- var postData={policyData: policy, trapData : data, faultData : faultData};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.validateData = data.data.replace(/\"/g, "");
- $scope.data=data.data.substring(1,8);
- var size = data.data.length;
- if($scope.data == 'success'){
- Notification.success("Validation Success.");
- $scope.savebutton = false;
- if (size > 18){
- var displayWarning = data.data.substring(19,size);
- document.getElementById("validate").innerHTML = "Safe Policy Warning Message : "+displayWarning;
- document.getElementById("validate").style.color = "white";
- document.getElementById("validate").style.backgroundColor = "skyblue";
- }
- }else{
- Notification.error("Validation Failed.");
- document.getElementById("validate").innerHTML = $scope.validateData;
- document.getElementById("validate").style.color = "white";
- document.getElementById("validate").style.backgroundColor = "red";
- $scope.savebutton = true;
- }
+ $scope.getPepActionValues = function(pepOptionValue){
+ for (var i = 0; i < $scope.pepOptionsDictionaryDataEntity.length; ++i) {
+ var obj = $scope.pepOptionsDictionaryDataEntity[i];
+ if (obj.pepName == pepOptionValue){
+ var splitAlarm = obj.actions.split(':#@');
+ for (var j = 0; j < splitAlarm.length; ++j) {
+ $scope.pepActionDictionaryDatas.push(splitAlarm[j].split('=#@')[0]);
+ }
+ }
+ }
+ };
- });
- console.log($scope.data);
- },
- error : function(data){
- Notification.error("Validation Failed.");
- $scope.savebutton = true;
- }
- });
- };
- if($scope.connectTriggerTrapsList == undefined){
- $scope.connectTriggerTrapsList = [];
- }
- if($scope.temp.policy.traptriggerSignatures == undefined){
- $scope.temp.policy.traptriggerSignatures = [];
- }
-
- $scope.ItemNo = 0;
- $scope.TriggerSignatureDatas = [{"triggerSignatures" : $scope.temp.policy.traptriggerSignatures}];
- $scope.addTriggerButton = function() {
- $scope.triggerdisabled = false;
- var newItemNo = $scope.temp.policy.traptriggerSignatures.length+1;
- $scope.ItemNo = newItemNo;
- $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+newItemNo});
- $scope.connectTriggerTrapsList.push('Trap'+newItemNo);
- };
- $scope.removeTriggerButton = function() {
- var lastItem = $scope.temp.policy.traptriggerSignatures.length-1;
- $scope.temp.policy.traptriggerSignatures.splice(lastItem);
- $scope.connectTriggerTrapsList.splice('Trap'+lastItem);
- };
+ function trapData(){
+ var data = {};
+ if($scope.temp.policy.triggerTrapSignatures.length == 1 || $scope.temp.policy.triggerTrapSignatures["Trap1"] != null){
+ data = {trap1 : $scope.temp.policy.triggerTrapSignatures.Trap1 }
+ }
+ if($scope.temp.policy.triggerTrapSignatures.length == 2 || $scope.temp.policy.triggerTrapSignatures["Trap2"] != null){
+ data = {trap1 : $scope.temp.policy.triggerTrapSignatures.Trap1, trap2 : $scope.temp.policy.triggerTrapSignatures.Trap2}
+ }
+ if($scope.temp.policy.triggerTrapSignatures.length == 3 || $scope.temp.policy.triggerTrapSignatures["Trap3"] != null){
+ data = {trap1 : $scope.temp.policy.triggerTrapSignatures.Trap1, trap2 : $scope.temp.policy.triggerTrapSignatures.Trap2,
+ trap3 : $scope.temp.policy.triggerTrapSignatures.Trap3}
+ }
+ if($scope.temp.policy.triggerTrapSignatures.length == 4 || $scope.temp.policy.triggerTrapSignatures["Trap4"] != null){
+ data = {trap1 : $scope.temp.policy.triggerTrapSignatures.Trap1, trap2 : $scope.temp.policy.triggerTrapSignatures.Trap2,
+ trap3 : $scope.temp.policy.triggerTrapSignatures.Trap3, trap4 : $scope.temp.policy.triggerTrapSignatures.Trap4}
+ }
+ if($scope.temp.policy.triggerTrapSignatures.length == 5 || $scope.temp.policy.triggerTrapSignatures["Trap5"] != null){
+ data = {trap1 : $scope.temp.policy.triggerTrapSignatures.Trap1, trap2 : $scope.temp.policy.triggerTrapSignatures.Trap2,
+ trap3 : $scope.temp.policy.triggerTrapSignatures.Trap3, trap4 : $scope.temp.policy.triggerTrapSignatures.Trap4,
+ trap5 : $scope.temp.policy.triggerTrapSignatures.Trap5}
+ }
+ if($scope.temp.policy.triggerTrapSignatures.length == 6 || $scope.temp.policy.triggerTrapSignatures["Trap6"] != null){
+ data = {trap1 : $scope.temp.policy.triggerTrapSignatures.Trap1, trap2 : $scope.temp.policy.triggerTrapSignatures.Trap2,
+ trap3 : $scope.temp.policy.triggerTrapSignatures.Trap3, trap4 : $scope.temp.policy.triggerTrapSignatures.Trap4,
+ trap5 : $scope.temp.policy.triggerTrapSignatures.Trap5, trap6 : $scope.temp.policy.triggerTrapSignatures.Trap6}
+ }
+ return data;
+ }
+
+ function faultDatas(){
+ var faultData = {};
+ if($scope.temp.policy.triggerfaultSignatures.length == 1 || $scope.temp.policy.triggerfaultSignatures["Fault1"] != null){
+ faultData = {trap1 : $scope.temp.policy.triggerfaultSignatures.Fault1 }
+ }
+ if($scope.temp.policy.triggerfaultSignatures.length == 2 || $scope.temp.policy.triggerfaultSignatures["Fault2"] != null){
+ faultData = {trap1 : $scope.temp.policy.triggerfaultSignatures.Fault1, trap2 : $scope.temp.policy.triggerfaultSignatures.Fault2}
+ }
+ if($scope.temp.policy.triggerfaultSignatures.length == 3 || $scope.temp.policy.triggerfaultSignatures["Fault3"] != null){
+ faultData = {trap1 : $scope.temp.policy.triggerfaultSignatures.Fault1, trap2 : $scope.temp.policy.triggerfaultSignatures.Fault2,
+ trap3 : $scope.temp.policy.triggerfaultSignatures.Fault3}
+ }
+ if($scope.temp.policy.triggerTrapSignatures.length == 4 || $scope.temp.policy.triggerfaultSignatures["Fault4"] != null){
+ faultData = {trap1 : $scope.temp.policy.triggerfaultSignatures.Fault1, trap2 : $scope.temp.policy.triggerfaultSignatures.Fault2,
+ trap3 : $scope.temp.policy.triggerfaultSignatures.Fault3, trap4 : $scope.temp.policy.triggerfaultSignatures.Fault4}
+ }
+ if($scope.temp.policy.triggerfaultSignatures.length == 5 || $scope.temp.policy.triggerfaultSignatures["Fault5"] != null){
+ faultData = {trap1 : $scope.temp.policy.triggerfaultSignatures.Fault1, trap2 : $scope.temp.policy.triggerfaultSignatures.Fault2,
+ trap3 : $scope.temp.policy.triggerfaultSignatures.Fault3, trap4 : $scope.temp.policy.triggerfaultSignatures.Fault4,
+ trap5 : $scope.temp.policy.triggerfaultSignatures.Fault5}
+ }
+ if($scope.temp.policy.triggerfaultSignatures.length == 6 || $scope.temp.policy.triggerfaultSignatures["Fault6"] != null){
+ faultData = {trap1 : $scope.temp.policy.triggerfaultSignatures.Fault1, trap2 : $scope.temp.policy.triggerfaultSignatures.Fault2,
+ trap3 : $scope.temp.policy.triggerfaultSignatures.Fault3, trap4 : $scope.temp.policy.triggerfaultSignatures.Fault4,
+ trap5 : $scope.temp.policy.triggerfaultSignatures.Fault5, trap6 : $scope.temp.policy.triggerfaultSignatures.Fault6}
+ }
+ return faultData;
+ }
+
+ $scope.saveFaultPolicy = function(policy){
+ if(policy.itemContent != undefined){
+ $scope.refreshCheck = true;
+ $scope.policyNavigator = policy.itemContent;
+ policy.itemContent = "";
+ }
+ $scope.savebutton = false;
+ var data = trapData();
+ var faultData = faultDatas();
+ var uuu = "policycreation/save_policy";
+ var postData={policyData: policy,
+ trapData : data,
+ faultData : faultData
+ };
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.data=data.policyData;
+ if($scope.data == 'success'){
+ $scope.temp.policy.readOnly = 'true';
+ $scope.pushStatus=data.policyData.split("&")[1];
+ if($scope.pushStatus=="successPush"){
+ Notification.success("Policy pushed successfully");
+ }
+ $scope.triggerdisabled = true;
+ $scope.verificationdisabled = true;
+ Notification.success("Policy Saved Successfully.");
+ }else if ($scope.data == 'PolicyExists'){
+ $scope.savebutton = true;
+ Notification.error("Policy Already Exists with Same Name in Scope.");
+ }
+ });
+ },
+ error : function(data){
+ Notification.error("Error Occured while saving Policy.");
+ }
+ });
+ };
-
- $scope.trapItemNo = 0;
- $scope.TrapTriggerSignatureDatas = [{"triggermainSignatures" : $scope.temp.policy.triggerTrapSignatures}];
- $scope.addTrapTriggerButton = function(indexId) {
- if(trapCollection.indexOf(indexId) !== -1){
+ $scope.validatePolicy = function(policy){
+ document.getElementById("validate").innerHTML = "";
+ var uuu = "policyController/validate_policy.htm";
+ var data = trapData();
+ var faultData = faultDatas();
+ var postData={policyData: policy, trapData : data, faultData : faultData};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.validateData = data.data.replace(/\"/g, "");
+ $scope.data=data.data.substring(1,8);
+ var size = data.data.length;
+ if($scope.data == 'success'){
+ Notification.success("Validation Success.");
+ $scope.savebutton = false;
+ if (size > 18){
+ var displayWarning = data.data.substring(19,size);
+ document.getElementById("validate").innerHTML = "Safe Policy Warning Message : "+displayWarning;
+ document.getElementById("validate").style.color = "white";
+ document.getElementById("validate").style.backgroundColor = "skyblue";
+ }
+ }else{
+ Notification.error("Validation Failed.");
+ document.getElementById("validate").innerHTML = $scope.validateData;
+ document.getElementById("validate").style.color = "white";
+ document.getElementById("validate").style.backgroundColor = "red";
+ $scope.savebutton = true;
+ }
- }else{
- $scope.temp.policy.triggerTrapSignatures[indexId] = [];
- trapCollection.push(indexId);
- }
- var newTrapItemNo = $scope.temp.policy.triggerTrapSignatures[indexId].length+1;
- $scope.trapItemNo = newTrapItemNo;
- $scope.temp.policy.triggerTrapSignatures.push($scope.temp.policy.triggerTrapSignatures[indexId].push({'id':'A'+newTrapItemNo}));
- if(newTrapItemNo > 1){
- var count = newTrapItemNo-1;
- $scope.varbindDictionaryDatas.push('A'+count);
- }
- };
- $scope.removeTrapTriggerButton = function(indexId) {
- var lastTrapItem = $scope.temp.policy.triggerTrapSignatures[indexId].length-1;
- var checkLastTrapItem = lastTrapItem;
- if(checkLastTrapItem == 0){
- trapCollection.splice(indexId);
- }
- $scope.temp.policy.triggerTrapSignatures[indexId].splice(lastTrapItem);
- };
+ });
+ },
+ error : function(data){
+ Notification.error("Validation Failed.");
+ $scope.savebutton = true;
+ }
+ });
+ };
+ if($scope.connectTriggerTrapsList == undefined){
+ $scope.connectTriggerTrapsList = [];
+ }
+ if($scope.temp.policy.traptriggerSignatures == undefined){
+ $scope.temp.policy.traptriggerSignatures = [];
+ }
+
+ $scope.ItemNo = 0;
+ $scope.TriggerSignatureDatas = [{"triggerSignatures" : $scope.temp.policy.traptriggerSignatures}];
+ $scope.addTriggerButton = function() {
+ $scope.triggerdisabled = false;
+ var newItemNo = $scope.temp.policy.traptriggerSignatures.length+1;
+ $scope.ItemNo = newItemNo;
+ $scope.temp.policy.traptriggerSignatures.push({'id':'Trap'+newItemNo});
+ $scope.connectTriggerTrapsList.push('Trap'+newItemNo);
+ };
+ $scope.removeTriggerButton = function() {
+ var lastItem = $scope.temp.policy.traptriggerSignatures.length-1;
+ $scope.temp.policy.traptriggerSignatures.splice(lastItem);
+ $scope.connectTriggerTrapsList.splice('Trap'+lastItem);
+ };
- if($scope.temp.policy.connecttriggerSignatures == undefined){
- $scope.temp.policy.connecttriggerSignatures = [];
- }
-
- $scope.connecttrapItemNo = 0;
- $scope.TrapConnectTriggerSignatureDatas = [{"connecttriggerSignatures" : $scope.temp.policy.connecttriggerSignatures}];
- $scope.addTriggerConnectButton = function() {
- var newConnectTrapItemNo = $scope.temp.policy.connecttriggerSignatures.length+1;
- $scope.connecttrapItemNo = newConnectTrapItemNo;
- $scope.temp.policy.connecttriggerSignatures.push({'id':'C'+newConnectTrapItemNo});
- if(newConnectTrapItemNo >1){
- var count = newConnectTrapItemNo-1;
- $scope.connectTriggerTrapsList.push('C'+count);
- }
- };
- $scope.removeTriggerConnectButton = function() {
- var lastConnectTrapItem = $scope.temp.policy.connecttriggerSignatures.length-1;
- $scope.temp.policy.connecttriggerSignatures.splice(lastConnectTrapItem);
- if(lastConnectTrapItem < 1){
- var count = lastConnectTrapItem-1;
- $scope.connectTriggerTrapsList.splice('C'+count);
- }
- };
- if($scope.connectTriggerFaultsList == undefined){
- $scope.connectTriggerFaultsList = [];
- }
- if($scope.temp.policy.faulttriggerSignatures == undefined){
- $scope.temp.policy.faulttriggerSignatures = [];
- }
-
- $scope.FaultItemNo = 0;
- $scope.FaultSignatureDatas = [{"verificationmainSignatures" : $scope.temp.policy.faulttriggerSignatures}];
- $scope.addVerFaultButton = function() {
- var newFaultItemNo = $scope.temp.policy.faulttriggerSignatures.length+1;
- $scope.FaultItemNo = newFaultItemNo;
- $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+newFaultItemNo});
- $scope.connectTriggerFaultsList.push('Fault'+newFaultItemNo);
- };
- $scope.removeVerFaultButton = function() {
- var lastFaultItem = $scope.temp.policy.faulttriggerSignatures.length-1;
- $scope.temp.policy.faulttriggerSignatures.splice(lastFaultItem);
- $scope.connectTriggerFaultsList.splice('Fault'+lastFaultItem);
- };
- if($scope.temp.policy.triggerfaultSignatures == undefined){
- $scope.temp.policy.triggerfaultSignatures = [];
- }
-
- $scope.faultItemNo1 = 0;
- $scope.FaultTriggerSignatureDatas = [{"verificationSignatures" : $scope.temp.policy.triggerfaultSignatures}];
- $scope.addVerTriggerButton = function(indexId) {
- $scope.verificationdisabled = false;
- if(faultCollection.indexOf(indexId) !== -1){
+
+ $scope.trapItemNo = 0;
+ $scope.TrapTriggerSignatureDatas = [{"triggermainSignatures" : $scope.temp.policy.triggerTrapSignatures}];
+ $scope.addTrapTriggerButton = function(indexId) {
+ if(trapCollection.indexOf(indexId) === -1){
+ $scope.temp.policy.triggerTrapSignatures[indexId] = [];
+ trapCollection.push(indexId);
+ }
+ var newTrapItemNo = $scope.temp.policy.triggerTrapSignatures[indexId].length+1;
+ $scope.trapItemNo = newTrapItemNo;
+ $scope.temp.policy.triggerTrapSignatures.push($scope.temp.policy.triggerTrapSignatures[indexId].push({'id':'A'+newTrapItemNo}));
+ if(newTrapItemNo > 1){
+ var count = newTrapItemNo-1;
+ $scope.varbindDictionaryDatas.push('A'+count);
+ }
+ };
+ $scope.removeTrapTriggerButton = function(indexId) {
+ var lastTrapItem = $scope.temp.policy.triggerTrapSignatures[indexId].length-1;
+ var checkLastTrapItem = lastTrapItem;
+ if(checkLastTrapItem == 0){
+ trapCollection.splice(indexId);
+ }
+ $scope.temp.policy.triggerTrapSignatures[indexId].splice(lastTrapItem);
+ };
- }else{
- $scope.temp.policy.triggerfaultSignatures[indexId] = [];
- faultCollection.push(indexId);
- }
- var newFaultItemNo1 = $scope.temp.policy.triggerfaultSignatures[indexId].length+1;
- $scope.faultItemNo1 = newFaultItemNo1;
- $scope.temp.policy.triggerfaultSignatures.push($scope.temp.policy.triggerfaultSignatures[indexId].push({'id':'A'+newFaultItemNo1}));
- if(newFaultItemNo1 > 1){
- var count = newFaultItemNo1-1;
- $scope.varbindDictionaryDatas.push('A'+count);
- }
- };
- $scope.removeVerTriggerButton = function(indexId) {
- var lastFaultItem1 = $scope.temp.policy.triggerfaultSignatures[indexId].length-1;
- var checkLastFaultItem = lastFaultItem1;
- if(checkLastFaultItem == 0){
- faultCollection.splice(indexId);
- }
- $scope.temp.policy.triggerfaultSignatures[indexId].splice(lastFaultItem1);
- };
+ if($scope.temp.policy.connecttriggerSignatures == undefined){
+ $scope.temp.policy.connecttriggerSignatures = [];
+ }
+
+ $scope.connecttrapItemNo = 0;
+ $scope.TrapConnectTriggerSignatureDatas = [{"connecttriggerSignatures" : $scope.temp.policy.connecttriggerSignatures}];
+ $scope.addTriggerConnectButton = function() {
+ var newConnectTrapItemNo = $scope.temp.policy.connecttriggerSignatures.length+1;
+ $scope.connecttrapItemNo = newConnectTrapItemNo;
+ $scope.temp.policy.connecttriggerSignatures.push({'id':'C'+newConnectTrapItemNo});
+ if(newConnectTrapItemNo >1){
+ var count = newConnectTrapItemNo-1;
+ $scope.connectTriggerTrapsList.push('C'+count);
+ }
+ };
+ $scope.removeTriggerConnectButton = function() {
+ var lastConnectTrapItem = $scope.temp.policy.connecttriggerSignatures.length-1;
+ $scope.temp.policy.connecttriggerSignatures.splice(lastConnectTrapItem);
+ if(lastConnectTrapItem < 1){
+ var count = lastConnectTrapItem-1;
+ $scope.connectTriggerTrapsList.splice('C'+count);
+ }
+ };
+ if($scope.connectTriggerFaultsList == undefined){
+ $scope.connectTriggerFaultsList = [];
+ }
+ if($scope.temp.policy.faulttriggerSignatures == undefined){
+ $scope.temp.policy.faulttriggerSignatures = [];
+ }
+
+ $scope.FaultItemNo = 0;
+ $scope.FaultSignatureDatas = [{"verificationmainSignatures" : $scope.temp.policy.faulttriggerSignatures}];
+ $scope.addVerFaultButton = function() {
+ var newFaultItemNo = $scope.temp.policy.faulttriggerSignatures.length+1;
+ $scope.FaultItemNo = newFaultItemNo;
+ $scope.temp.policy.faulttriggerSignatures.push({'id':'Fault'+newFaultItemNo});
+ $scope.connectTriggerFaultsList.push('Fault'+newFaultItemNo);
+ };
+ $scope.removeVerFaultButton = function() {
+ var lastFaultItem = $scope.temp.policy.faulttriggerSignatures.length-1;
+ $scope.temp.policy.faulttriggerSignatures.splice(lastFaultItem);
+ $scope.connectTriggerFaultsList.splice('Fault'+lastFaultItem);
+ };
+ if($scope.temp.policy.triggerfaultSignatures == undefined){
+ $scope.temp.policy.triggerfaultSignatures = [];
+ }
+
+ $scope.faultItemNo1 = 0;
+ $scope.FaultTriggerSignatureDatas = [{"verificationSignatures" : $scope.temp.policy.triggerfaultSignatures}];
+ $scope.addVerTriggerButton = function(indexId) {
+ $scope.verificationdisabled = false;
+ if(faultCollection.indexOf(indexId) === -1){
+ $scope.temp.policy.triggerfaultSignatures[indexId] = [];
+ faultCollection.push(indexId);
+ }
+ var newFaultItemNo1 = $scope.temp.policy.triggerfaultSignatures[indexId].length+1;
+ $scope.faultItemNo1 = newFaultItemNo1;
+ $scope.temp.policy.triggerfaultSignatures.push($scope.temp.policy.triggerfaultSignatures[indexId].push({'id':'A'+newFaultItemNo1}));
+ if(newFaultItemNo1 > 1){
+ var count = newFaultItemNo1-1;
+ $scope.varbindDictionaryDatas.push('A'+count);
+ }
+ };
+ $scope.removeVerTriggerButton = function(indexId) {
+ var lastFaultItem1 = $scope.temp.policy.triggerfaultSignatures[indexId].length-1;
+ var checkLastFaultItem = lastFaultItem1;
+ if(checkLastFaultItem == 0){
+ faultCollection.splice(indexId);
+ }
+ $scope.temp.policy.triggerfaultSignatures[indexId].splice(lastFaultItem1);
+ };
- if($scope.temp.policy.connectVerificationSignatures == undefined){
- $scope.temp.policy.connectVerificationSignatures = [];
- }
-
- $scope.connectFaultItemNo = 0;
- $scope.FaultConnectTriggerSignatureDatas = [{"connectVerificationSignatures" : $scope.temp.policy.connectVerificationSignatures}];
- $scope.addFaultConnectButton = function() {
- var newConnectFaultItemNo = $scope.temp.policy.connectVerificationSignatures.length+1;
- $scope.connectFaultItemNo = newConnectFaultItemNo;
- $scope.temp.policy.connectVerificationSignatures.push({'id':'C'+newConnectFaultItemNo});
- if(newConnectFaultItemNo >1){
- var count = newConnectFaultItemNo-1;
- $scope.connectTriggerFaultsList.push('C'+count);
- }
- };
- $scope.removeFaultConnectButton = function() {
- var lastConnectFaultItem = $scope.temp.policy.connectVerificationSignatures.length-1;
- $scope.temp.policy.connectVerificationSignatures.splice(lastConnectFaultItem);
- if(lastConnectFaultItem < 1){
- var count = lastConnectFaultItem-1;
- $scope.connectTriggerFaultsList.splice('C'+count);
- }
- };
+ if($scope.temp.policy.connectVerificationSignatures == undefined){
+ $scope.temp.policy.connectVerificationSignatures = [];
+ }
+
+ $scope.connectFaultItemNo = 0;
+ $scope.FaultConnectTriggerSignatureDatas = [{"connectVerificationSignatures" : $scope.temp.policy.connectVerificationSignatures}];
+ $scope.addFaultConnectButton = function() {
+ var newConnectFaultItemNo = $scope.temp.policy.connectVerificationSignatures.length+1;
+ $scope.connectFaultItemNo = newConnectFaultItemNo;
+ $scope.temp.policy.connectVerificationSignatures.push({'id':'C'+newConnectFaultItemNo});
+ if(newConnectFaultItemNo >1){
+ var count = newConnectFaultItemNo-1;
+ $scope.connectTriggerFaultsList.push('C'+count);
+ }
+ };
+ $scope.removeFaultConnectButton = function() {
+ var lastConnectFaultItem = $scope.temp.policy.connectVerificationSignatures.length-1;
+ $scope.temp.policy.connectVerificationSignatures.splice(lastConnectFaultItem);
+ if(lastConnectFaultItem < 1){
+ var count = lastConnectFaultItem-1;
+ $scope.connectTriggerFaultsList.splice('C'+count);
+ }
+ };
-}]); \ No newline at end of file
+}]);
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopPMController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopPMController.js
index a67266074..454a724a9 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopPMController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ClosedLoopPMController.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.
@@ -29,7 +29,7 @@ angular.module("abs").controller('clPMController', ['$scope', '$window', '$timeo
policyType : "Config",
configPolicyType : "ClosedLoop_PM"
}
- };
+ }
$scope.refresh = function(){
if($scope.refreshCheck){
@@ -193,4 +193,4 @@ angular.module("abs").controller('clPMController', ['$scope', '$window', '$timeo
});
};
-}]); \ No newline at end of file
+}]);
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DCAEMicroServicePolicyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DCAEMicroServicePolicyController.js
index cffa46f53..1e452e830 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DCAEMicroServicePolicyController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DCAEMicroServicePolicyController.js
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 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,7 +18,9 @@
* ============LICENSE_END=========================================================
*/
-angular.module('abs').controller('dcaeMicroServiceController', ['$scope', '$window', '$compile', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', function ($scope, $window, $compile, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) {
+angular.module('abs').controller('dcaeMicroServiceController',
+ ['$scope', '$window', '$compile', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification',
+ function ($scope, $window, $compile, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) {
$("#dialog").hide();
$scope.policyNavigator;
@@ -29,18 +31,18 @@ angular.module('abs').controller('dcaeMicroServiceController', ['$scope', '$wind
var layer = 0;
if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
- $scope.temp.policy = {
- policyType : "Config",
- configPolicyType : "Micro Service"
- }
- };
+ $scope.temp.policy = {
+ policyType : "Config",
+ configPolicyType : "Micro Service"
+ }
+ }
$scope.refresh = function(){
- if($scope.refreshCheck){
- $scope.policyNavigator.refresh();
- }
- $scope.modal('createNewPolicy', true);
- $scope.temp.policy = "";
+ if($scope.refreshCheck){
+ $scope.policyNavigator.refresh();
+ }
+ $scope.modal('createNewPolicy', true);
+ $scope.temp.policy = "";
};
$scope.modal = function(id, hide) {
@@ -48,328 +50,290 @@ angular.module('abs').controller('dcaeMicroServiceController', ['$scope', '$wind
};
$('#ttlDate').datepicker({
- dateFormat: 'dd/mm/yy',
- changeMonth: true,
- changeYear: true,
- onSelect: function(date) {
- angular.element($('#ttlDate')).triggerHandler('input');
- }
+ dateFormat: 'dd/mm/yy',
+ changeMonth: true,
+ changeYear: true,
+ onSelect: function(date) {
+ angular.element($('#ttlDate')).triggerHandler('input');
+ }
});
- if ($scope.temp.policy.editPolicy != undefined|| $scope.temp.policy.readOnly != undefined){
- if ($scope.temp.policy.configName == undefined){
- $scope.isCheck = false;
- }else{
- $scope.isCheck = true;
- }
- }else {
- $scope.isCheck = false;
- }
-
- 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);
- console.log($scope.onapNameDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ if ($scope.temp.policy.editPolicy != undefined|| $scope.temp.policy.readOnly != undefined){
+ if ($scope.temp.policy.configName == undefined){
+ $scope.isCheck = false;
+ }else{
+ $scope.isCheck = true;
+ }
+ }else {
+ $scope.isCheck = false;
+ }
+
+ PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
+ });
- PolicyAppService.getData('get_DCAEPriorityValues').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.priorityDatas = JSON.parse($scope.data.priorityDatas);
- console.log($scope.priorityDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('get_DCAEPriorityValues').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.priorityDatas = JSON.parse($scope.data.priorityDatas);
+ });
- PolicyAppService.getData('getDictionary/get_GroupPolicyScopeDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.groupPolicyScopeListDatas = JSON.parse($scope.data.groupPolicyScopeListDatas);
- console.log($scope.groupPolicyScopeListDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_GroupPolicyScopeDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.groupPolicyScopeListDatas = JSON.parse($scope.data.groupPolicyScopeListDatas);
+ });
- PolicyAppService.getData('getDictionary/get_MicroServiceConfigNameDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- console.log("$scope.data.microServiceConfigNameDictionaryDatas : " + $scope.data.microServiceConfigNameDictionaryDatas);
- if($scope.data.microServiceConfigNameDictionaryDatas){
- $scope.microServiceCongigNameDictionaryDatas = JSON.parse($scope.data.microServiceConfigNameDictionaryDatas);
- }
- console.log($scope.microServiceCongigNameDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_MicroServiceConfigNameDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ if($scope.data.microServiceConfigNameDictionaryDatas){
+ $scope.microServiceCongigNameDictionaryDatas = JSON.parse($scope.data.microServiceConfigNameDictionaryDatas);
+ }
+ });
- PolicyAppService.getData('getDictionary/get_MicroServiceLocationDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.microServiceLocationDictionaryDatas = JSON.parse($scope.data.microServiceLocationDictionaryDatas);
- console.log($scope.microServiceLocationDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_MicroServiceLocationDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.microServiceLocationDictionaryDatas = JSON.parse($scope.data.microServiceLocationDictionaryDatas);
+ });
- PolicyAppService.getData('getDictionary/get_MicroServiceModelsDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- var inputModelList = JSON.parse($scope.data.microServiceModelsDictionaryDatas);
- var unique = {};
- var uniqueList = [];
- for(var i = 0; i < inputModelList.length; i++){
- if(typeof unique[inputModelList[i]] == "undefined"){
- unique[inputModelList[i]] = "";
- uniqueList.push(inputModelList[i]);
- }
- }
- $scope.microServiceModelsDictionaryDatas = uniqueList;
- console.log($scope.microServiceModelsDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_MicroServiceModelsDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ var inputModelList = JSON.parse($scope.data.microServiceModelsDictionaryDatas);
+ var unique = {};
+ var uniqueList = [];
+ for(var i = 0; i < inputModelList.length; i++){
+ if(typeof unique[inputModelList[i]] == "undefined"){
+ unique[inputModelList[i]] = "";
+ uniqueList.push(inputModelList[i]);
+ }
+ }
+ $scope.microServiceModelsDictionaryDatas = uniqueList;
+ });
- PolicyAppService.getData('getDictionary/get_DCAEUUIDDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.dcaeUUIDDictionaryDatas = JSON.parse($scope.data.dcaeUUIDDictionaryDatas);
- console.log($scope.dcaeUUIDDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_DCAEUUIDDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.dcaeUUIDDictionaryDatas = JSON.parse($scope.data.dcaeUUIDDictionaryDatas);
+ });
- PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
- console.log($scope.riskTypeDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
+ });
- PolicyAppService.getData('getDictionary/get_MicroServiceAttributeData').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.microServiceAttributeDictionaryDatas = JSON.parse($scope.data.microServiceAttributeDictionaryDatas);
- console.log($scope.microServiceAttributeDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
-
+ PolicyAppService.getData('getDictionary/get_MicroServiceAttributeData').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.microServiceAttributeDictionaryDatas = JSON.parse($scope.data.microServiceAttributeDictionaryDatas);
+ });
+
- $scope.choices = [];
- $scope.attributeDatas = [{"attributes" : $scope.choices}];
- addNewChoice = function(value) {
- console.log("input key : " + value);
- var isFoundInRuleData = false;
- if(value != undefined){
- if (value.startsWith('div.')){
- value = value.replace('div.','');
- }
-
- console.log(" document.getElementById : div."+value);
- var parentElement = document.getElementById("div."+value);
- console.log("parentElement : " + parentElement);
- var div = document.getElementById(value+"@0");
- if(div != null){
- var clone = div.cloneNode(true);
- var addElement = parentElement.childElementCount;
- clone.id = ''+value+'@'+addElement;
- clone.value = '';
- if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){ //if it's view or edit
- if($scope.temp.policy.ruleData[clone.id] || $scope.temp.policy.editPolicy){ // Only append child if its value found in ruleData or edit mode
- if($scope.temp.policy.ruleData[clone.id]){
- clone.value = $scope.temp.policy.ruleData[clone.id];
- isFoundInRuleData = true;
- }
- console.log(" clone.value :" + clone.value);
- console.log(" clone.id :" + clone.id);
- if(!isFoundInRuleData && isInitViewEdit){
- return;
- }
- if(!clone.className.includes("child_single")){
- clone.className += ' child_single'; //here cloned is single element
- }
- document.getElementById("div."+value).appendChild(clone);
- plainAttributeKeys.push(''+value+'@'+addElement);
- }
- }else{ //not view or edit
- if(!clone.className.includes("child_single")){
- clone.className += ' child_single'; //here cloned is single element
- }
- document.getElementById("div."+value).appendChild(clone);
- plainAttributeKeys.push(''+value+'@'+addElement);
- }
- }else{
-
- if(parentElement == null){
- return;
- }
- div = document.getElementById("div."+value+"@0");
- if(div){
-
- if(!div.className.includes('children_group border')){
- layer++;
- if(layer > 4){
- layer = 1
- };
- div.className += ' children_group border' + layer; //here is div with a group of children.
- }
- }
- var childElement = parentElement.firstElementChild;
- var countParent = parentElement.childElementCount;
- var childElementString = childElement.innerHTML;
- var find = value+"@0";
- var re = new RegExp(find, 'g');
- childElementString = childElementString.replace(re,value+'@' + countParent);
- var clone = childElement.cloneNode(true);
- for (var ii = 0; ii < parentElement.childNodes.length; ii++){
- var childId = parentElement.childNodes[ii].id;
- if(ii = parentElement.childNodes.length){
- var childnewId = childId.slice(0, -1);
- var count = childId.slice(-1);
- }
- }
- var countvalue = parseInt(count) + 1;
- clone.id = childnewId+countvalue;
- clone.value = '';
- clone.innerHTML=childElementString;
- document.getElementById("div."+value).appendChild(clone);
- var selects = clone.getElementsByTagName("select");
- var inputs = clone.getElementsByTagName("input");
- var removeValues = [];
- for(var i=0; i<inputs.length; i++){
- if ($scope.temp.policy.ruleData!=undefined){
- var checkValue = $scope.temp.policy.ruleData[inputs[i].id];
- console.log(" checkValue.value :" + checkValue);
- console.log(" inputs["+i+"].id :" + inputs[i].id);
- if (checkValue!=undefined && checkValue != "undefined"){
- document.getElementById(inputs[i].id).value = checkValue;
- plainAttributeKeys.push(inputs[i].id);
- } else {
- plainAttributeKeys.push(inputs[i].id);
- }
- }else {
- plainAttributeKeys.push(inputs[i].id);
- }
- }
-
- for(var i=0; i<selects.length; i++){
- if ($scope.temp.policy.ruleData!=undefined){
- var checkValue = $scope.temp.policy.ruleData[selects[i].id];
- if (checkValue!=undefined && checkValue!="undefined"){
- if($scope.temp.policy.ruleData != null){
- var checkValue = $scope.temp.policy.ruleData[selects[i].id];
- var option = document.createElement('option');
- option.setAttribute('value', checkValue);
- option.appendChild(document.createTextNode(checkValue));
- document.getElementById(selects[i].id).appendChild(option);
- document.getElementById(selects[i].id).value = $scope.temp.policy.ruleData[selects[i].id];
- plainAttributeKeys.push(selects[i].id);
- }
- } else {
- plainAttributeKeys.push(selects[i].id);
- }
- }else {
- plainAttributeKeys.push(selects[i].id);
- }
- }
-
- for (var k=0; k<removeValues.length; k++){
- var elem = document.getElementById(removeValues[k]);
- elem.parentNode.removeChild(elem);
- }
- var ele = angular.element(document.getElementById("div."+value));
- $compile(ele.contents())($scope)
- }
- }
- };
-
-
- removeChoice = function(value) {
- console.log(value);
- if(value != undefined){
- var c = document.getElementById("div."+value).childElementCount;
-
- if(c == 1){
- Notification.error("The original one is not removable.");
- return;
- }
- document.getElementById("div."+value).removeChild(document.getElementById("div."+value).lastChild);
- }
- };
-
- function findVal(object, key) {
- var value;
- Object.keys(object).some(function(k) {
- if (k === key) {
- value = object[k];
- return true;
- }
- if (object[k] && typeof object[k] === 'object') {
- value = findVal(object[k], key);
- return value !== undefined;
- }
- });
- return value;
- }
-
- $scope.pullVersion = function(serviceName) {
- console.log(serviceName);
- if(serviceName != undefined){
- var uuu = "policyController/getModelServiceVersioneData.htm";
- var postData={policyData: serviceName};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.microServiceModelsDictionaryVersionDatas = data[0].dcaeModelVersionData;
- });
- },
- error : function(data){
- alert("Error While Retriving the Template Layout Pattren.");
- }
- });
- }
- };
+ $scope.choices = [];
+ $scope.attributeDatas = [{"attributes" : $scope.choices}];
+ addNewChoice = function(value) {
+ var isFoundInRuleData = false;
+ if(value != undefined){
+ if (value.startsWith('div.')){
+ value = value.replace('div.','');
+ }
+
+ var parentElement = document.getElementById("div."+value);
+ var div = document.getElementById(value+"@0");
+ if(div != null){
+ var clone = div.cloneNode(true);
+ var addElement = parentElement.childElementCount;
+ clone.id = ''+value+'@'+addElement;
+ clone.value = '';
+ if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){
+ //if it's vi or edit
+ if($scope.temp.policy.ruleData[clone.id] || $scope.temp.policy.editPolicy){
+ //Only append child if its value found in ruleData or edit mode
+ if($scope.temp.policy.ruleData[clone.id]){
+ clone.value = $scope.temp.policy.ruleData[clone.id];
+ isFoundInRuleData = true;
+ }
+ if(!isFoundInRuleData && isInitViewEdit){
+ return;
+ }
+ if(!clone.className.includes("child_single")){
+ clone.className += ' child_single'; // here cloned is single element
+ }
+ document.getElementById("div."+value).appendChild(clone);
+ plainAttributeKeys.push(''+value+'@'+addElement);
+ }
+ }else{ // not view or edit
+ if(!clone.className.includes("child_single")){
+ clone.className += ' child_single'; // here cloned is single element
+ }
+ document.getElementById("div."+value).appendChild(clone);
+ plainAttributeKeys.push(''+value+'@'+addElement);
+ }
+ }else{
+
+ if(parentElement == null){
+ return;
+ }
+ div = document.getElementById("div."+value+"@0");
+ if(div){
+
+ if(!div.className.includes('children_group border')){
+ layer++;
+ if(layer > 4){
+ layer = 1
+ }
+ div.className += ' children_group border' + layer; // here is div with a group of children.
+ }
+ }
+ var childElement = parentElement.firstElementChild;
+ var countParent = parentElement.childElementCount;
+ var childElementString = childElement.innerHTML;
+ var find = value+"@0";
+ var re = new RegExp(find, 'g');
+ childElementString = childElementString.replace(re,value+'@' + countParent);
+ var clone = childElement.cloneNode(true);
+ for (var ii = 0; ii < parentElement.childNodes.length; ii++){
+ var childId = parentElement.childNodes[ii].id;
+ if(ii = parentElement.childNodes.length){
+ var childnewId = childId.slice(0, -1);
+ var count = childId.slice(-1);
+ }
+ }
+ var countvalue = parseInt(count) + 1;
+ clone.id = childnewId+countvalue;
+ clone.value = '';
+ clone.innerHTML=childElementString;
+ document.getElementById("div."+value).appendChild(clone);
+ var selects = clone.getElementsByTagName("select");
+ var inputs = clone.getElementsByTagName("input");
+ var removeValues = [];
+ for(var i=0; i<inputs.length; i++){
+ plainAttributeKeys.push(inputs[i].id);
+ if ($scope.temp.policy.ruleData!=undefined){
+ var checkValue = $scope.temp.policy.ruleData[inputs[i].id];
+ if (checkValue!=undefined && checkValue != "undefined"){
+ if(checkValue == "false"){
+ document.getElementById(inputs[i].id).removeAttribute("checked");
+ }
+ else if(checkValue == "true"){
+ document.getElementById(inputs[i].id).setAttribute("checked", true);
+ }else{
+ document.getElementById(inputs[i].id).value = checkValue;
+ }
+ } else {
+ if(inputs[i].type == "checkbox"){
+ inputs[i].checked = false;
+ }
+ }
+ }else {
+ document.getElementById(inputs[i].id).removeAttribute("checked");
+ }
+ }
+
+ for(var i=0; i<selects.length; i++){
+ if ($scope.temp.policy.ruleData!=undefined){
+ var checkValue = $scope.temp.policy.ruleData[selects[i].id];
+ if (checkValue!=undefined && checkValue!="undefined"){
+ if($scope.temp.policy.ruleData != null){
+ var checkValue = $scope.temp.policy.ruleData[selects[i].id];
+ var option = document.createElement('option');
+ option.setAttribute('value', checkValue);
+ option.appendChild(document.createTextNode(checkValue));
+ document.getElementById(selects[i].id).appendChild(option);
+ document.getElementById(selects[i].id).value = $scope.temp.policy.ruleData[selects[i].id];
+ plainAttributeKeys.push(selects[i].id);
+ }
+ } else {
+ plainAttributeKeys.push(selects[i].id);
+ }
+ }else {
+ plainAttributeKeys.push(selects[i].id);
+ }
+ }
+
+ for (var k=0; k<removeValues.length; k++){
+ var elem = document.getElementById(removeValues[k]);
+ elem.parentNode.removeChild(elem);
+ }
+ var ele = angular.element(document.getElementById("div."+value));
+ $compile(ele.contents())($scope)
+ }
+ }
+ };
+
+
+ removeChoice = function(value) {
+ if(value != undefined){
+ var c = document.getElementById("div."+value).childElementCount;
+
+ if(c == 1){
+ Notification.error("The original one is not removable.");
+ return;
+ }
+ document.getElementById("div."+value).removeChild(document.getElementById("div."+value).lastChild);
+ }
+ };
+
+ function findVal(object, key) {
+ var value;
+ Object.keys(object).some(function(k) {
+ if (k === key) {
+ value = object[k];
+ return true;
+ }
+ if (object[k] && typeof object[k] === 'object') {
+ value = findVal(object[k], key);
+ return value !== undefined;
+ }
+ });
+ return value;
+ }
+
+ $scope.pullVersion = function(serviceName) {
+ if(serviceName != undefined){
+ var uuu = "policyController/getModelServiceVersioneData.htm";
+ var postData={policyData: serviceName};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.microServiceModelsDictionaryVersionDatas = data[0].dcaeModelVersionData;
+ });
+ },
+ error : function(data){
+ Notification.error("Error While Retriving the Template Layout Pattren.");
+ }
+ });
+ }
+ };
- var splitDash = '-';
- var splitEqual = '=';
- var splitComma = ',';
- var splitcolon = ':';
- var splitsemicolon = ";";
- var splitEnum = "],";
- var plainAttributeKeys = [];
- var matching = [];
- var enumKeyList = [];
- var dictionaryList = [];
- var dictionaryNameList = [];
- var isInitViewEdit = false;
+ var splitEqual = '=';
+ var splitComma = ',';
+ var splitcolon = ':';
+ var splitEnum = "],";
+ var plainAttributeKeys = [];
+ var matching = [];
+ var enumKeyList = [];
+ var dictionaryList = [];
+ var dictionaryNameList = [];
+ var isInitViewEdit = false;
$scope.addDataToFields = function(serviceName, version){
if(serviceName != null && version !=null){
- var service=serviceName+"-v"+version;
- var myNode = document.getElementById("DynamicTemplate");
- myNode.innerHTML = '';
+ var service=serviceName+"-v"+version;
+ var myNode = document.getElementById("DynamicTemplate");
+ myNode.innerHTML = '';
var uuu = "policyController/getDCAEMSTemplateData.htm";
var postData={policyData: service};
- console.log("service: " +service);
var dataOrderInfo = "";
@@ -384,217 +348,206 @@ angular.module('abs').controller('dcaeMicroServiceController', ['$scope', '$wind
contentType: 'application/json',
data: JSON.stringify(postData),
success : function(data){
-
- document.getElementById("msPolicyloader").style.visibility = "hidden";
-
+
+ document.getElementById("msPolicyloader").style.visibility = "hidden";
+
$scope.$apply(function(){
- var plainAttributeKeys = [];
- $scope.dcaeModelData = data[0].dcaeModelData;
- $scope.dcaeJsonDate = data[0].jsonValue;
+ $scope.dcaeModelData = data[0].dcaeModelData;
+ $scope.dcaeJsonDate = data[0].jsonValue;
$scope.dataOrderInfo = null;
- $scope.dataOrderInfo = data[0].dataOrderInfo;
- console.log("data[0].dataOrderInfo: " + data[0].dataOrderInfo);
- console.log("$scope.dataOrderInfo: " + $scope.dataOrderInfo);
-
- if(data[0].allManyTrueKeys){
- console.log("$scope.allManyTrueKeys: " + $scope.allManyTrueKeys);
- }
- console.log("$scope.dcaeJsonDate: " + $scope.dcaeJsonDate);
- var attributes = $scope.dcaeModelData.attributes;
- console.log("attributes: " +attributes);
- var refAttributes = $scope.dcaeModelData.ref_attributes;
- var subAttributes = $scope.dcaeModelData.sub_attributes;
- console.log("subAttributes: " + subAttributes);
- console.log("refAttributes: " + refAttributes);
- var headDefautlsData = data[0].headDefautlsData;
- if(headDefautlsData != null){
- $scope.temp.policy.onapName = headDefautlsData.onapName;
- $scope.temp.policy.guard = headDefautlsData.guard;
- $scope.temp.policy.riskType = headDefautlsData.riskType;
- $scope.temp.policy.riskLevel = headDefautlsData.riskLevel;
- $scope.temp.policy.priority = headDefautlsData.priority;
- }
-
- var enumAttributes = $scope.dcaeModelData.enumValues;
- var annotation = $scope.dcaeModelData.annotation;
- var dictionary = $scope.microServiceAttributeDictionaryDatas;
+ $scope.dataOrderInfo = data[0].dataOrderInfo;
+
+ if(data[0].allManyTrueKeys){
+ }
+ var attributes = $scope.dcaeModelData.attributes;
+ var refAttributes = $scope.dcaeModelData.ref_attributes;
+ var subAttributes = $scope.dcaeModelData.sub_attributes;
+ var headDefautlsData = data[0].headDefautlsData;
+ if(headDefautlsData != null){
+ $scope.temp.policy.onapName = headDefautlsData.onapName;
+ $scope.temp.policy.guard = headDefautlsData.guard;
+ $scope.temp.policy.riskType = headDefautlsData.riskType;
+ $scope.temp.policy.riskLevel = headDefautlsData.riskLevel;
+ $scope.temp.policy.priority = headDefautlsData.priority;
+ }
+
+ var annotation = $scope.dcaeModelData.annotation;
+ var dictionary = $scope.microServiceAttributeDictionaryDatas;
- if (annotation == null || annotation.length<1){
- $scope.isCheck = true;
- }else {
- $scope.isCheck = false;
- var annoationList = annotation.split(splitComma);
- for (k = 0; k < annoationList.length; k++){
- var splitAnnotation = annoationList[k].split(splitEqual);
- if (splitAnnotation[1].includes("matching-true")){
- matching.push(splitAnnotation[0].trim());
- }
- }
+ if (annotation == null || annotation.length<1){
+ $scope.isCheck = true;
+ }else {
+ $scope.isCheck = false;
+ var annoationList = annotation.split(splitComma);
+ for (k = 0; k < annoationList.length; k++){
+ var splitAnnotation = annoationList[k].split(splitEqual);
+ if (splitAnnotation[1].includes("matching-true")){
+ matching.push(splitAnnotation[0].trim());
+ }
+ }
- }
+ }
- if (dictionary!= null && dictionary.length>1){
- for (m=0; m < dictionary.length; m += 1){
- var keyCompare = dictionary[m].name;
- var valueCompare = dictionary[m].value;
- var valueModel = dictionary[m].modelName;
- var conpairService = serviceName;
- if (valueModel.includes('-v')){
- conpairService = service;
- }
- if(valueModel.localeCompare(conpairService) == 0){
- console.log(valueCompare);
- dictionaryList.push(dictionary[m]);
- if (!dictionaryNameList.includes(dictionary[m].name)){
- dictionaryNameList.push(dictionary[m].name)
- }
- }
- }
- }
+ if (dictionary!= null && dictionary.length>1){
+ for (m=0; m < dictionary.length; m += 1){
+ var valueCompare = dictionary[m].value;
+ var valueModel = dictionary[m].modelName;
+ var conpairService = serviceName;
+ if (valueModel.includes('-v')){
+ conpairService = service;
+ }
+ if(valueModel.localeCompare(conpairService) == 0){
+ dictionaryList.push(dictionary[m]);
+ if (!dictionaryNameList.includes(dictionary[m].name)){
+ dictionaryNameList.push(dictionary[m].name)
+ }
+ }
+ }
+ }
- $scope.temp.policy.ruleGridData = [];
-
- if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){
- dataOrderInfo = $scope.dataOrderInfo;
- }
-
- $scope.jsonLayout($scope.dcaeJsonDate);
-
+ $scope.temp.policy.ruleGridData = [];
+
+ if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){
+ dataOrderInfo = $scope.dataOrderInfo;
+ }
+
+ $scope.jsonLayout($scope.dcaeJsonDate);
+
});
if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){ // If it's veiw or edit
- isInitViewEdit = true;
- var checkData = [];
- var data = [];
- // If ruleData contains extra elements created by clicked add button
- console.log("$scope.temp.policy.ruleData:" + $scope.temp.policy.ruleData);
- if($scope.temp.policy.ruleData != null){
- var propNames = Object.getOwnPropertyNames($scope.temp.policy.ruleData);
- propNames.forEach(function(name) {
- data.push(name);
- });
-
- var extraElements = data;
-
- if(plainAttributeKeys != null){
- for(var b = 0; b < plainAttributeKeys.length; b++){ // Remove already populated elements from data array
- var newValue = plainAttributeKeys[b].split("*");
- for(var a = 0; a < data.length; a++){
- if(data[a] === newValue[0] || data[a] === (newValue[0]+"@0")){
- extraElements.splice(a, 1);
- }
- }
- }
-
- //--- Populate these extra elements created by clicked add button
- for(var a = 0; a < extraElements.length; a++){
- if(extraElements[a].includes("@")){
- var index = extraElements[a].lastIndexOf("@");
- if(index > 0){
- // Get the number after @
- var n = getNumOfDigits(extraElements[a], index+1);
-
- var key = extraElements[a].substring(0, index+n+1); //include @x in key also by n+2 since x can be 1,12, etc
- console.log("key: " + key);
- checkData.push(key);
- }
- }
- }
- var unique = checkData.filter(onlyUnique);
- var parentLevelElements = [];
- if(unique){
- //--- get all root level exta elments first (only contains one "@")
- for(var i =0; i < unique.length; i++){
- var firstIndex = unique[i].indexOf("@");
- var lastIndex = unique[i].lastIndexOf("@");
- if(firstIndex == lastIndex){
- var newKey = unique[i].substring(0, firstIndex);
- console.log("root element: " + newKey);
- parentLevelElements.push(newKey);
- unique[i] = "*processed*";
- }
- }
- }
-
-
- for (var i = 0; i < $scope.labelManyKeys.length; i++) {
- var label = $scope.labelManyKeys[i];
- if(parentLevelElements){
- for (var k = 0; k < parentLevelElements.length; k++){
- if(label == parentLevelElements[k]){
- addNewChoice(label);
- }
- }
- }
- }
-
- //if no layout order info, keep the process as before
- if(!dataOrderInfo){
- for(var i =0; i < unique.length; i++){
- if(unique[i] != "*processed*"){
- var index = unique[i].lastIndexOf("@");
- var newKey = unique[i].substring(0, index);
- console.log("newKey: " + newKey);
-
- var newElement = document.getElementById("div."+unique[j]);
- //check weather it has been created already
+ isInitViewEdit = true;
+ var checkData = [];
+ var data = [];
+ // If ruleData contains extra elements created by clicked add button
+ if($scope.temp.policy.ruleData != null){
+ var propNames = Object.getOwnPropertyNames($scope.temp.policy.ruleData);
+ propNames.forEach(function(name) {
+ if(document.getElementById(name) != null){
+ if(document.getElementById(name).getAttribute("class") == "onoffswitch-checkbox"){
+ if($scope.temp.policy.ruleData[name] == "true"){
+ document.getElementById(name).setAttribute("checked", true);
+ }
+ else{
+ document.getElementById(name).removeAttribute("checked");
+ }
+ }
+ }
+ data.push(name);
+ });
+ var extraElements = data;
+ if(plainAttributeKeys != null){
+ for(var b = 0; b < plainAttributeKeys.length; b++){ // Remove already populated elements from data array
+ var newValue = plainAttributeKeys[b].split("*");
+ for(var a = 0; a < data.length; a++){
+ if(data[a] === newValue[0] || data[a] === (newValue[0]+"@0")){
+ extraElements.splice(a, 1);
+ }
+ }
+ }
+ // --- Populate these extra elements created by clicked add button
+ for(var a = 0; a < extraElements.length; a++){
+ if(extraElements[a].includes("@")){
+ var index = extraElements[a].lastIndexOf("@");
+ if(index > 0){
+ // Get the number after @
+ var n = getNumOfDigits(extraElements[a], index+1);
+ var key = extraElements[a].substring(0, index+n+1); // include @x in key also by n+2 since x can be 1,12,etc
+ checkData.push(key);
+ }
+ }
+ }
+ var unique = checkData.filter(onlyUnique);
+ var parentLevelElements = [];
+ if(unique){
+ // --- get all root level exta elments first (only contains one "@")
+ for(var i =0; i < unique.length; i++){
+ var firstIndex = unique[i].indexOf("@");
+ var lastIndex = unique[i].lastIndexOf("@");
+ if(firstIndex == lastIndex){
+ var newKey = unique[i].substring(0, firstIndex);
+ parentLevelElements.push(newKey);
+ unique[i] = "*processed*";
+ }
+ }
+ }
+ for (var i = 0; i < $scope.labelManyKeys.length; i++) {
+ var label = $scope.labelManyKeys[i];
+ if(parentLevelElements){
+ for (var k = 0; k < parentLevelElements.length; k++){
+ if(label == parentLevelElements[k]){
+ addNewChoice(label);
+ }
+ }
+ }
+ }
+
+ // if no layout order info, keep the process as before
+ if(!dataOrderInfo){
+ for(var i =0; i < unique.length; i++){
+ if(unique[i] != "*processed*"){
+ var index = unique[i].lastIndexOf("@");
+ var newKey = unique[i].substring(0, index);
+
+ var newElement = document.getElementById("div."+unique[j]);
+ // check weather it has been created already
if(newElement != null){
- continue;
+ continue;
}else{
- newElement = document.getElementById(unique[j]);
- if(newElement != null){
- continue;
- }
+ newElement = document.getElementById(unique[j]);
+ if(newElement != null){
+ continue;
+ }
}
- if(newKey){
- addNewChoice(newKey);
- }
- }
- }
- }else{
- //---reset to default
- dataOrderInfo = [];
- $scope.labelManyKeys = [];
-
- //---process none labels
- for (var j = 0; j < unique.length; j++){
- if(unique[j] != "*processed*"){
- // if not created yet
- if(!document.getElementById(unique[j])){
- var index = unique[j].lastIndexOf("@");
- var newKey = unique[j].substring(0, index);
-
- var newElement = document.getElementById("div."+unique[j]);
-
- //check weather it has been created already
+ if(newKey){
+ addNewChoice(newKey);
+ }
+ }
+ }
+ }else{
+ // ---reset to default
+ dataOrderInfo = [];
+ $scope.labelManyKeys = [];
+
+ // ---process none labels
+ for (var j = 0; j < unique.length; j++){
+ if(unique[j] != "*processed*"){
+ // if not created yet
+ if(!document.getElementById(unique[j])){
+ var index = unique[j].lastIndexOf("@");
+ var newKey = unique[j].substring(0, index);
+
+ var newElement = document.getElementById("div."+unique[j]);
+
+ // check weather it has been created already
if(newElement != null){
- continue;
+ continue;
}else{
- newElement = document.getElementById(unique[j]);
- if(newElement != null){
- continue;
- }
+ newElement = document.getElementById(unique[j]);
+ if(newElement != null){
+ continue;
+ }
}
- //if not created yet, then create it.
- addNewChoice(newKey);
-
- }
- }
- }
- }
- }
- }
+ // if not created yet,then create it.
+ addNewChoice(newKey);
+
+ }
+ }
+ }
+ }
+ }
+ }
}
var ele = angular.element(document.getElementById("DynamicTemplate"));
- $compile(ele.contents())($scope);
+ $compile(ele.contents())($scope);
$scope.$apply();
isInitViewEdit = false;
},
error : function(data){
- alert("Error While Retriving the Template Layout Pattren.");
+ Notification.error("Error While Retriving the Template Layout Pattren.");
}
});
@@ -602,991 +555,967 @@ angular.module('abs').controller('dcaeMicroServiceController', ['$scope', '$wind
};
function getNumOfDigits(str_value, index){
- // Get the number after @
- var str = str_value.substring(index, str_value.length);
- var c = '';
- var n = 0;
- for (var x = 0; x < str.length; x++){
- c = str.charAt(x);
- if(!isNaN(c)){
+ // Get the number after @
+ var str = str_value.substring(index, str_value.length);
+ var c = '';
+ var n = 0;
+ for (var x = 0; x < str.length; x++){
+ c = str.charAt(x);
+ if(!isNaN(c)){
n++;
- }else{
+ }else{
break;
}
- }
- return n;
+ }
+ return n;
}
function getDictionary(attribute){
- var dicName = attribute;
- if(attribute){
- if(attribute.includes(":")){
- dicName = attribute.split(":")[0];
- }
- }
- var dictionaryRegExp = new RegExp(dicName);
- listemunerateValues = [];
- if (dictionaryRegExp.test(dictionaryNameList)) {
- for (p=0; p < dictionaryList.length; p += 1) {
- if (dicName == dictionaryList[p].name) {
- listemunerateValues.push(dictionaryList[p].value);
- }
- }
- }
- return listemunerateValues;
+ var dicName = attribute;
+ if(attribute){
+ if(attribute.includes(":")){
+ dicName = attribute.split(":")[0];
+ }
+ }
+ var dictionaryRegExp = new RegExp(dicName);
+ listemunerateValues = [];
+ if (dictionaryRegExp.test(dictionaryNameList)) {
+ for (p=0; p < dictionaryList.length; p += 1) {
+ if (dicName == dictionaryList[p].name) {
+ listemunerateValues.push(dictionaryList[p].value);
+ }
+ }
+ }
+ return listemunerateValues;
}
function getList(attribute) {
- var enumName = attribute;
- console.log("In getList: attribute => " + attribute);
- if(attribute){
- if(attribute.includes(":")){
- enumName = attribute.split(":")[0];
- }
- }
+ var enumName = attribute;
+ if(attribute){
+ if(attribute.includes(":")){
+ enumName = attribute.split(":")[0];
+ }
+ }
var baseEnum = $scope.dcaeModelData.enumValues;
var enumList = [];
if(baseEnum != null){
- enumList = baseEnum.split(splitEnum);
+ enumList = baseEnum.split(splitEnum);
}
- var enumAttributes;
- var patternTest = new RegExp(enumName);
- for (k=0; k < enumList.length; k += 1){
- if(patternTest.test(enumList[k]) == true){
- enumAttributes = enumList[k].trim();
- }
- }
+ var enumAttributes;
+ var patternTest = new RegExp(enumName);
+ for (k=0; k < enumList.length; k += 1){
+ if(patternTest.test(enumList[k]) == true){
+ enumAttributes = enumList[k].trim();
+ }
+ }
if(enumAttributes){
- enumAttributes = enumAttributes.replace("[", "");
- enumAttributes = enumAttributes.replace("]", "");
- enumAttributes = enumAttributes.replace(/ /g, '');
- var dropListAfterCommaSplit = enumAttributes.split(splitEqual);
- listemunerateValues = dropListAfterCommaSplit[1].split(splitComma);
- //enumKeyList.push(attribute);
- return listemunerateValues;
+ enumAttributes = enumAttributes.replace("[", "");
+ enumAttributes = enumAttributes.replace("]", "");
+ enumAttributes = enumAttributes.replace(/ /g, '');
+ var dropListAfterCommaSplit = enumAttributes.split(splitEqual);
+ listemunerateValues = dropListAfterCommaSplit[1].split(splitComma);
+ // enumKeyList.push(attribute);
+ return listemunerateValues;
}
return [];
- }
-
- function getBooleanList(){
- var booleanList = [];
- booleanList.push(true);
- booleanList.push(false);
- return booleanList;
- }
-
-
- function isArray(arrayTest) {
- return Object.prototype.toString.call(arrayTest) === '[object Array]';
- }
- var lableList = [];
-
- $scope.layOutElementList = [];
- $scope.layOutOnlyLableList = [];
-
- var elementOrderNum = 0;
-
- function deconstructJSON(layOutData, level , name) {
+ }
+
+ function getBooleanList(){
+ var booleanList = [];
+ booleanList.push(true);
+ booleanList.push(false);
+ return booleanList;
+ }
+
- var array = false;
- var label = level;
- var stringValue = "java.lang.String";
- var string = "string";
- var intValue = "int";
- var integerValue = "integer";
- var double = "double";
- var boolean = "boolean";
- var baseLevel = level;
- var list = "list";
- var String = "String";
-
- var attributekey = "";
-
- if (name.length > 1){
- label = label + name + '.';
- }
-
- for (key in layOutData) {
- array = isArray(layOutData[key]);
- console.log("key: " + key , "value: " + layOutData[key]);
-
- if (!!layOutData[key] && typeof(layOutData[key])=="object") {
-
- if (array==false && key!=="0"){
-
- if($scope.dataOrderInfo){
- var labelObject = {"label" : key, "level" : label, "array" : array};
- //save it to the list
- $scope.layOutOnlyLableList.push(labelObject);
-
- }else {
- //call label layout
- $scope.labelLayout(label, key, array );
- }
-
- }
-
- if (array == true && key!=0){
- lableList.push(key);
- }
-
- if (lableList.length > 0){
- array = true;
- }
- if ( key==="0"){
- var newKey = lableList.pop();
-
- if($scope.dataOrderInfo){
-
- var labelObject = {"label" : newKey, "level" : baseLevel, "array" : array};
- //save it to the list
- $scope.layOutOnlyLableList.push(labelObject);
-
- }else {
- //call label layout
- $scope.labelLayout(baseLevel, newKey, array );
- }
-
- if (array){
- label = baseLevel + newKey + '@0.';
- } else {
- label = baseLevel + newKey + '.';
- }
- }
- deconstructJSON(layOutData[key] , label, key);
- } else {
- var attirbuteLabel = label;
- var defaultValue='';
- var description='';
- var isRequired = false;
- if (layOutData[key].includes('defaultValue-')){
- defaultValue = layOutData[key].split('defaultValue-')[1];
- }
-
- if (layOutData[key].includes('description-')){
- description = layOutData[key].split('description-')[1];
- }
-
+ function isArray(arrayTest) {
+ return Object.prototype.toString.call(arrayTest) === '[object Array]';
+ }
+ var lableList = [];
+
+ $scope.layOutElementList = [];
+ $scope.layOutOnlyLableList = [];
+
+ var elementOrderNum = 0;
+
+ function deconstructJSON(layOutData, level , name) {
- if (key==="0"){
- array = true;
- attributekey = lableList.pop();
- attirbuteLabel = baseLevel;
- } else {
- attributekey = key.split();
- }
-
- if (layOutData[key].includes('required-true')){
- isRequired = true;
- }
-
- var subAttributes = $scope.dcaeModelData.sub_attributes;
-
- if(subAttributes){
- var jsonObject = JSON.parse(subAttributes);
-
- var lablInfo = findVal(jsonObject, attributekey);
- console.log("deconstructJSON:findValue : " + attributekey +": "+ lablInfo);
- if (lablInfo){
- if(lablInfo.includes('required-true')){
- isRequired = true;
- }
- if(lablInfo.includes('defaultValue-')){
- defaultValue = lablInfo.split('defaultValue-')[1];
- }
-
- if(lablInfo.includes('description-')){
- description = lablInfo.split('description-')[1];
- }
-
- }else{
- var allkeys = Object.keys(jsonObject);
- if(allkeys){
- for (var k = 0; k < allkeys.length; k++) {
- var keyValue = allkeys[k];
- console.log(" keyValue:jsonObject["+keyValue+ "]: " + jsonObject[keyValue]);
- if(jsonObject[keyValue]){
- var tempObject = jsonObject[keyValue];
- if(tempObject && tempObject[key]){
- if (tempObject[key].includes('required-true')){
- isRequired = true;
- }
-
- if(tempObject[key].includes('defaultValue-')){
- defaultValue = tempObject[key].split('defaultValue-')[1];
- }
-
- if(tempObject[key].includes('description-')){
- description = tempObject[key].split('description-')[1];
- }
+ var array = false;
+ var label = level;
+ var stringValue = "java.lang.String";
+ var string = "string";
+ var intValue = "int";
+ var integerValue = "integer";
+ var double = "double";
+ var boolean = "boolean";
+ var baseLevel = level;
+
+ var attributekey = "";
+
+ if (name.length > 1){
+ label = label + name + '.';
+ }
+
+ for (key in layOutData) {
+ array = isArray(layOutData[key]);
+
+ if (!!layOutData[key] && typeof(layOutData[key])=="object") {
+
+ if (array==false && key!=="0"){
+
+ if($scope.dataOrderInfo){
+ var labelObject = {"label" : key, "level" : label, "array" : array};
+ // save it to the list
+ $scope.layOutOnlyLableList.push(labelObject);
+
+ }else {
+ // call label layout
+ $scope.labelLayout(label, key, array );
+ }
+
+ }
+
+ if (array == true && key!=0){
+ lableList.push(key);
+ }
+
+ if (lableList.length > 0){
+ array = true;
+ }
+ if ( key==="0"){
+ var newKey = lableList.pop();
+
+ if($scope.dataOrderInfo){
+
+ var labelObject = {"label" : newKey, "level" : baseLevel, "array" : array};
+ // save it to the list
+ $scope.layOutOnlyLableList.push(labelObject);
+
+ }else {
+ // call label layout
+ $scope.labelLayout(baseLevel, newKey, array );
+ }
+
+ if (array){
+ label = baseLevel + newKey + '@0.';
+ } else {
+ label = baseLevel + newKey + '.';
+ }
+ }
+ deconstructJSON(layOutData[key] , label, key);
+ } else {
+ var attirbuteLabel = label;
+ var defaultValue='';
+ var description='';
+ var isRequired = false;
+ if (layOutData[key].includes('defaultValue-')){
+ defaultValue = layOutData[key].split('defaultValue-')[1];
+ }
+
+ if (layOutData[key].includes('description-')){
+ description = layOutData[key].split('description-')[1];
+ }
+
- }
- }
- }
- }
- }
- }
-
- var elementObject = {};
- switch (layOutData[key].split(splitcolon)[0]){
-
- case stringValue:
- case string:
- if($scope.dataOrderInfo){
- elementOrderNum++;
- elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue, "isRequired": isRequired, "type":"text", "description":description};
- $scope.layOutElementList.push(elementObject);
- }else{
- $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
- }
- break;
- case intValue:
- case integerValue:
- if($scope.dataOrderInfo){
- elementOrderNum++;
- elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"number" , "description":description};
- $scope.layOutElementList.push(elementObject);
- }else{
- $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "number");
- }
- break;
- case double:
- if($scope.dataOrderInfo){
- elementOrderNum++;
- elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"double", "description":description};
- $scope.layOutElementList.push(elementObject);
- }else{
- $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "double");
- }
- break;
- case boolean:
- if($scope.dataOrderInfo){
- elementOrderNum++;
- elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue, "isRequired": isRequired, "type":"boolean", "description":description};
- $scope.layOutElementList.push(elementObject);
- }else{
- $scope.dropBoxLayout(attirbuteLabel, attributekey, array, layOutData[key], getBooleanList());
- }
- break;
- default:
- if (layOutData[key].includes('dictionary-')){
- var list = getDictionary(layOutData[key].split('dictionary-')[1]);
- }else{
- //--- get dropdown values from enumValues
- var list = getList(layOutData[key]);
- }
- if (list.length===0){ //not dropdown element
- if($scope.dataOrderInfo){
- elementOrderNum++;
- elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"text", "description":description};
- $scope.layOutElementList.push(elementObject);
-
- }else{
- $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
- }
- }else{
- if($scope.dataOrderInfo){
- elementOrderNum++;
- elementObject = {"id": elementOrderNum, "attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "list":list, "type":"dropBox", "description":description};
- $scope.layOutElementList.push(elementObject);
- }else{
- $scope.dropBoxLayout(attirbuteLabel, attributekey, array, layOutData[key], list, isRequired);
- }
- }
- break;
- }
- }
- }
- }
-
-
- $scope.validContionalRequired = function(parentId) {
- console.log("ng-blur event: parentId : " + parentId);
- var c = document.getElementById(parentId).children;
- var i;
- var hasValue = false;
- for (i = 0; i < c.length; i++) {
- if(c[i].getAttribute("data-conditional")){
- console.log(c[i].getAttribute("data-conditional"));
- console.log(c[i].value);
- if(c[i].value != null && c[i].value.trim() != ""){
- hasValue = true;
- }
- }
- }
+ if (key==="0"){
+ array = true;
+ attributekey = lableList.pop();
+ attirbuteLabel = baseLevel;
+ } else {
+ attributekey = key.split();
+ }
+
+ if (layOutData[key].includes('required-true')){
+ isRequired = true;
+ }
+
+ var subAttributes = $scope.dcaeModelData.subAttributes;
+
+ if(subAttributes){
+ var jsonObject = JSON.parse(subAttributes);
+
+ var lablInfo = findVal(jsonObject, attributekey);
+ if (lablInfo){
+ if(lablInfo.includes('required-true')){
+ isRequired = true;
+ }
+ if(lablInfo.includes('defaultValue-')){
+ defaultValue = lablInfo.split('defaultValue-')[1];
+ }
+
+ if(lablInfo.includes('description-')){
+ description = lablInfo.split('description-')[1];
+ }
+
+ }else{
+ var allkeys = Object.keys(jsonObject);
+ if(allkeys){
+ for (var k = 0; k < allkeys.length; k++) {
+ var keyValue = allkeys[k];
+ if(jsonObject[keyValue]){
+ var tempObject = jsonObject[keyValue];
+ if(tempObject && tempObject[key]){
+ if (tempObject[key].includes('required-true')){
+ isRequired = true;
+ }
+
+ if(tempObject[key].includes('defaultValue-')){
+ defaultValue = tempObject[key].split('defaultValue-')[1];
+ }
+
+ if(tempObject[key].includes('description-')){
+ description = tempObject[key].split('description-')[1];
+ }
- for (i = 0; i < c.length; i++) {
- if(c[i].getAttribute("data-conditional")){
- if(hasValue){
- c[i].setAttribute("required", true);
- }else{
- c[i].removeAttribute("required");
- }
- }
- }
- }
-
- $scope.jsonLayout = function(layOutData){
-
- deconstructJSON(layOutData , "", "");
-
- var orderValue = $scope.dataOrderInfo;
- var layOutElementList = $scope.layOutElementList;
- var labelList = $scope.layOutOnlyLableList;
-
- //reset to default
- elementOrderNum = 0;
- $scope.layOutElementList = [];
- $scope.layOutOnlyLableList = [];
-
- // Only layout in order if order info provided
- if(orderValue){
-
- if(orderValue.includes("[")){
- orderValue = orderValue.replace("[", "") ;
- orderValue = orderValue.replace("]", "") ;
- }
-
- orderValue = orderValue.split(',') ;
-
- for (var i = 0; i < orderValue.length; i++) {
- console.log("orderValue["+i+"]"+ orderValue[i]);
- var key = orderValue[i].trim();
-
- //--- Create labels first {"label" : newKey, "level" : baseLevel, "array" : array};
- if(labelList){
- for (var k = 0; k < labelList.length; k++){
-
- var label = labelList[k].label.toString().trim();
- var level = labelList[k].level.toString().trim();
- var array = labelList[k].array;
-
- if(key == label){
- $scope.labelLayout(level, label, array);
- //in case to have duplicate label names
- labelList[k].label = "*processed*";
- break;
- }
- }
- }
- //--- then layout each element based on its order defined in YAML file
- for (var j = 0; j < layOutElementList.length; j++) {
-
- var attributekey = layOutElementList[j].attributekey.toString().trim();
-
- if(key == attributekey){
+ }
+ }
+ }
+ }
+ }
+ }
+
+ var elementObject = {};
+ switch (layOutData[key].split(splitcolon)[0]){
+
+ case stringValue:
+ case string:
+ if($scope.dataOrderInfo){
+ elementOrderNum++;
+ elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue, "isRequired": isRequired, "type":"text", "description":description};
+ $scope.layOutElementList.push(elementObject);
+ }else{
+ $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
+ }
+ break;
+ case intValue:
+ case integerValue:
+ if($scope.dataOrderInfo){
+ elementOrderNum++;
+ elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"number" , "description":description};
+ $scope.layOutElementList.push(elementObject);
+ }else{
+ $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "number");
+ }
+ break;
+ case double:
+ if($scope.dataOrderInfo){
+ elementOrderNum++;
+ elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"double", "description":description};
+ $scope.layOutElementList.push(elementObject);
+ }else{
+ $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "double");
+ }
+ break;
+ case boolean:
+ if($scope.dataOrderInfo){
+ elementOrderNum++;
+ elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue, "isRequired": isRequired, "type":"boolean", "description":description};
+ $scope.layOutElementList.push(elementObject);
+ }else{
+ $scope.dropBoxLayout(attirbuteLabel, attributekey, array, layOutData[key], getBooleanList());
+ }
+ break;
+ default:
+ if (layOutData[key].includes('dictionary-')){
+ var list = getDictionary(layOutData[key].split('dictionary-')[1]);
+ }else{
+ // --- get dropdown values from enumValues
+ var list = getList(layOutData[key]);
+ }
+ if (list.length===0){ // not dropdown element
+ if($scope.dataOrderInfo){
+ elementOrderNum++;
+ elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"text", "description":description};
+ $scope.layOutElementList.push(elementObject);
+
+ }else{
+ $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
+ }
+ }else{
+ if($scope.dataOrderInfo){
+ elementOrderNum++;
+ elementObject = {"id": elementOrderNum, "attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "list":list, "type":"dropBox", "description":description};
+ $scope.layOutElementList.push(elementObject);
+ }else{
+ $scope.dropBoxLayout(attirbuteLabel, attributekey, array, layOutData[key], list, isRequired);
+ }
+ }
+ break;
+ }
+ }
+ }
+ }
+
+
+ $scope.validContionalRequired = function(parentId) {
+ var c = document.getElementById(parentId).children;
+ var i;
+ var hasValue = false;
+ for (i = 0; i < c.length; i++) {
+ if(c[i].getAttribute("data-conditional")){
+ if(c[i].value != null && c[i].value.trim() != ""){
+ hasValue = true;
+ }
+ }
+ }
- var attirbuteLabel = layOutElementList[j].attirbuteLabel.toString().trim();
- var defaultValue = layOutElementList[j].defaultValue.toString().trim();
- var description = layOutElementList[j].description;
- var isRequired = layOutElementList[j].isRequired;
-
- console.log("layOutElementList[" +j+ "]: id:" + layOutElementList[j].id + ", attributekey:"+ layOutElementList[j].attributekey + ", attirbuteLabel:" + layOutElementList[j].attirbuteLabel);
- console.log("layOutElementList[" +j+ "]: type:" + layOutElementList[j].type);
- if (layOutElementList[j].type == "dropBox"){
- $scope.dropBoxLayout(attirbuteLabel, attributekey, layOutElementList[j].array, defaultValue, layOutElementList[j].list, isRequired, description);
-
- }else{
- $scope.attributeBox(attributekey, layOutElementList[j].array, attirbuteLabel, defaultValue, isRequired, layOutElementList[j].type, description);
-
- }
-
- //in case to have duplicate attribute names
- layOutElementList[j].attributekey = "*processed*";
- break;
- }
- }
- }
- }
- }
-
-
- $scope.attributeBox = function(attibuteKey, attributeManyKey, labelValue, defaultValue, isRequired, dataType, description){
- $scope.temp.policy.ruleGridData.push(attibuteKey);
- var br = document.createElement("BR");
-
- var label = document.createElement("Label");
- var labeltext = null;
- var requiredLabName = "";
- if (matching.includes(attibuteKey)){
- labeltext = document.createTextNode(attibuteKey + "*!");
- isRequired = true; //set required as true for matching element
- }else {
- if(isRequired){
- requiredLabName = attibuteKey + " * ";
- labeltext = document.createTextNode(requiredLabName);
- }else{
- labeltext = document.createTextNode(attibuteKey);
- }
- }
+ for (i = 0; i < c.length; i++) {
+ if(c[i].getAttribute("data-conditional")){
+ if(hasValue){
+ c[i].setAttribute("required", true);
+ }else{
+ c[i].removeAttribute("required");
+ }
+ }
+ }
+ }
+
+ $scope.jsonLayout = function(layOutData){
+
+ deconstructJSON(layOutData , "", "");
+
+ var orderValue = $scope.dataOrderInfo;
+ var layOutElementList = $scope.layOutElementList;
+ var labelList = $scope.layOutOnlyLableList;
+
+ // reset to default
+ elementOrderNum = 0;
+ $scope.layOutElementList = [];
+ $scope.layOutOnlyLableList = [];
+
+ // Only layout in order if order info provided
+ if(orderValue){
+
+ if(orderValue.includes("[")){
+ orderValue = orderValue.replace("[", "") ;
+ orderValue = orderValue.replace("]", "") ;
+ }
+
+ orderValue = orderValue.split(',') ;
+
+ for (var i = 0; i < orderValue.length; i++) {
+ var key = orderValue[i].trim();
+
+ // --- Create labels first {"label" : newKey, "level" : baseLevel, "array" : array};
+ if(labelList){
+ for (var k = 0; k < labelList.length; k++){
+
+ var label = labelList[k].label.toString().trim();
+ var level = labelList[k].level.toString().trim();
+ var array = labelList[k].array;
+
+ if(key == label){
+ $scope.labelLayout(level, label, array);
+ // in case to have duplicate label names
+ labelList[k].label = "*processed*";
+ break;
+ }
+ }
+ }
+ // --- then layout each element based on its order defined in YAML file
+ for (var j = 0; j < layOutElementList.length; j++) {
+
+ var attributekey = layOutElementList[j].attributekey.toString().trim();
+
+ if(key == attributekey){
-
- var divID = labelValue;
-
- if (labelValue.length < 1){
- divID = "DynamicTemplate";
- }else if (labelValue.endsWith('.')){
- var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
- }
-
- label.appendChild(labeltext);
-
- var textField = document.createElement("INPUT");
-
- textField.setAttribute("class" , "form-control");
- if(dataType){
- if(dataType == "double"){
- textField.setAttribute("type" , "number");
- textField.setAttribute("step" , "any");
+ var attirbuteLabel = layOutElementList[j].attirbuteLabel.toString().trim();
+ var defaultValue = layOutElementList[j].defaultValue.toString().trim();
+ var description = layOutElementList[j].description;
+ var isRequired = layOutElementList[j].isRequired;
+
+ if (layOutElementList[j].type == "dropBox"){
+ $scope.dropBoxLayout(attirbuteLabel, attributekey, layOutElementList[j].array, defaultValue, layOutElementList[j].list, isRequired, description);
+
+ }else{
+ $scope.attributeBox(attributekey, layOutElementList[j].array, attirbuteLabel, defaultValue, isRequired, layOutElementList[j].type, description);
+
+ }
+
+ // in case to have duplicate attribute names
+ layOutElementList[j].attributekey = "*processed*";
+ break;
+ }
+ }
+ }
+ }
+ }
+
+
+ $scope.attributeBox = function(attibuteKey, attributeManyKey, labelValue, defaultValue, isRequired, dataType, description){
+ $scope.temp.policy.ruleGridData.push(attibuteKey);
+ var br = document.createElement("BR");
+
+ var label = document.createElement("Label");
+ var labeltext = null;
+ var requiredLabName = "";
+ if (matching.includes(attibuteKey)){
+ labeltext = document.createTextNode(attibuteKey + "*!");
+ isRequired = true; // set required as true for matching element
+ }else {
+ if(isRequired){
+ requiredLabName = attibuteKey + " * ";
+ labeltext = document.createTextNode(requiredLabName);
+ }else{
+ labeltext = document.createTextNode(attibuteKey);
+ }
+ }
- }else if(dataType == "boolean"){ //gw1218 testing boolean
- var booleanDiv = document.createElement("div");
+
+ var divID = labelValue;
+
+ if (labelValue.length < 1){
+ divID = "DynamicTemplate";
+ }else if (labelValue.endsWith('.')){
+ var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
+ }
+
+ label.appendChild(labeltext);
+
+ var textField = document.createElement("INPUT");
+
+ textField.setAttribute("class" , "form-control");
+ if(dataType){
+ if(dataType == "double"){
+ textField.setAttribute("type" , "number");
+ textField.setAttribute("step" , "any");
- booleanDiv.setAttribute("class" , "onoffswitch");
+ }else if(dataType == "boolean"){ // gw1218 testing boolean
+ var booleanDiv = document.createElement("div");
- //var checkField = document.createElement("INPUT");
- textField.setAttribute("type" , "checkbox");
- textField.setAttribute("name" , "onoffswitch");
- textField.setAttribute("class" , "onoffswitch-checkbox");
- textField.setAttribute("id" , ''+labelValue +attibuteKey+'');
- if(defaultValue.substring(0,defaultValue.indexOf(":")) == "true") {
- textField.setAttribute("checked" , true);
- }else{
- textField.removeAttribute("checked");
- }
+ booleanDiv.setAttribute("class" , "onoffswitch");
- var booleanlabel = document.createElement("Label");
- booleanlabel.setAttribute("class" , "onoffswitch-label");
- booleanlabel.setAttribute("for" , ''+labelValue +attibuteKey+'');
-
- var span1 = document.createElement("span");
- span1.setAttribute("class" , "onoffswitch-inner");
-
- var span2 = document.createElement("span");
- span2.setAttribute("class" , "onoffswitch-switch");
-
-
- booleanlabel.appendChild(span1);
- booleanlabel.appendChild(span2);
- booleanDiv.appendChild(textField);
- booleanDiv.appendChild(booleanlabel);
-
- document.getElementById(divID).appendChild(label);
- document.getElementById(divID).appendChild(booleanDiv);
+ // var checkField = document.createElement("INPUT");
+ textField.setAttribute("type" , "checkbox");
+ textField.setAttribute("name" , "onoffswitch");
+ textField.setAttribute("class" , "onoffswitch-checkbox");
+ textField.setAttribute("id" , ''+labelValue +attibuteKey+'');
+ if(defaultValue.substring(0,defaultValue.indexOf(":")) == "true") {
+ textField.setAttribute("checked" , true);
+ }else{
+ textField.removeAttribute("checked");
+ }
+ textField.setAttribute("ng-click" , "validateOnAndOff('"+labelValue +attibuteKey+"', $event)");
+ var booleanlabel = document.createElement("Label");
+ booleanlabel.setAttribute("class" , "onoffswitch-label");
+ booleanlabel.setAttribute("for" , ''+labelValue +attibuteKey+'');
+
+ var span1 = document.createElement("span");
+ span1.setAttribute("class" , "onoffswitch-inner");
+
+ var span2 = document.createElement("span");
+ span2.setAttribute("class" , "onoffswitch-switch");
+
+
+ booleanlabel.appendChild(span1);
+ booleanlabel.appendChild(span2);
+ booleanDiv.appendChild(textField);
+ booleanDiv.appendChild(booleanlabel);
+
+ document.getElementById(divID).appendChild(label);
+ document.getElementById(divID).appendChild(booleanDiv);
- //return;
- } else{
- textField.setAttribute("type" , dataType);
- }
-
-
+ // return;
+ } else{
+ textField.setAttribute("type" , dataType);
+ }
+
+
- }
-
- if(dataType != "boolean"){
- textField.setAttribute("style" , "width:300px;");
- textField.setAttribute("ng-disabled" , "temp.policy.readOnly");
- if(description && description != "null"){
- textField.setAttribute("title", description);
- }
- }
+ }
+
+ if(dataType != "boolean"){
+ textField.setAttribute("style" , "width:300px;");
+ textField.setAttribute("ng-disabled" , "temp.policy.readOnly");
+ if(description && description != "null"){
+ textField.setAttribute("title", description);
+ }
+ }
- var checkKey;
- var id = "";
- if(attributeManyKey){
- checkKey = labelValue + attibuteKey+'@0';
- textField.setAttribute("id" , ''+labelValue + attibuteKey+'@0'+'');
- var divTag = document.createElement("div");
- divTag.setAttribute("id", "div."+ labelValue +attibuteKey);
- var addButton = document.createElement("BUTTON");
- var buttonaddLabel = document.createTextNode("+");
- addButton.appendChild(buttonaddLabel);
- addButton.setAttribute("id", labelValue + attibuteKey);
- addButton.setAttribute("class", "btn btn-add-remove");
- addButton.setAttribute("onclick" , 'addNewChoice("'+labelValue + attibuteKey+'");');
- addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
- var removeButton = document.createElement("BUTTON");
- var buttonremoveLabel = document.createTextNode("-");
- removeButton.appendChild(buttonremoveLabel);
- removeButton.setAttribute("class", "btn btn-add-remove");
- removeButton.setAttribute("onclick" , 'removeChoice("'+labelValue + attibuteKey+'");');
- removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
- document.getElementById(divID).appendChild(addButton);
- document.getElementById(divID).appendChild(removeButton);
- document.getElementById(divID).appendChild(label);
- id = "div."+labelValue+attibuteKey;
- //var divTag = document.createElement("div");
- divTag.setAttribute("id", id);
- document.getElementById(divID).appendChild(divTag);
- textField.className += ' first_child';
- if(isRequired){
- textField.setAttribute("required", "true");
- }
-
- divTag.appendChild(textField);
- document.getElementById(divID).appendChild(divTag);
-
- }else if (dataType != "boolean"){
- checkKey = labelValue + attibuteKey;
- textField.setAttribute("id" , ''+labelValue +attibuteKey+'');
- if(document.getElementById(divID).hasAttribute('required') || !document.getElementById(divID).hasAttribute('data-conditional')){
- if(requiredLabName.includes("*") || isRequired){
- textField.setAttribute("required", "true");
- }
- }else if (document.getElementById(divID).hasAttribute('data-conditional')){
- if(requiredLabName.includes("*")){
- var requiredNode = document.createElement('span');
- requiredNode.setAttribute("class", "mstooltip");
- requiredNode.textContent = "?";
- label.appendChild(requiredNode);
-
- var requiredNodeToolTip = document.createElement('span');
- requiredNodeToolTip.setAttribute("class", "tooltiptext");
- requiredNodeToolTip.textContent = "Conditional Required";
- requiredNode.appendChild(requiredNodeToolTip);
-
- textField.setAttribute("data-conditional", divID);
- textField.setAttribute("ng-blur", "validContionalRequired('"+divID+"')");
- }
- }
+ var checkKey;
+ var id = "";
+ if(attributeManyKey){
+ checkKey = labelValue + attibuteKey+'@0';
+ textField.setAttribute("id" , ''+labelValue + attibuteKey+'@0'+'');
+ var divTag = document.createElement("div");
+ divTag.setAttribute("id", "div."+ labelValue +attibuteKey);
+ var addButton = document.createElement("BUTTON");
+ var buttonaddLabel = document.createTextNode("+");
+ addButton.appendChild(buttonaddLabel);
+ addButton.setAttribute("id", labelValue + attibuteKey);
+ addButton.setAttribute("class", "btn btn-add-remove");
+ addButton.setAttribute("onclick" , 'addNewChoice("'+labelValue + attibuteKey+'");');
+ addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
+ var removeButton = document.createElement("BUTTON");
+ var buttonremoveLabel = document.createTextNode("-");
+ removeButton.appendChild(buttonremoveLabel);
+ removeButton.setAttribute("class", "btn btn-add-remove");
+ removeButton.setAttribute("onclick" , 'removeChoice("'+labelValue + attibuteKey+'");');
+ removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
+ document.getElementById(divID).appendChild(addButton);
+ document.getElementById(divID).appendChild(removeButton);
+ document.getElementById(divID).appendChild(label);
+ id = "div."+labelValue+attibuteKey;
+ // var divTag = document.createElement("div");
+ divTag.setAttribute("id", id);
+ document.getElementById(divID).appendChild(divTag);
+ textField.className += ' first_child';
+ if(isRequired){
+ textField.setAttribute("required", "true");
+ }
+
+ divTag.appendChild(textField);
+ document.getElementById(divID).appendChild(divTag);
+
+ }else if (dataType != "boolean"){
+ checkKey = labelValue + attibuteKey;
+ textField.setAttribute("id" , ''+labelValue +attibuteKey+'');
+ if(document.getElementById(divID).hasAttribute('required') || !document.getElementById(divID).hasAttribute('data-conditional')){
+ if(requiredLabName.includes("*") || isRequired){
+ textField.setAttribute("required", "true");
+ }
+ }else if (document.getElementById(divID).hasAttribute('data-conditional')){
+ if(requiredLabName.includes("*")){
+ var requiredNode = document.createElement('span');
+ requiredNode.setAttribute("class", "mstooltip");
+ requiredNode.textContent = "?";
+ label.appendChild(requiredNode);
+
+ var requiredNodeToolTip = document.createElement('span');
+ requiredNodeToolTip.setAttribute("class", "tooltiptext");
+ requiredNodeToolTip.textContent = "Conditional Required";
+ requiredNode.appendChild(requiredNodeToolTip);
+
+ textField.setAttribute("data-conditional", divID);
+ textField.setAttribute("ng-blur", "validContionalRequired('"+divID+"')");
+ }
+ }
- document.getElementById(divID).appendChild(label);
- document.getElementById(divID).appendChild(textField);
- document.getElementById(divID).appendChild(br);
+ document.getElementById(divID).appendChild(label);
+ document.getElementById(divID).appendChild(textField);
+ document.getElementById(divID).appendChild(br);
- }
+ }
- if(dataType != "boolean" && divID.includes("@0") && divID.includes("div.")){
- var firstChild_Id = divID.split("@0")[0];
- var firstChild_element = document.getElementById(firstChild_Id);
- if(firstChild_element){
-
- if(!firstChild_element.className.includes('children_group border')){
- layer++;
- if(layer > 4){
- layer = 1
- };
- firstChild_element.className += ' children_group border' + layer; //here is div with a group of children.
- }
- }
- }
- console.log('firstChild_Id: ' + firstChild_Id);
- console.log('divID: ' + divID);
-
- if(dataType != "boolean" && defaultValue.length > 0){
- if(defaultValue.includes(":")){
- defaultValue = defaultValue.split(":")[0];
- if(defaultValue === "NA") {
- defaultValue = "";
- }
- }
- if(defaultValue != "undefined" && defaultValue != undefined && defaultValue != "null"){
- document.getElementById(checkKey).value = defaultValue;
- }
- }
-
- if($scope.temp.policy.ruleData != null){
- //document.getElementById(checkKey).value = $scope.temp.policy.ruleData[checkKey];
- if (attributeManyKey){
- var newCheckKey = checkKey.replace(attibuteKey + '@0',attibuteKey);
- if($scope.temp.policy.ruleData[newCheckKey +'@0'] != undefined && $scope.temp.policy.ruleData[newCheckKey +'@0'] != "undefined"){
- document.getElementById(newCheckKey +'@0').value = $scope.temp.policy.ruleData[newCheckKey +'@0'];
- }
- }else{
- if($scope.temp.policy.ruleData[checkKey] != undefined && $scope.temp.policy.ruleData[checkKey] != "undefined"){
- document.getElementById(checkKey).value = $scope.temp.policy.ruleData[checkKey];
- }
- }
- }
-
- if (dataType != "boolean"){
- plainAttributeKeys.push(labelValue + attibuteKey+'*'+attributeManyKey);
- }else{
- plainAttributeKeys.push(labelValue + attibuteKey+'*'+"boolean");
- }
+ if(dataType != "boolean" && divID.includes("@0") && divID.includes("div.")){
+ var firstChild_Id = divID.split("@0")[0];
+ var firstChild_element = document.getElementById(firstChild_Id);
+ if(firstChild_element){
+
+ if(!firstChild_element.className.includes('children_group border')){
+ layer++;
+ if(layer > 4){
+ layer = 1
+ }
+ firstChild_element.className += ' children_group border' + layer; // here is div with a group of children.
+ }
+ }
+ }
+
+ if(dataType != "boolean" && defaultValue.length > 0){
+ if(defaultValue.includes(":")){
+ defaultValue = defaultValue.split(":")[0];
+ if(defaultValue === "NA") {
+ defaultValue = "";
+ }
+ }
+ if(defaultValue != "undefined" && defaultValue != undefined && defaultValue != "null"){
+ document.getElementById(checkKey).value = defaultValue;
+ }
+ }
+
+ if($scope.temp.policy.ruleData != null){
+ // document.getElementById(checkKey).value =
+ // $scope.temp.policy.ruleData[checkKey];
+ if (attributeManyKey){
+ var newCheckKey = checkKey.replace(attibuteKey + '@0',attibuteKey);
+ if($scope.temp.policy.ruleData[newCheckKey +'@0'] != undefined && $scope.temp.policy.ruleData[newCheckKey +'@0'] != "undefined"){
+ document.getElementById(newCheckKey +'@0').value = $scope.temp.policy.ruleData[newCheckKey +'@0'];
+ }
+ }else{
+ if($scope.temp.policy.ruleData[checkKey] != undefined && $scope.temp.policy.ruleData[checkKey] != "undefined"){
+ document.getElementById(checkKey).value = $scope.temp.policy.ruleData[checkKey];
+ }
+ }
+ }
+
+ if (dataType != "boolean"){
+ plainAttributeKeys.push(labelValue + attibuteKey+'*'+attributeManyKey);
+ }else{
+ plainAttributeKeys.push(labelValue + attibuteKey+'*'+"boolean");
+ }
+ };
+
+ $scope.validateOnAndOff = function(id , value) {
+ console.log(id, value);
+ if (value.target.checked) {
+ document.getElementById(id).setAttribute("checked", true);
+ } else {
+ document.getElementById(id).removeAttribute("checked");
+ }
};
-
+
$scope.labelManyKeys = [];
$scope.labelLayout = function(labelValue, lableName, labelManyKey ){
- var label = document.createElement("Label")
- var divID = labelValue;
- if (labelValue.endsWith('.')){
- var workingLabel = labelValue.substring(0, labelValue.length-1);
- }else {
- var workingLabel = labelValue;
- }
-
- if (labelValue.length < 1){
- divID = "DynamicTemplate";
- } else if (labelValue.endsWith('.')){
- var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
- }
-
- var subAttributes = $scope.dcaeModelData.sub_attributes;
- var jsonObject = JSON.parse(subAttributes);
- var lablInfo = findVal(jsonObject, lableName);
- console.log("findValue : " + lableName +": "+ lablInfo);
- var star = "";
- var required = null;
- if(lablInfo){
- if(typeof lablInfo === 'string' ){
- if(lablInfo.includes("required-true")){
- star = " *";
- required = true;
- }else if (lablInfo.includes("required-false")){
- required = false
- }
- }
- }
-
- var labeltext = document.createTextNode(lableName + star);
-
- label.appendChild(labeltext);
+ var label = document.createElement("Label")
+ var divID = labelValue;
+ if (labelValue.endsWith('.')){
+ var workingLabel = labelValue.substring(0, labelValue.length-1);
+ }else {
+ var workingLabel = labelValue;
+ }
+ if (labelValue.length < 1){
+ divID = "DynamicTemplate";
+ } else if (labelValue.endsWith('.')){
+ var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
+ }
+
+ var subAttributes = $scope.dcaeModelData.subAttributes;
+ var jsonObject = JSON.parse(subAttributes);
+ var lablInfo = findVal(jsonObject, lableName);
+ var star = "";
+ var required = null;
+ if(lablInfo){
+ if(typeof lablInfo === 'string' ){
+ if(lablInfo.includes("required-true")){
+ star = " *";
+ required = true;
+ }else if (lablInfo.includes("required-false")){
+ required = false
+ }
+ }
+ }
+
+ var labeltext = document.createTextNode(lableName + star);
+
+ label.appendChild(labeltext);
- if(labelManyKey){
- var addButton = document.createElement("BUTTON");
- var buttonLabel = document.createTextNode("+");
- addButton.appendChild(buttonLabel);
- addButton.setAttribute("class", "btn btn-add-remove");
- addButton.setAttribute("onclick" , 'addNewChoice("'+labelValue + lableName+'");');
- addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
- var removeButton = document.createElement("BUTTON");
- var buttonremoveLabel = document.createTextNode("-");
- removeButton.appendChild(buttonremoveLabel);
- removeButton.setAttribute("class", "btn btn-add-remove");
- removeButton.setAttribute("onclick" , 'removeChoice("'+labelValue +lableName+'");');
- removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
- document.getElementById(divID).appendChild(addButton);
- document.getElementById(divID).appendChild(removeButton);
- document.getElementById(divID).appendChild(label);
- var id = "div."+labelValue+lableName;
- var divTag = document.createElement("div");
- divTag.setAttribute("id", id);
- document.getElementById(divID).appendChild(divTag);
-
- var divTag = document.createElement("div");
- divTag.setAttribute("id", id +'@0');
-
- if(!divTag.className.includes('children_group border')){
- layer++;
- if(layer > 4){
- layer = 1
- };
- divTag.className += ' children_group border' + layer; //here is div with a group of children.
- }
- if(required){
- divTag.setAttribute("required", required);
- }else if(required == false){
- divTag.setAttribute("data-conditional", "yes");
- }
-
- document.getElementById(id).appendChild(divTag);
-
- $scope.labelManyKeys.push(lableName);
-
- }else{
- var divTag = document.createElement("div");
- divTag.setAttribute("id", "div."+labelValue+lableName);
-
- if(!divTag.className.includes('children_group border')){
- layer++;
- if(layer > 4){
- layer = 1
- };
- divTag.className += ' children_group border' + layer; //here is div with a group of children.
- }
- if(required){
- divTag.setAttribute("required", required);
- }else if(required == false){
- divTag.setAttribute("data-conditional", "yes");
- }
- document.getElementById(divID).appendChild(label);
- document.getElementById(divID).appendChild(divTag);
- }
+ if(labelManyKey){
+ var addButton = document.createElement("BUTTON");
+ var buttonLabel = document.createTextNode("+");
+ addButton.appendChild(buttonLabel);
+ addButton.setAttribute("class", "btn btn-add-remove");
+ addButton.setAttribute("onclick" , 'addNewChoice("'+labelValue + lableName+'");');
+ addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
+ var removeButton = document.createElement("BUTTON");
+ var buttonremoveLabel = document.createTextNode("-");
+ removeButton.appendChild(buttonremoveLabel);
+ removeButton.setAttribute("class", "btn btn-add-remove");
+ removeButton.setAttribute("onclick" , 'removeChoice("'+labelValue +lableName+'");');
+ removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
+ document.getElementById(divID).appendChild(addButton);
+ document.getElementById(divID).appendChild(removeButton);
+ document.getElementById(divID).appendChild(label);
+ var id = "div."+labelValue+lableName;
+ var divTag = document.createElement("div");
+ divTag.setAttribute("id", id);
+ document.getElementById(divID).appendChild(divTag);
+
+ var divTag = document.createElement("div");
+ divTag.setAttribute("id", id +'@0');
+
+ if(!divTag.className.includes('children_group border')){
+ layer++;
+ if(layer > 4){
+ layer = 1
+ }
+ divTag.className += ' children_group border' + layer; // here is div with a group of children.
+ }
+ if(required){
+ divTag.setAttribute("required", required);
+ }else if(required == false){
+ divTag.setAttribute("data-conditional", "yes");
+ }
+
+ document.getElementById(id).appendChild(divTag);
+
+ $scope.labelManyKeys.push(lableName);
+
+ }else{
+ var divTag = document.createElement("div");
+ divTag.setAttribute("id", "div."+labelValue+lableName);
+
+ if(!divTag.className.includes('children_group border')){
+ layer++;
+ if(layer > 4){
+ layer = 1
+ }
+ divTag.className += ' children_group border' + layer; // here is div with a group of children.
+ }
+ if(required){
+ divTag.setAttribute("required", required);
+ }else if(required == false){
+ divTag.setAttribute("data-conditional", "yes");
+ }
+ document.getElementById(divID).appendChild(label);
+ document.getElementById(divID).appendChild(divTag);
+ }
};
$scope.dropBoxLayout = function(labelLevel, attributeName, many , defaultValue, listemunerateValues, isRequired, description){
- var br = document.createElement("BR");
-
- if (labelLevel.length < 1){
- var divID = "DynamicTemplate";
- } else if (labelLevel.endsWith('.')){
- var divID = 'div.'+ labelLevel.substring(0, labelLevel.length-1);
- }
-
-
- var label = document.createElement("Label")
-
- var refAttributes = $scope.dcaeModelData.ref_attributes;
- if(isRequired != true && refAttributes){ //check refAttributes also
- var refAttributesList = refAttributes.split(splitComma);
- for (k = 0; k < refAttributesList.length; k++){
- var refAttribute = refAttributesList[k].split(splitEqual);
- if (attributeName == refAttribute[0].trim() && refAttribute[1].includes("required-true")){
- isRequired = true;
- }
- }
- }
-
- if (matching.includes(attributeName)){
- var labeltext = document.createTextNode(attributeName + "*!");
- label.appendChild(labeltext);
- isRequired = true; //set required as true for matching element
- }else {
- var labeltext = document.createTextNode(attributeName);
- if(isRequired){
- var requiredLabName = attributeName+ " * ";
- labeltext = document.createTextNode(requiredLabName);
- }else{
- labeltext = document.createTextNode(attributeName);
- }
-
- label.appendChild(labeltext);
- }
- label.appendChild(labeltext);
- // if this field is required, but its parent is not required
- if(isRequired && document.getElementById(divID).hasAttribute('data-conditional')){
- var requiredNode = document.createElement('span');
- requiredNode.setAttribute("class", "mstooltip");
- requiredNode.textContent = "?";
- label.appendChild(requiredNode);
-
- var requiredNodeToolTip = document.createElement('span');
- requiredNodeToolTip.setAttribute("class", "tooltiptext");
- requiredNodeToolTip.textContent = "Conditional Required";
- requiredNode.appendChild(requiredNodeToolTip);
-
- }
-
- var listField = document.createElement("SELECT");
- listField.setAttribute("class" , "form-control");
- listField.setAttribute("style" , "width:300px;");
- listField.setAttribute("ng-disabled" , "temp.policy.readOnly");
+ var br = document.createElement("BR");
+
+ if (labelLevel.length < 1){
+ var divID = "DynamicTemplate";
+ } else if (labelLevel.endsWith('.')){
+ var divID = 'div.'+ labelLevel.substring(0, labelLevel.length-1);
+ }
+
+
+ var label = document.createElement("Label")
+
+ var refAttributes = $scope.dcaeModelData.refAttributes;
+ if(isRequired != true && refAttributes){ // check refAttributes also
+ var refAttributesList = refAttributes.split(splitComma);
+ for (k = 0; k < refAttributesList.length; k++){
+ var refAttribute = refAttributesList[k].split(splitEqual);
+ if (attributeName == refAttribute[0].trim() && refAttribute[1].includes("required-true")){
+ isRequired = true;
+ }
+ }
+ }
+
+ if (matching.includes(attributeName)){
+ var labeltext = document.createTextNode(attributeName + "*!");
+ label.appendChild(labeltext);
+ isRequired = true; // set required as true for matching element
+ }else {
+ var labeltext = document.createTextNode(attributeName);
+ if(isRequired){
+ var requiredLabName = attributeName+ " * ";
+ labeltext = document.createTextNode(requiredLabName);
+ }else{
+ labeltext = document.createTextNode(attributeName);
+ }
+
+ label.appendChild(labeltext);
+ }
+ label.appendChild(labeltext);
+ // if this field is required, but its parent is not required
+ if(isRequired && document.getElementById(divID).hasAttribute('data-conditional')){
+ var requiredNode = document.createElement('span');
+ requiredNode.setAttribute("class", "mstooltip");
+ requiredNode.textContent = "?";
+ label.appendChild(requiredNode);
+
+ var requiredNodeToolTip = document.createElement('span');
+ requiredNodeToolTip.setAttribute("class", "tooltiptext");
+ requiredNodeToolTip.textContent = "Conditional Required";
+ requiredNode.appendChild(requiredNodeToolTip);
- if(description && description != "null"){
- listField.setAttribute("title", description);
- }
+ }
- if(isRequired){
- if(document.getElementById(divID).hasAttribute('data-conditional')){
- listField.setAttribute("data-conditional", divID);
- listField.setAttribute("ng-blur", "validContionalRequired('"+divID+"')");
- }else{
- listField.setAttribute("required", true);
- }
- }
- if( many != true || isRequired != true){ // add an empty option for not required or not multiple select element
- var optionFirst = document.createElement('option');
- var optionValue = "";
- if($scope.temp.policy.ruleData != null){
- if($scope.temp.policy.ruleData[labelLevel + attributeName] != undefined && $scope.temp.policy.ruleData[labelLevel + attributeName] != "undefined"){
- optionValue = $scope.temp.policy.ruleData[labelLevel + attributeName];
- }
- }
- optionFirst.setAttribute('value', optionValue);
- optionFirst.appendChild(document.createTextNode(optionValue));
- listField.appendChild(optionFirst);
- }
- var ruleFormationCheck = false;
- if(listemunerateValues.length !== 0 && typeof listemunerateValues[0] == "string" && listemunerateValues[0].includes("dictionary:")) {
- var ruleCheck = listemunerateValues[0].split("&");
- var dictParams = ruleCheck[0].split(":");
- var dictParamsSplit = dictParams[1].split("@");
- if (ruleCheck[1] != undefined && ruleCheck[1] == 'Rule') {
- ruleFormationCheck = true;
- }
- PolicyAppService.getData(dictParamsSplit[0]).then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.listDictionarys = JSON.parse($scope.data[dictParamsSplit[1]]);
- for (i=0; i < $scope.listDictionarys.length; i += 1) {
- option = document.createElement('option');
- option.setAttribute('value', $scope.listDictionarys[i]);
- option.appendChild(document.createTextNode($scope.listDictionarys[i]));
- listField.appendChild(option);
- }
- }, function (error) {
- console.log("failed");
- });
+ var listField = document.createElement("SELECT");
+ listField.setAttribute("class" , "form-control");
+ listField.setAttribute("style" , "width:300px;");
+ listField.setAttribute("ng-disabled" , "temp.policy.readOnly");
- }
- else{
- for (i=0; i < listemunerateValues.length; i += 1) {
- if(typeof listemunerateValues[i] == "string" && listemunerateValues[i].includes("equal-sign")){
- listemunerateValues[i] = listemunerateValues[i].replace('equal-sign','=');
- }
-
- option = document.createElement('option');
- option.setAttribute('value', listemunerateValues[i]);
- option.appendChild(document.createTextNode(listemunerateValues[i]));
- option.setAttribute('value', listemunerateValues[i]);
- listField.appendChild(option);
- }
- }
- listField.setAttribute("id" , ''+ labelLevel + attributeName + '');
+ if(description && description != "null"){
+ listField.setAttribute("title", description);
+ }
- enumKeyList.push(attributeName);
+ if(isRequired){
+ if(document.getElementById(divID).hasAttribute('data-conditional')){
+ listField.setAttribute("data-conditional", divID);
+ listField.setAttribute("ng-blur", "validContionalRequired('"+divID+"')");
+ }else{
+ listField.setAttribute("required", true);
+ }
+ }
+ if( many != true || isRequired != true){ // add an empty option for not required or not multiple select element
+ var optionFirst = document.createElement('option');
+ var optionValue = "";
+ if($scope.temp.policy.ruleData != null){
+ if($scope.temp.policy.ruleData[labelLevel + attributeName] != undefined && $scope.temp.policy.ruleData[labelLevel + attributeName] != "undefined"){
+ optionValue = $scope.temp.policy.ruleData[labelLevel + attributeName];
+ }
+ }
+ optionFirst.setAttribute('value', optionValue);
+ optionFirst.appendChild(document.createTextNode(optionValue));
+ listField.appendChild(optionFirst);
+ }
+ var ruleFormationCheck = false;
+ if(listemunerateValues.length !== 0 && typeof listemunerateValues[0] == "string" && listemunerateValues[0].includes("dictionary:")) {
+ var ruleCheck = listemunerateValues[0].split("&");
+ var dictParams = ruleCheck[0].split(":");
+ var dictParamsSplit = dictParams[1].split("@");
+ if (ruleCheck[1] != undefined && ruleCheck[1] == 'Rule') {
+ ruleFormationCheck = true;
+ }
+ PolicyAppService.getData(dictParamsSplit[0]).then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.listDictionarys = JSON.parse($scope.data[dictParamsSplit[1]]);
+ for (i=0; i < $scope.listDictionarys.length; i += 1) {
+ option = document.createElement('option');
+ option.setAttribute('value', $scope.listDictionarys[i]);
+ option.appendChild(document.createTextNode($scope.listDictionarys[i]));
+ listField.appendChild(option);
+ }
+ });
- document.getElementById(divID).appendChild(label);
- document.getElementById(divID).appendChild(br);
+ }
+ else{
+ for (i=0; i < listemunerateValues.length; i += 1) {
+ if(typeof listemunerateValues[i] == "string" && listemunerateValues[i].includes("equal-sign")){
+ listemunerateValues[i] = listemunerateValues[i].replace('equal-sign','=');
+ }
+
+ option = document.createElement('option');
+ option.setAttribute('value', listemunerateValues[i]);
+ option.appendChild(document.createTextNode(listemunerateValues[i]));
+ option.setAttribute('value', listemunerateValues[i]);
+ listField.appendChild(option);
+ }
+ }
+ listField.setAttribute("id" , ''+ labelLevel + attributeName + '');
- if(many == true){
- document.getElementById(divID).appendChild(listField).multiple = true;
- plainAttributeKeys.push(labelLevel + attributeName+'*'+true);
- }else {
- document.getElementById(divID).appendChild(listField).multiple = false;
- plainAttributeKeys.push(labelLevel + attributeName+'*'+false);
+ enumKeyList.push(attributeName);
- if (defaultValue){
- if(defaultValue.includes(':')){
- defaultValue = defaultValue.split(':')[0];
- }
- var location = listemunerateValues.indexOf(defaultValue);
- document.getElementById(labelLevel +attributeName).options[location+1].selected = true;
- }
- }
+ document.getElementById(divID).appendChild(label);
+ document.getElementById(divID).appendChild(br);
- if (ruleFormationCheck) {
- var optionInput = document.createElement("INPUT");
- optionInput.setAttribute("type" , "text");
- optionInput.setAttribute("id" , ''+ labelLevel + attributeName + '.input');
- optionInput.setAttribute("name" , "ruleName");
- optionInput.setAttribute("value" , " ");
- optionInput.setAttribute("style" , "width:300px;");
- optionInput.setAttribute("ng-disabled" , "temp.policy.readOnly");
- optionInput.removeAttribute("required");
+ if(many == true){
+ document.getElementById(divID).appendChild(listField).multiple = true;
+ plainAttributeKeys.push(labelLevel + attributeName+'*'+true);
+ }else {
+ document.getElementById(divID).appendChild(listField).multiple = false;
+ plainAttributeKeys.push(labelLevel + attributeName+'*'+false);
- document.getElementById(divID).appendChild(optionInput);
+ if (defaultValue){
+ if(defaultValue.includes(':')){
+ defaultValue = defaultValue.split(':')[0];
+ }
+ var location = listemunerateValues.indexOf(defaultValue);
+ document.getElementById(labelLevel +attributeName).options[location+1].selected = true;
+ }
+ }
- var optionButton = document.createElement("BUTTON");
- optionButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
- var buttonLabel = document.createTextNode("+");
- optionButton.appendChild(buttonLabel);
- optionButton.setAttribute("class", "btn btn-add-remove");
- optionButton.setAttribute("onclick" , 'addDynamicOptions("'+ labelLevel + attributeName + '");');
- optionButton.removeAttribute("required");
+ if (ruleFormationCheck) {
+ var optionInput = document.createElement("INPUT");
+ optionInput.setAttribute("type" , "text");
+ optionInput.setAttribute("id" , ''+ labelLevel + attributeName + '.input');
+ optionInput.setAttribute("name" , "ruleName");
+ optionInput.setAttribute("value" , " ");
+ optionInput.setAttribute("style" , "width:300px;");
+ optionInput.setAttribute("ng-disabled" , "temp.policy.readOnly");
+ optionInput.removeAttribute("required");
+ document.getElementById(divID).appendChild(optionInput);
- document.getElementById(divID).appendChild(optionButton);
- document.getElementById(divID).appendChild(br);
- }
+ var optionButton = document.createElement("BUTTON");
+ optionButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
+ var buttonLabel = document.createTextNode("+");
+ optionButton.appendChild(buttonLabel);
+ optionButton.setAttribute("class", "btn btn-add-remove");
+ optionButton.setAttribute("onclick" , 'addDynamicOptions("'+ labelLevel + attributeName + '");');
+ optionButton.removeAttribute("required");
- if($scope.temp.policy.ruleData != null){
- if (many == true){
- document.getElementById(labelLevel +attributeName).options[0].selected = false;
- for (i=0; i < listemunerateValues.length; i += 1) {
- var testValue = $scope.temp.policy.ruleData[labelLevel +attributeName+'@' + i];
- if (testValue === undefined){
- testValue = $scope.temp.policy.ruleData[labelLevel +attributeName];
- }
- var location = listemunerateValues.indexOf(testValue);
- if (location!=-1){
- document.getElementById(labelLevel +attributeName).options[location].selected = true;
- }
- }
- }else {
- if($scope.temp.policy.ruleData[labelLevel + attributeName] != undefined && $scope.temp.policy.ruleData[labelLevel + attributeName] != "undefined"){
- document.getElementById(labelLevel + attributeName).value = $scope.temp.policy.ruleData[labelLevel + attributeName];
- }
- }
- }
- };
- addDynamicOptions = function(id) {
- var option = document.createElement("option");
- var value = document.getElementById(id+".input").value;
- option.setAttribute('value', value);
- option.appendChild(document.createTextNode(value));
- document.getElementById(id).options.add(option);
- document.getElementById(id+".input").value = "";
- };
+ document.getElementById(divID).appendChild(optionButton);
+ document.getElementById(divID).appendChild(br);
+ }
- function onlyUnique(value, index, self) {
- return self.indexOf(value) === index;
- };
+ if($scope.temp.policy.ruleData != null){
+ if (many == true){
+ document.getElementById(labelLevel +attributeName).options[0].selected = false;
+ for (i=0; i < listemunerateValues.length; i += 1) {
+ var testValue = $scope.temp.policy.ruleData[labelLevel +attributeName+'@' + i];
+ if (testValue === undefined){
+ testValue = $scope.temp.policy.ruleData[labelLevel +attributeName];
+ }
+ var location = listemunerateValues.indexOf(testValue);
+ if (location!=-1){
+ document.getElementById(labelLevel +attributeName).options[location].selected = true;
+ }
+ }
+ }else {
+ if($scope.temp.policy.ruleData[labelLevel + attributeName] != undefined && $scope.temp.policy.ruleData[labelLevel + attributeName] != "undefined"){
+ document.getElementById(labelLevel + attributeName).value = $scope.temp.policy.ruleData[labelLevel + attributeName];
+ }
+ }
+ }
+ };
+ addDynamicOptions = function(id) {
+ var option = document.createElement("option");
+ var value = document.getElementById(id+".input").value;
+ option.setAttribute('value', value);
+ option.appendChild(document.createTextNode(value));
+ document.getElementById(id).options.add(option);
+ document.getElementById(id+".input").value = "";
+ };
- function checkDictionary(value){
- for (i = 0; i < $scope.microServiceAttributeDictionaryDatas.length; i++) {
- if ($scope.microServiceAttributeDictionaryDatas[i].name.localeCompare(value)){
- return true;
- }
- }
+ function onlyUnique(value, index, self) {
+ return self.indexOf(value) === index;
+ }
- }
- $scope.savePolicy = function(policy){
- if(policy.itemContent != undefined){
- $scope.refreshCheck = true;
- $scope.policyNavigator = policy.itemContent;
- policy.itemContent = "";
- }
- $scope.savebutton = false;
- var splitAt = '*';
- var dot ='.';
- var jsonPolicy = {};
- if(plainAttributeKeys != null){
- for(a = 0; a < plainAttributeKeys.length; a++){
- var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
- console.log("splitPlainAttributeKey: " + splitPlainAttributeKey);
- var searchElement = document.getElementById(splitPlainAttributeKey[0]);
- var key = splitPlainAttributeKey[0];
- if(searchElement == null){
- searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
- key = splitPlainAttributeKey[0]+'@0';
- }else if (searchElement.nodeName == 'BUTTON'){
- searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
- key = splitPlainAttributeKey[0]+'@0';
- }
- if(searchElement != null){
- var keySplit = key.split(dot);
- var elumentLocation = keySplit.length;
- var enumKey = key;
- if (elumentLocation > 1){
- enumKey = keySplit[keySplit.length - 1];
- }
- //check it is undefined or not
- if (enumKeyList != undefined && enumKeyList.indexOf(enumKey) != -1){
- if (splitPlainAttributeKey[1]!= undefined && splitPlainAttributeKey[1].indexOf("true") !== -1){
- var multiSlect = [];
- for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
- multiSlect.push(searchElement.selectedOptions[i].value);
- }
- jsonPolicy[key]= multiSlect;
- }else{
- console.log(" searchElement.value = > " + searchElement.value);
- if(splitPlainAttributeKey[1]!= undefined && splitPlainAttributeKey[1] == "boolean"){
- jsonPolicy[key]= false;
- for(var i=0; i<booleanTrueElements.length; i++){
- if(booleanTrueElements[i] == key){
- jsonPolicy[key]= true;
- }
- }
+ $scope.savePolicy = function(policy){
+ if(policy.itemContent != undefined){
+ $scope.refreshCheck = true;
+ $scope.policyNavigator = policy.itemContent;
+ policy.itemContent = "";
+ }
+ $scope.savebutton = false;
+ var splitAt = '*';
+ var dot ='.';
+ var jsonPolicy = {};
+ if(plainAttributeKeys != null){
+ for(a = 0; a < plainAttributeKeys.length; a++){
+ var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
+ var searchElement = document.getElementById(splitPlainAttributeKey[0]);
+ var key = splitPlainAttributeKey[0];
+ if(searchElement == null){
+ searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
+ key = splitPlainAttributeKey[0]+'@0';
+ }else if (searchElement.nodeName == 'BUTTON'){
+ searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
+ key = splitPlainAttributeKey[0]+'@0';
+ }
+ if(searchElement != null){
+ var keySplit = key.split(dot);
+ var elumentLocation = keySplit.length;
+ var enumKey = key;
+ if (elumentLocation > 1){
+ enumKey = keySplit[keySplit.length - 1];
+ }
+ // check it is undefined or not
+ if (enumKeyList != undefined && enumKeyList.indexOf(enumKey) != -1){
+ if (splitPlainAttributeKey[1]!= undefined && splitPlainAttributeKey[1].indexOf("true") !== -1){
+ var multiSlect = [];
+ for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
+ multiSlect.push(searchElement.selectedOptions[i].value);
+ }
+ jsonPolicy[key]= multiSlect;
+ }else{
+ if(splitPlainAttributeKey[1]!= undefined && splitPlainAttributeKey[1] == "boolean"){
+ jsonPolicy[key]= false;
+ for(var i=0; i<booleanTrueElements.length; i++){
+ if(booleanTrueElements[i] == key){
+ jsonPolicy[key]= true;
+ }
+ }
- }else{
- jsonPolicy[key]= searchElement.value;
- }
- }
- } else {
- if(searchElement.value != null){
- jsonPolicy[key]= searchElement.value;
- console.log(" searchElement.value = > " + searchElement.value);
- if(splitPlainAttributeKey[1] == "boolean"){
- jsonPolicy[key]= false;
- for(var i=0; i<booleanTrueElements.length; i++){
- if(booleanTrueElements[i] == key){
- jsonPolicy[key]= true;
- }
- }
- }
- }
- }
- }
- }
- }
+ }else{
+ jsonPolicy[key]= searchElement.value;
+ }
+ }
+ } else {
+ if(searchElement.value != null){
+ if(searchElement.parentElement.children[0].checked == true){
+ jsonPolicy[key]= searchElement.checked;
+ }
+ else{
+ jsonPolicy[key]= window.btoa(searchElement.value);
+ }
+ }
+ }
+ }
+ }
+ }
var uuu = "policycreation/save_policy";
var postData={policyData: policy, policyJSON : jsonPolicy};
$.ajax({
@@ -1597,199 +1526,192 @@ angular.module('abs').controller('dcaeMicroServiceController', ['$scope', '$wind
data: JSON.stringify(postData),
success : function(data){
$scope.$apply(function(){
- $scope.data=data.policyData;
- if($scope.data == 'success'){
- $scope.temp.policy.readOnly = 'true';
- $scope.safetyChecker = data.policyData.split("#")[2];
- if ($scope.safetyChecker!=undefined) {
- Notification.success($scope.safetyChecker);
- }
- $scope.pushStatus=data.policyData.split("&")[1];
- if($scope.pushStatus=="successPush"){
- Notification.success("Policy pushed successfully");
- }
- Notification.success("Policy Saved Successfully.");
- }else if ($scope.data == 'PolicyExists'){
- $scope.savebutton = true;
- Notification.error("Policy Already Exists with Same Name in Scope.");
- }
+ $scope.data=data.policyData;
+ if($scope.data == 'success'){
+ $scope.temp.policy.readOnly = 'true';
+ $scope.safetyChecker = data.policyData.split("#")[2];
+ if ($scope.safetyChecker!=undefined) {
+ Notification.success($scope.safetyChecker);
+ }
+ $scope.pushStatus=data.policyData.split("&")[1];
+ if($scope.pushStatus=="successPush"){
+ Notification.success("Policy pushed successfully");
+ }
+ $scope.temp.policy.readOnly = 'true';
+ $scope.savebutton = true;
+ Notification.success("Policy Saved Successfully.");
+ }else if ($scope.data == 'PolicyExists'){
+ $scope.savebutton = true;
+ Notification.error("Policy Already Exists with Same Name in Scope.");
+ }
});
- console.log($scope.data);
},
error : function(data){
- Notification.error("Error Occured while saving Policy.");
+ Notification.error("Error Occured while saving Policy.");
}
});
};
var booleanTrueElements = [];
$scope.validatePolicy = function(policy){
- document.getElementById("validate").innerHTML = "";
- var splitAt = '*';
- var dot ='.';
- var jsonPolicy = {};
- if(plainAttributeKeys != null){
- for(a = 0; a < plainAttributeKeys.length; a++){
- var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
- console.log(splitPlainAttributeKey[1]);
- var searchElement = document.getElementById(splitPlainAttributeKey[0]);
- var key = splitPlainAttributeKey[0];
- if(searchElement == null){
- searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
- key = splitPlainAttributeKey[0]+'@0';
- }else if (searchElement.nodeName == 'BUTTON'){
- searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
- key = splitPlainAttributeKey[0]+'@0';
- }
- if(searchElement != null){
- if (enumKeyList.indexOf(key) != -1){
- if (splitPlainAttributeKey[1].indexOf("true") !== -1){
- var multiSlect = [];
- for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
- multiSlect.push(searchElement.selectedOptions[i].value);
- }
- jsonPolicy[key]= multiSlect;
- }else{
- jsonPolicy[key]= searchElement.value;
- }
- if(searchElement.getAttribute("required")){
- if(!searchElement.value){
- return;
- }
- }
- } else {
- if(searchElement.value != null){
- jsonPolicy[key]= searchElement.value;
- if(searchElement.getAttribute("required")){
- if(!searchElement.value){
- return;
- }
- }
- }
- }
- }
- }
-
-
- var checkedValue = $('.onoffswitch-checkbox:checked').val();
-
- var x = document.getElementsByClassName("onoffswitch-checkbox");
-
-
- if(checkedValue){
- console.log("checkedValue:" + checkedValue);
- for(var i=0; i<x.length; x++){
- console.log("checkbox id: " + x[i].id);
- booleanTrueElements.push(x[i].id)
- }
- }
- }
+ document.getElementById("validate").innerHTML = "";
+ var splitAt = '*';
+ var jsonPolicy = {};
+ if(plainAttributeKeys != null){
+ for(a = 0; a < plainAttributeKeys.length; a++){
+ var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
+ var searchElement = document.getElementById(splitPlainAttributeKey[0]);
+ var key = splitPlainAttributeKey[0];
+ if(searchElement == null){
+ searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
+ key = splitPlainAttributeKey[0]+'@0';
+ }else if (searchElement.nodeName == 'BUTTON'){
+ searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
+ key = splitPlainAttributeKey[0]+'@0';
+ }
+ if(searchElement != null){
+ if (enumKeyList.indexOf(key) != -1){
+ if (splitPlainAttributeKey[1].indexOf("true") !== -1){
+ var multiSlect = [];
+ for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
+ multiSlect.push(searchElement.selectedOptions[i].value);
+ }
+ jsonPolicy[key]= multiSlect;
+ }else{
+ jsonPolicy[key]= searchElement.value;
+ }
+ if(searchElement.getAttribute("required")){
+ if(!searchElement.value){
+ return;
+ }
+ }
+ } else {
+ if(searchElement.value != null){
+ if(searchElement.parentElement.children[0].checked == true){
+ jsonPolicy[key]= searchElement.checked;
+ }
+ else{
+ jsonPolicy[key]= searchElement.value;
+ }
+ if(searchElement.getAttribute("required")){
+ if(!searchElement.value){
+ return;
+ }
+ }
+ }
+ }
+ }
+ }
+
+
+ var checkedValue = $('.onoffswitch-checkbox:checked').val();
+
+ var x = document.getElementsByClassName("onoffswitch-checkbox");
+
+
+ if(checkedValue){
+ for(var i=0; i<x.length; x++){
+ booleanTrueElements.push(x[i].id)
+ }
+ }
+ }
var uuu = "policyController/validate_policy.htm";
- console.log("$scope.isCheck:" + $scope.isCheck);
if($scope.isCheck == true){
- if(("configName" in policy) == false){
- Notification.error("Validation Failed: configName is required");
- $scope.savebutton = true;
- return;
- }
- if(("location" in policy) == false){
- Notification.error("Validation Failed: location is required");
- $scope.savebutton = true;
- return;
- }
- if(("uuid" in policy) == false){
- Notification.error("Validation Failed: uuid is required");
- $scope.savebutton = true;
- return;
- }
- if(("policyScope" in policy) == false){
- Notification.error("Validation Failed: policyScope is required");
- $scope.savebutton = true;
- return;
- }
+ if(("configName" in policy) == false){
+ Notification.error("Validation Failed: configName is required");
+ $scope.savebutton = true;
+ return;
+ }
+ if(("location" in policy) == false){
+ Notification.error("Validation Failed: location is required");
+ $scope.savebutton = true;
+ return;
+ }
+ if(("uuid" in policy) == false){
+ Notification.error("Validation Failed: uuid is required");
+ $scope.savebutton = true;
+ return;
+ }
+ if(("policyScope" in policy) == false){
+ Notification.error("Validation Failed: policyScope is required");
+ $scope.savebutton = true;
+ return;
+ }
}
var postData={policyData: policy, policyJSON : jsonPolicy};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.validateData = data.data.replace(/\"/g, "");
- $scope.data=data.data.substring(1,8);
- var size = data.data.length;
- if($scope.data == 'success'){
- Notification.success("Validation Success.");
- $scope.savebutton = false;
- if (size > 18){
- var displayWarning = data.data.substring(19,size - 1);
- document.getElementById("validate").innerHTML = "Safe Policy Warning Message : "+displayWarning;
- document.getElementById("validate").style.color = "white";
- document.getElementById("validate").style.backgroundColor = "skyblue";
- }
- }else{
- Notification.error("Validation Failed.");
- document.getElementById("validate").innerHTML = $scope.validateData;
- document.getElementById("validate").style.color = "white";
- document.getElementById("validate").style.backgroundColor = "red";
- $scope.savebutton = true;
- }
-
- });
- console.log($scope.data);
- },
- error : function(data){
- Notification.error("Validation Failed.");
- $scope.savebutton = true;
- }
- });
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.validateData = data.data.replace(/\"/g, "");
+ $scope.data=data.data.substring(1,8);
+ var size = data.data.length;
+ if($scope.data == 'success'){
+ Notification.success("Validation Success.");
+ $scope.savebutton = false;
+ if (size > 18){
+ var displayWarning = data.data.substring(19,size - 1);
+ document.getElementById("validate").innerHTML = "Safe Policy Warning Message : "+displayWarning;
+ document.getElementById("validate").style.color = "white";
+ document.getElementById("validate").style.backgroundColor = "skyblue";
+ }
+ }else{
+ Notification.error("Validation Failed.");
+ document.getElementById("validate").innerHTML = $scope.validateData;
+ document.getElementById("validate").style.color = "white";
+ document.getElementById("validate").style.backgroundColor = "red";
+ $scope.savebutton = true;
+ }
+
+ });
+ },
+ error : function(data){
+ Notification.error("Validation Failed.");
+ $scope.savebutton = true;
+ }
+ });
};
- function extend(obj, src) {
- for (var key in src) {
- if (src.hasOwnProperty(key)) obj[key] = src[key];
+ // Switch Click
+ $('.Switch').click(function() {
+ // Check If Enabled (Has 'On' Class)
+ if ($(this).hasClass('On')){
+ // Try To Find Checkbox Within Parent Div, And Check It
+ $(this).parent().find('input:checkbox').attr('checked', true);
+ // Change Button Style - Remove On Class, Add Off Class
+ $(this).removeClass('On').addClass('Off');
+ } else { // If Button Is Disabled (Has 'Off' Class)
+ // Try To Find Checkbox Within Parent Div, And Uncheck It
+ $(this).parent().find('input:checkbox').attr('checked', false);
+ // Change Button Style - Remove Off Class, Add On Class
+ $(this).removeClass('Off').addClass('On');
+ }
+ });
+ // Loops Through Each Toggle Switch On Page
+ $('.Switch').each(function() {
+ // Search of a checkbox within the parent
+ if ($(this).parent().find('input:checkbox').length){
+
+ // If checkbox doesnt have the show class then hide it
+ if (!$(this).parent().find('input:checkbox').hasClass("show")){
+ $(this).parent().find('input:checkbox').hide(); }
+
+ // Look at the checkbox's checkked state
+ if ($(this).parent().find('input:checkbox').is(':checked')){
+ // Checkbox is not checked, Remove the On Class and Add the Off Class
+ $(this).removeClass('On').addClass('Off');
+ } else {
+ // Checkbox Is Checked Remove Off Class, and Add the On Class
+ $(this).removeClass('Off').addClass('On');
}
- return obj;
}
-
- // Switch Click
- $('.Switch').click(function() {
- // Check If Enabled (Has 'On' Class)
- if ($(this).hasClass('On')){
- // Try To Find Checkbox Within Parent Div, And Check It
- $(this).parent().find('input:checkbox').attr('checked', true);
- // Change Button Style - Remove On Class, Add Off Class
- $(this).removeClass('On').addClass('Off');
- } else { // If Button Is Disabled (Has 'Off' Class)
- // Try To Find Checkbox Within Parent Div, And Uncheck It
- $(this).parent().find('input:checkbox').attr('checked', false);
- // Change Button Style - Remove Off Class, Add On Class
- $(this).removeClass('Off').addClass('On');
- }
- });
- // Loops Through Each Toggle Switch On Page
- $('.Switch').each(function() {
- // Search of a checkbox within the parent
- if ($(this).parent().find('input:checkbox').length){
-
- // If checkbox doesnt have the show class then hide it
- if (!$(this).parent().find('input:checkbox').hasClass("show")){
- $(this).parent().find('input:checkbox').hide(); }
-
- // Look at the checkbox's checkked state
- if ($(this).parent().find('input:checkbox').is(':checked')){
- // Checkbox is not checked, Remove the On Class and Add the Off Class
- $(this).removeClass('On').addClass('Off');
- } else {
- // Checkbox Is Checked Remove Off Class, and Add the On Class
- $(this).removeClass('Off').addClass('On');
- }
- }
- });
+ });
}]);
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DecisionPolicyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DecisionPolicyController.js
index 0e53ce9de..4d63dbe3f 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DecisionPolicyController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DecisionPolicyController.js
@@ -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.
@@ -17,447 +17,411 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-angular.module('abs').controller('decisionPolicyController', [ '$scope', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', '$http', function($scope, PolicyAppService, PolicyNavigator, modalService, $modal, Notification, $http) {
- $("#dialog").hide();
-
- $scope.policyNavigator;
- $scope.savebutton = true;
- $scope.refreshCheck = false;
- $scope.disableOnCreate = false;
- $scope.notRawPolicy = true;
-
- if (!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly) {
- $scope.disableOnCreate = true;
- $scope.temp.policy = {
- policyType : "Decision"
- }
- }
- ;
-
- $scope.refresh = function() {
- if ($scope.refreshCheck) {
- $scope.policyNavigator.refresh();
- }
- $scope.modal('createNewPolicy', true);
- $scope.temp.policy = "";
- };
-
- $scope.modal = function(id, hide) {
- return $('#' + id).modal(hide ? 'hide' : 'show');
- };
-
- if ($scope.temp.policy.ruleProvider == undefined) {
- $scope.temp.policy.ruleProvider = "Custom";
- }
-
- if ($scope.temp.policy.blackListEntryType == undefined) {
- $scope.temp.policy.blackListEntryType = "Use Manual Entry";
- }
-
- 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);
- console.log($scope.onapNameDictionaryDatas);
- }, function(error) {
- console.log("failed");
- });
-
- PolicyAppService.getData('getDictionary/get_SettingsDictionaryDataByName').then(function(data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.settingsDictionaryDatas = JSON.parse($scope.data.settingsDictionaryDatas);
- console.log($scope.settingsDictionaryDatas);
- }, function(error) {
- console.log("failed");
- });
-
- PolicyAppService.getData('get_FunctionDefinitionDataByName').then(function(data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.functionDefinitionDatas = JSON.parse($scope.data.functionDefinitionDatas);
- console.log($scope.functionDefinitionDatas);
- }, function(error) {
- console.log("failed");
- });
-
- PolicyAppService.getData('getDictionary/get_AttributeDatabyAttributeName').then(function(data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.attributeDictionaryDatas = JSON.parse($scope.data.attributeDictionaryDatas);
- console.log($scope.attributeDictionaryDatas);
- }, function(error) {
- console.log("failed");
- });
-
- PolicyAppService.getData('getDictionary/get_RainyDayDictionaryDataByName').then(function(data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.rainyDayDictionaryDatas = JSON.parse($scope.data.rainyDayDictionaryDatas);
- console.log($scope.rainyDayDictionaryDatas);
- }, function(error) {
- console.log("failed");
- });
-
- PolicyAppService.getData('getDictionary/get_RainyDayDictionaryData').then(function(data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.rainyDayDictionaryDataEntity = JSON.parse($scope.data.rainyDayDictionaryDatas);
- console.log($scope.rainyDayDictionaryDatasEntity);
- }, function(error) {
- console.log("failed");
- });
-
- function extend(obj, src) {
- for (var key in src) {
- if (src.hasOwnProperty(key))
- obj[key] = src[key];
- }
- return obj;
- }
-
- $scope.saveDecisionPolicy = function(policy) {
- if (policy.itemContent != undefined) {
- $scope.refreshCheck = true;
- $scope.policyNavigator = policy.itemContent;
- policy.itemContent = "";
- }
- $scope.savebutton = false;
- console.log(policy);
- var uuu = "policycreation/save_policy";
- var postData = {
- policyData : policy
- };
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType : 'json',
- contentType : 'application/json',
- data : JSON.stringify(postData),
- success : function(data) {
- $scope.$apply(function() {
- $scope.data = data.policyData;
- if ($scope.data == 'success') {
- $scope.temp.policy.readOnly = 'true';
- Notification.success("Policy Saved Successfully.");
- } else if ($scope.data == 'PolicyExists') {
- $scope.savebutton = true;
- Notification.error("Policy Already Exists with Same Name in Scope.");
- }
- });
- console.log($scope.data);
-
- },
- error : function(data) {
- Notification.error("Error Occured while saving Policy.");
- }
- });
- };
-
- $scope.validatePolicy = function(policy) {
- console.log(policy);
- document.getElementById("validate").innerHTML = "";
- var uuu = "policyController/validate_policy.htm";
- var postData = {
- policyData : policy
- };
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType : 'json',
- contentType : 'application/json',
- data : JSON.stringify(postData),
- success : function(data) {
- $scope.$apply(function() {
- $scope.validateData = data.data.replace(/\"/g, "");
- $scope.data = data.data;
- if ($scope.data == '"success"') {
- Notification.success("Validation Success.");
- $scope.savebutton = false;
- } else {
- Notification.error("Validation Failed.");
- document.getElementById("validate").innerHTML = $scope.validateData;
- document.getElementById("validate").style.color = "white";
- document.getElementById("validate").style.backgroundColor = "red";
- $scope.savebutton = true;
- }
-
- });
- console.log($scope.data);
- },
- error : function(data) {
- Notification.error("Validation Failed.");
- $scope.savebutton = true;
- }
- });
- };
-
- if (!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly) {
- $scope.temp.policy.attributes = [];
- $scope.temp.policy.settings = [];
- $scope.temp.policy.ruleAlgorithmschoices = [];
- if (!$scope.temp.policy.yamlparams) {
- $scope.temp.policy.yamlparams = {};
- }
- if (!$scope.temp.policy.yamlparams.targets) {
- $scope.temp.policy.yamlparams.targets = [];
- }
- if (!$scope.temp.policy.yamlparams.blackList) {
- $scope.temp.policy.yamlparams.blackList = [];
- }
- if (!$scope.temp.policy.rainyday) {
- $scope.temp.policy.rainyday = {};
- }
- if (!$scope.temp.policy.rainyday.treatmentTableChoices) {
- $scope.temp.policy.rainyday.treatmentTableChoices = [];
- }
-
- } else if ($scope.temp.policy.ruleProvider == "Custom") {
- if ($scope.temp.policy.attributes.length == 0) {
- $scope.temp.policy.attributes = [];
- }
- if ($scope.temp.policy.settings.length == 0) {
- $scope.temp.policy.settings = [];
- }
- if ($scope.temp.policy.ruleAlgorithmschoices == null || $scope.temp.policy.ruleAlgorithmschoices.length == 0) {
- $scope.temp.policy.ruleAlgorithmschoices = [];
- }
- } else if ($scope.temp.policy.ruleProvider == "GUARD_BL_YAML") {
- if ($scope.temp.policy.yamlparams.blackList == null || $scope.temp.policy.yamlparams.blackList.length == 0) {
- $scope.temp.policy.yamlparams.blackList = [];
- }
- if ($scope.temp.policy.blackListEntries == null || $scope.temp.policy.blackListEntries.length == 0) {
- $scope.temp.policy.blackListEntries = [];
- }
- $scope.blackListEntries = [];
- $scope.temp.policy.appendBlackListEntries = [];
- $scope.blackListEntries = arrayUnique($scope.temp.policy.blackListEntries.concat($scope.temp.policy.yamlparams.blackList));
-
+angular.module('abs').controller('decisionPolicyController',
+ [ '$scope', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', '$http',
+ function($scope, PolicyAppService, PolicyNavigator, modalService, $modal, Notification, $http) {
+ $("#dialog").hide();
+
+ $scope.policyNavigator;
+ $scope.savebutton = true;
+ $scope.refreshCheck = false;
+ $scope.disableOnCreate = false;
+ $scope.notRawPolicy = true;
+
+ if (!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly) {
+ $scope.disableOnCreate = true;
+ $scope.temp.policy = {
+ policyType : "Decision"
+ }
+ }
+
+ $scope.refresh = function() {
+ if ($scope.refreshCheck) {
+ $scope.policyNavigator.refresh();
+ }
+ $scope.modal('createNewPolicy', true);
+ $scope.temp.policy = "";
+ };
+
+ $scope.modal = function(id, hide) {
+ return $('#' + id).modal(hide ? 'hide' : 'show');
+ };
+
+ if ($scope.temp.policy.ruleProvider == undefined) {
+ $scope.temp.policy.ruleProvider = "Custom";
+ }
+
+ if ($scope.temp.policy.blackListEntryType == undefined) {
+ $scope.temp.policy.blackListEntryType = "Use Manual Entry";
+ }
+
+ PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function(data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
+ });
+
+ PolicyAppService.getData('getDictionary/get_SettingsDictionaryDataByName').then(function(data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.settingsDictionaryDatas = JSON.parse($scope.data.settingsDictionaryDatas);
+ });
+
+ PolicyAppService.getData('get_FunctionDefinitionDataByName').then(function(data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.functionDefinitionDatas = JSON.parse($scope.data.functionDefinitionDatas);
+ });
+
+ PolicyAppService.getData('getDictionary/get_AttributeDatabyAttributeName').then(function(data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.attributeDictionaryDatas = JSON.parse($scope.data.attributeDictionaryDatas);
+ });
+
+ PolicyAppService.getData('getDictionary/get_RainyDayDictionaryDataByName').then(function(data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.rainyDayDictionaryDatas = JSON.parse($scope.data.rainyDayDictionaryDatas);
+ });
+
+ PolicyAppService.getData('getDictionary/get_RainyDayDictionaryData').then(function(data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.rainyDayDictionaryDataEntity = JSON.parse($scope.data.rainyDayDictionaryDatas);
+ });
+
+ $scope.saveDecisionPolicy = function(policy) {
+ if (policy.itemContent != undefined) {
+ $scope.refreshCheck = true;
+ $scope.policyNavigator = policy.itemContent;
+ policy.itemContent = "";
+ }
+ $scope.savebutton = false;
+ var uuu = "policycreation/save_policy";
+ var postData = {
+ policyData : policy
+ };
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType : 'json',
+ contentType : 'application/json',
+ data : JSON.stringify(postData),
+ success : function(data) {
+ $scope.$apply(function() {
+ $scope.data = data.policyData;
+ if ($scope.data == 'success') {
+ $scope.temp.policy.readOnly = 'true';
+ Notification.success("Policy Saved Successfully.");
+ } else if ($scope.data == 'PolicyExists') {
+ $scope.savebutton = true;
+ Notification.error("Policy Already Exists with Same Name in Scope.");
+ }
+ });
+
+ },
+ error : function(data) {
+ Notification.error("Error Occured while saving Policy.");
+ }
+ });
+ };
+
+ $scope.validatePolicy = function(policy) {
+ document.getElementById("validate").innerHTML = "";
+ var uuu = "policyController/validate_policy.htm";
+ var postData = {
+ policyData : policy
+ };
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType : 'json',
+ contentType : 'application/json',
+ data : JSON.stringify(postData),
+ success : function(data) {
+ $scope.$apply(function() {
+ $scope.validateData = data.data.replace(/\"/g, "");
+ $scope.data = data.data;
+ if ($scope.data == '"success"') {
+ Notification.success("Validation Success.");
+ $scope.savebutton = false;
+ } else {
+ Notification.error("Validation Failed.");
+ document.getElementById("validate").innerHTML = $scope.validateData;
+ document.getElementById("validate").style.color = "white";
+ document.getElementById("validate").style.backgroundColor = "red";
+ $scope.savebutton = true;
+ }
+
+ });
+ },
+ error : function(data) {
+ Notification.error("Validation Failed.");
+ $scope.savebutton = true;
+ }
+ });
+ };
+
+ if (!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly) {
+ $scope.temp.policy.attributes = [];
+ $scope.temp.policy.settings = [];
+ $scope.temp.policy.ruleAlgorithmschoices = [];
+ if (!$scope.temp.policy.yamlparams) {
+ $scope.temp.policy.yamlparams = {};
+ }
+ if (!$scope.temp.policy.yamlparams.targets) {
+ $scope.temp.policy.yamlparams.targets = [];
+ }
+ if (!$scope.temp.policy.yamlparams.blackList) {
+ $scope.temp.policy.yamlparams.blackList = [];
+ }
+ if (!$scope.temp.policy.rainyday) {
+ $scope.temp.policy.rainyday = {};
+ }
+ if (!$scope.temp.policy.rainyday.treatmentTableChoices) {
+ $scope.temp.policy.rainyday.treatmentTableChoices = [];
+ }
+
+ } else if ($scope.temp.policy.ruleProvider == "Custom") {
+ if ($scope.temp.policy.attributes.length == 0) {
+ $scope.temp.policy.attributes = [];
+ }
+ if ($scope.temp.policy.settings.length == 0) {
+ $scope.temp.policy.settings = [];
+ }
+ if ($scope.temp.policy.ruleAlgorithmschoices == null || $scope.temp.policy.ruleAlgorithmschoices.length == 0) {
+ $scope.temp.policy.ruleAlgorithmschoices = [];
+ }
+ } else if ($scope.temp.policy.ruleProvider == "GUARD_BL_YAML") {
+ if ($scope.temp.policy.yamlparams.blackList == null || $scope.temp.policy.yamlparams.blackList.length == 0) {
+ $scope.temp.policy.yamlparams.blackList = [];
+ }
+ if ($scope.temp.policy.blackListEntries == null || $scope.temp.policy.blackListEntries.length == 0) {
+ $scope.temp.policy.blackListEntries = [];
+ }
+ $scope.blackListEntries = [];
+ $scope.temp.policy.appendBlackListEntries = [];
+ $scope.blackListEntries = arrayUnique($scope.temp.policy.blackListEntries.concat($scope.temp.policy.yamlparams.blackList));
+
}else if($scope.temp.policy.ruleProvider=="GUARD_YAML" || $scope.temp.policy.ruleProvider=="GUARD_MIN_MAX"){
- if($scope.temp.policy.yamlparams.targets.length==0){
- $scope.temp.policy.yamlparams.targets = [];
- }
- } else if ($scope.temp.policy.ruleProvider == "Rainy_Day") {
- if ($scope.temp.policy.rainyday.treatmentTableChoices == null || $scope.temp.policy.rainyday.treatmentTableChoices.length == 0) {
- $scope.temp.policy.rainyday.treatmentTableChoices = [];
- }
- }
- $scope.attributeDatas = [ {
- "attributes" : $scope.temp.policy.attributes
- } ];
- $scope.addNewChoice = function() {
- var newItemNo = $scope.temp.policy.attributes.length + 1;
- $scope.temp.policy.attributes.push({
- 'id' : 'choice' + newItemNo
- });
- };
- $scope.removeChoice = function() {
- var lastItem = $scope.temp.policy.attributes.length - 1;
- $scope.temp.policy.attributes.splice(lastItem);
- };
-
- $scope.settingsDatas = [ {
- "settings" : $scope.temp.policy.settings
- } ];
- $scope.addNewSettingsChoice = function() {
- var newItemNo = $scope.temp.policy.settings.length + 1;
- $scope.temp.policy.settings.push({
- 'id' : 'choice' + newItemNo
- });
- };
- $scope.removeSettingsChoice = function() {
- var lastItem = $scope.temp.policy.settings.length - 1;
- $scope.temp.policy.settings.splice(lastItem);
- };
-
- $scope.addNewTarget = function() {
- $scope.temp.policy.yamlparams.targets.push('');
- };
- $scope.removeTarget = function() {
- var lastItem = $scope.temp.policy.yamlparams.targets.length - 1;
- $scope.temp.policy.yamlparams.targets.splice(lastItem);
- };
-
- $scope.addNewBL = function() {
- $scope.temp.policy.yamlparams.blackList.push('');
- };
+ if($scope.temp.policy.yamlparams.targets.length==0){
+ $scope.temp.policy.yamlparams.targets = [];
+ }
+ } else if ($scope.temp.policy.ruleProvider == "Rainy_Day") {
+ if ($scope.temp.policy.rainyday.treatmentTableChoices == null || $scope.temp.policy.rainyday.treatmentTableChoices.length == 0) {
+ $scope.temp.policy.rainyday.treatmentTableChoices = [];
+ }
+ }
+ $scope.attributeDatas = [ {
+ "attributes" : $scope.temp.policy.attributes
+ } ];
+ $scope.addNewChoice = function() {
+ var newItemNo = $scope.temp.policy.attributes.length + 1;
+ $scope.temp.policy.attributes.push({
+ 'id' : 'choice' + newItemNo
+ });
+ };
+ $scope.removeChoice = function() {
+ var lastItem = $scope.temp.policy.attributes.length - 1;
+ $scope.temp.policy.attributes.splice(lastItem);
+ };
+
+ $scope.settingsDatas = [ {
+ "settings" : $scope.temp.policy.settings
+ } ];
+ $scope.addNewSettingsChoice = function() {
+ var newItemNo = $scope.temp.policy.settings.length + 1;
+ $scope.temp.policy.settings.push({
+ 'id' : 'choice' + newItemNo
+ });
+ };
+ $scope.removeSettingsChoice = function() {
+ var lastItem = $scope.temp.policy.settings.length - 1;
+ $scope.temp.policy.settings.splice(lastItem);
+ };
+
+ $scope.addNewTarget = function() {
+ $scope.temp.policy.yamlparams.targets.push('');
+ };
+ $scope.removeTarget = function() {
+ var lastItem = $scope.temp.policy.yamlparams.targets.length - 1;
+ $scope.temp.policy.yamlparams.targets.splice(lastItem);
+ };
+
+ $scope.addNewBL = function() {
+ $scope.temp.policy.yamlparams.blackList.push('');
+ };
$scope.removeBL = function(id) {
- $scope.temp.policy.yamlparams.blackList = $scope.temp.policy.yamlparams.blackList.filter(function (obj){
- return obj !== id;
- });
- };
-
- $scope.treatmentDatas = [ {
- "treatmentValues" : $scope.temp.policy.rainyday.treatmentTableChoices
- } ];
-
- $scope.addNewTreatment = function() {
- $scope.temp.policy.rainyday.treatmentTableChoices.push({});
- };
-
- $scope.removeTreatment = function() {
- var lastItem = $scope.temp.policy.rainyday.treatmentTableChoices.length - 1;
- $scope.temp.policy.rainyday.treatmentTableChoices.splice(lastItem);
- };
-
- $scope.workstepDictionaryDatas = [];
- $scope.getWorkstepValues = function(bbidValue) {
- for (var i = 0; i < $scope.rainyDayDictionaryDataEntity.length; ++i) {
- var obj = $scope.rainyDayDictionaryDataEntity[i];
- if (obj.bbid == bbidValue) {
- $scope.workstepDictionaryDatas.push(obj.workstep);
- }
- }
- };
-
- $scope.allowedTreatmentsDatas = [];
- $scope.getTreatmentValues = function(bbidValue, workstepValue) {
- for (var i = 0; i < $scope.rainyDayDictionaryDataEntity.length; ++i) {
- var obj = $scope.rainyDayDictionaryDataEntity[i];
- if (obj.bbid == bbidValue && obj.workstep == workstepValue) {
- var splitAlarm = obj.treatments.split(',');
- for (var j = 0; j < splitAlarm.length; ++j) {
- $scope.allowedTreatmentsDatas.push(splitAlarm[j]);
- }
- }
- }
- };
-
- $scope.ItemNo = 0;
- $scope.ruleAlgorithmDatas = [ {
- "ruleAlgorithms" : $scope.temp.policy.ruleAlgorithmschoices
- } ];
-
- $scope.addNewRuleAlgorithm = function() {
- if ($scope.temp.policy.ruleAlgorithmschoices != null) {
- var newItemNo = $scope.temp.policy.ruleAlgorithmschoices.length + 1;
- } else {
- var newItemNo = 1;
- }
- if (newItemNo > 1) {
- var value = newItemNo - 1;
- $scope.attributeDictionaryDatas.push('A' + value);
- }
- $scope.temp.policy.ruleAlgorithmschoices.push({
- 'id' : 'A' + newItemNo
- });
- };
-
- $scope.removeRuleAlgorithm = function() {
- var lastItem = $scope.temp.policy.ruleAlgorithmschoices.length - 1;
- $scope.temp.policy.ruleAlgorithmschoices.splice(lastItem);
- };
-
- $scope.providerListener = function(ruleProvider) {
- if (ruleProvider != "Custom") {
- $scope.temp.policy.ruleAlgorithmschoices = [];
- $scope.temp.policy.settings = [];
- $scope.temp.policy.attributes = [];
- }
- if (ruleProvider === "Raw") {
- $scope.notRawPolicy = false;
- }
- };
-
- $scope.importButton = true;
- var fd;
- $scope.uploadBLFile = function(files) {
- fd = new FormData();
- fd.append("file", files[0]);
- var fileExtension = files[0].name.split(".")[1];
- if (fileExtension == "xls") {
- $scope.importButton = false;
- $scope.$apply();
- } else {
- Notification.error("Upload the BlackList file which extends with .xls format.");
- }
- };
-
- function arrayUnique(array) {
- var a = array.concat();
- for (var i = 0; i < a.length; ++i) {
- for (var j = i + 1; j < a.length; ++j) {
- if (a[i] === a[j])
- a.splice(j--, 1);
- }
- }
- return a;
- }
-
- $scope.submitUpload = function() {
- $http.post("policycreation/importBlackListForDecisionPolicy", fd, {
- withCredentials : false,
- headers : {
- 'Content-Type' : undefined
- },
- transformRequest : angular.identity
- }).success(function(data) {
- $scope.data = JSON.parse(data.data);
- $scope.temp.policy.blackListEntries = $scope.data.blackListEntries;
- if ($scope.temp.policy.blackListEntries[0] !== "error") {
- $scope.blackListEntries = arrayUnique($scope.temp.policy.blackListEntries.concat($scope.temp.policy.yamlparams.blackList));
- $scope.temp.policy.appendBlackListEntries = $scope.data.appendBlackListEntries;
- $scope.blackListEntries = $scope.blackListEntries.filter(function(obj) {
- return !$scope.temp.policy.appendBlackListEntries.includes(obj);
- });
- if ($scope.blackListEntries.length == 0) {
- $scope.validateButton = true;
- Notification.error("Black Lists are empty. Minimum one entry required.");
- } else {
- $scope.temp.policy.blackListEntries = $scope.blackListEntries;
- Notification.success("Blacklist File Uploaded Successfully.");
- $scope.validateButton = false;
- $scope.importButton = true;
- }
- } else {
- Notification.error("Blacklist File Upload Failed." + $scope.temp.policy.blackListEntries[1]);
- }
- }).error(function(data) {
- Notification.error("Blacklist File Upload Failed.");
- });
- };
-
- $scope.initializeBlackList = function() {
- if ($scope.temp.policy.blackListEntryType === "Use File Upload") {
- $scope.validateButton = true;
- } else {
- $scope.validateButton = false;
- }
- $("#importFile").val('');
- };
-
- $scope.exportBlackListEntries = function() {
- var uuu = "policycreation/exportDecisionBlackListEntries";
- var postData = {
- policyData : $scope.temp.policy,
- date : $scope.temp.model.modifiedDate,
- version : $scope.temp.model.version
- };
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType : 'json',
- contentType : 'application/json',
- data : JSON.stringify(postData),
- success : function(data) {
- $scope.$apply(function() {
- $scope.data = data.data;
- var url = '../' + $scope.data;
- window.location = url;
- Notification.success("BlackList Entries Exported Successfully.");
- });
- console.log($scope.data);
- },
- error : function(data) {
- Notification.error("Error Occured while Exporting BlackList Entries.");
- }
- });
- };
-} ]); \ No newline at end of file
+ $scope.temp.policy.yamlparams.blackList = $scope.temp.policy.yamlparams.blackList.filter(function (obj){
+ return obj !== id;
+ });
+ };
+
+ $scope.treatmentDatas = [ {
+ "treatmentValues" : $scope.temp.policy.rainyday.treatmentTableChoices
+ } ];
+
+ $scope.addNewTreatment = function() {
+ $scope.temp.policy.rainyday.treatmentTableChoices.push({});
+ };
+
+ $scope.removeTreatment = function() {
+ var lastItem = $scope.temp.policy.rainyday.treatmentTableChoices.length - 1;
+ $scope.temp.policy.rainyday.treatmentTableChoices.splice(lastItem);
+ };
+
+ $scope.workstepDictionaryDatas = [];
+ $scope.getWorkstepValues = function(bbidValue) {
+ for (var i = 0; i < $scope.rainyDayDictionaryDataEntity.length; ++i) {
+ var obj = $scope.rainyDayDictionaryDataEntity[i];
+ if (obj.bbid == bbidValue) {
+ $scope.workstepDictionaryDatas.push(obj.workstep);
+ }
+ }
+ };
+
+ $scope.allowedTreatmentsDatas = [];
+ $scope.getTreatmentValues = function(bbidValue, workstepValue) {
+ for (var i = 0; i < $scope.rainyDayDictionaryDataEntity.length; ++i) {
+ var obj = $scope.rainyDayDictionaryDataEntity[i];
+ if (obj.bbid == bbidValue && obj.workstep == workstepValue) {
+ var splitAlarm = obj.treatments.split(',');
+ for (var j = 0; j < splitAlarm.length; ++j) {
+ $scope.allowedTreatmentsDatas.push(splitAlarm[j]);
+ }
+ }
+ }
+ };
+
+ $scope.ItemNo = 0;
+ $scope.ruleAlgorithmDatas = [ {
+ "ruleAlgorithms" : $scope.temp.policy.ruleAlgorithmschoices
+ } ];
+
+ $scope.addNewRuleAlgorithm = function() {
+ if ($scope.temp.policy.ruleAlgorithmschoices != null) {
+ var newItemNo = $scope.temp.policy.ruleAlgorithmschoices.length + 1;
+ } else {
+ var newItemNo = 1;
+ }
+ if (newItemNo > 1) {
+ var value = newItemNo - 1;
+ $scope.attributeDictionaryDatas.push('A' + value);
+ }
+ $scope.temp.policy.ruleAlgorithmschoices.push({
+ 'id' : 'A' + newItemNo
+ });
+ };
+
+ $scope.removeRuleAlgorithm = function() {
+ var lastItem = $scope.temp.policy.ruleAlgorithmschoices.length - 1;
+ $scope.temp.policy.ruleAlgorithmschoices.splice(lastItem);
+ };
+
+ $scope.providerListener = function(ruleProvider) {
+ if (ruleProvider != "Custom") {
+ $scope.temp.policy.ruleAlgorithmschoices = [];
+ $scope.temp.policy.settings = [];
+ $scope.temp.policy.attributes = [];
+ }
+ if (ruleProvider === "Raw") {
+ $scope.notRawPolicy = false;
+ }
+ };
+
+ $scope.importButton = true;
+ var fd;
+ $scope.uploadBLFile = function(files) {
+ fd = new FormData();
+ fd.append("file", files[0]);
+ var fileExtension = files[0].name.split(".")[1];
+ if (fileExtension == "xls") {
+ $scope.importButton = false;
+ $scope.$apply();
+ } else {
+ Notification.error("Upload the BlackList file which extends with .xls format.");
+ }
+ };
+
+ function arrayUnique(array) {
+ var a = array.concat();
+ for (var i = 0; i < a.length; ++i) {
+ for (var j = i + 1; j < a.length; ++j) {
+ if (a[i] === a[j])
+ a.splice(j--, 1);
+ }
+ }
+ return a;
+ }
+
+ $scope.submitUpload = function() {
+ $http.post("policycreation/importBlackListForDecisionPolicy", fd, {
+ withCredentials : false,
+ headers : {
+ 'Content-Type' : undefined
+ },
+ transformRequest : angular.identity
+ }).success(function(data) {
+ $scope.data = JSON.parse(data.data);
+ $scope.temp.policy.blackListEntries = $scope.data.blackListEntries;
+ if ($scope.temp.policy.blackListEntries[0] !== "error") {
+ $scope.blackListEntries = arrayUnique($scope.temp.policy.blackListEntries.concat($scope.temp.policy.yamlparams.blackList));
+ $scope.temp.policy.appendBlackListEntries = $scope.data.appendBlackListEntries;
+ $scope.blackListEntries = $scope.blackListEntries.filter(function(obj) {
+ return !$scope.temp.policy.appendBlackListEntries.includes(obj);
+ });
+ if ($scope.blackListEntries.length == 0) {
+ $scope.validateButton = true;
+ Notification.error("Black Lists are empty. Minimum one entry required.");
+ } else {
+ $scope.temp.policy.blackListEntries = $scope.blackListEntries;
+ Notification.success("Blacklist File Uploaded Successfully.");
+ $scope.validateButton = false;
+ $scope.importButton = true;
+ }
+ } else {
+ Notification.error("Blacklist File Upload Failed." + $scope.temp.policy.blackListEntries[1]);
+ }
+ }).error(function(data) {
+ Notification.error("Blacklist File Upload Failed.");
+ });
+ };
+
+ $scope.initializeBlackList = function() {
+ if ($scope.temp.policy.blackListEntryType === "Use File Upload") {
+ $scope.validateButton = true;
+ } else {
+ $scope.validateButton = false;
+ }
+ $("#importFile").val('');
+ };
+
+ $scope.exportBlackListEntries = function() {
+ var uuu = "policycreation/exportDecisionBlackListEntries";
+ var postData = {
+ policyData : $scope.temp.policy,
+ date : $scope.temp.model.modifiedDate,
+ version : $scope.temp.model.version
+ };
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType : 'json',
+ contentType : 'application/json',
+ data : JSON.stringify(postData),
+ success : function(data) {
+ $scope.$apply(function() {
+ $scope.data = data.data;
+ var url = '../' + $scope.data;
+ window.location = url;
+ Notification.success("BlackList Entries Exported Successfully.");
+ });
+ },
+ error : function(data) {
+ Notification.error("Error Occured while Exporting BlackList Entries.");
+ }
+ });
+ };
+} ]);
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/FirewallPolicyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/FirewallPolicyController.js
index 1051ecd9a..b62f91d0d 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/FirewallPolicyController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/FirewallPolicyController.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.
@@ -17,7 +17,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-angular.module('abs').controller('fwPolicyController', ['$scope', '$window', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', function ($scope, $window, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) {
+angular.module('abs').controller('fwPolicyController',
+ ['$scope', '$window', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification',
+ function ($scope, $window, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) {
$("#dialog").hide();
$scope.policyNavigator;
@@ -25,18 +27,18 @@ angular.module('abs').controller('fwPolicyController', ['$scope', '$window', 'Po
$scope.refreshCheck = false;
if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
- $scope.temp.policy = {
- policyType : "Config",
- configPolicyType : "Firewall Config"
- }
+ $scope.temp.policy = {
+ policyType : "Config",
+ configPolicyType : "Firewall Config"
+ }
};
$scope.refresh = function(){
- if($scope.refreshCheck){
- $scope.policyNavigator.refresh();
- }
- $scope.modal('createNewPolicy', true);
- $scope.temp.policy = "";
+ if($scope.refreshCheck){
+ $scope.policyNavigator.refresh();
+ }
+ $scope.modal('createNewPolicy', true);
+ $scope.temp.policy = "";
};
$scope.modal = function(id, hide) {
@@ -44,83 +46,51 @@ angular.module('abs').controller('fwPolicyController', ['$scope', '$window', 'Po
};
$('#ttlDate').datepicker({
- dateFormat: 'dd/mm/yy',
- changeMonth: true,
- changeYear: true,
- onSelect: function(date) {
- angular.element($('#ttlDate')).triggerHandler('input');
- }
+ dateFormat: 'dd/mm/yy',
+ changeMonth: true,
+ changeYear: true,
+ onSelect: function(date) {
+ angular.element($('#ttlDate')).triggerHandler('input');
+ }
});
-
+
PolicyAppService.getData('getDictionary/get_SecurityZoneDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.securityZoneDictionaryDatas = JSON.parse($scope.data.securityZoneDictionaryDatas);
- console.log($scope.securityZoneDictionaryDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.securityZoneDictionaryDatas = JSON.parse($scope.data.securityZoneDictionaryDatas);
});
PolicyAppService.getData('getDictionary/get_TermListDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.termListDictionaryDatas = JSON.parse($scope.data.termListDictionaryDatas);
- console.log($scope.termListDictionaryDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.termListDictionaryDatas = JSON.parse($scope.data.termListDictionaryDatas);
});
PolicyAppService.getData('getDictionary/get_FWDictionaryListDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.fwDictListDictionaryDatas = JSON.parse($scope.data.fwDictListDictionaryDatas);
- console.log($scope.fwDictListDictionaryDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.fwDictListDictionaryDatas = JSON.parse($scope.data.fwDictListDictionaryDatas);
});
PolicyAppService.getData('getDictionary/get_FWParentListDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.fwParentListDictionaryDatas = JSON.parse($scope.data.fwParentListDictionaryDatas);
- console.log($scope.fwParentListDictionaryDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.fwParentListDictionaryDatas = JSON.parse($scope.data.fwParentListDictionaryDatas);
});
PolicyAppService.getData('getDictionary/get_TagPickerNameByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.fwTagPickerDictionaryDatas = JSON.parse($scope.data.fwTagPickerDictionaryDatas);
- console.log($scope.fwTagPickerDictionaryDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.fwTagPickerDictionaryDatas = JSON.parse($scope.data.fwTagPickerDictionaryDatas);
});
PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
- console.log($scope.riskTypeDictionaryDatas);
- }, function (error) {
- console.log("failed");
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
});
- function extend(obj, src) {
- for (var key in src) {
- if (src.hasOwnProperty(key)) obj[key] = src[key];
- }
- return obj;
- }
-
$scope.viewFWRule = function(policy){
- console.log(policy);
var uuu = "policyController/ViewFWPolicyRule.htm";
var postData={policyData: policy};
$.ajax({
@@ -131,110 +101,106 @@ angular.module('abs').controller('fwPolicyController', ['$scope', '$window', 'Po
data: JSON.stringify(postData),
success : function(data){
$scope.$apply(function(){
- window.alert(data.policyData);
+ window.alert(data.policyData);
});
},
error : function(data){
- Notification.error("Error Occured while Showing Rule.");
+ Notification.error("Error Occured while Showing Rule.");
}
});
};
$scope.saveFWPolicy = function(policy){
- if(policy.itemContent != undefined){
- $scope.refreshCheck = true;
- $scope.policyNavigator = policy.itemContent;
- policy.itemContent = "";
- }
- $scope.savebutton = false;
- console.log(policy);
+ if(policy.itemContent != undefined){
+ $scope.refreshCheck = true;
+ $scope.policyNavigator = policy.itemContent;
+ policy.itemContent = "";
+ }
+ $scope.savebutton = false;
var uuu = "policycreation/save_policy";
- var postData={policyData: policy};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.data=data.policyData;
- if($scope.data == 'success'){
- $scope.temp.policy.readOnly = 'true';
- $scope.pushStatus=data.policyData.split("&")[1];
- if($scope.pushStatus=="successPush"){
- Notification.success("Policy pushed successfully");
- }
- Notification.success("Policy Saved Successfully.");
- }else if ($scope.data == 'PolicyExists'){
- $scope.savebutton = true;
- Notification.error("Policy Already Exists with Same Name in Scope.");
- }
- });
- console.log($scope.data);
- },
- error : function(data){
- Notification.error("Error Occured while saving Policy.");
- }
- });
+ var postData={policyData: policy};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.data=data.policyData;
+ if($scope.data == 'success'){
+ $scope.temp.policy.readOnly = 'true';
+ $scope.pushStatus=data.policyData.split("&")[1];
+ if($scope.pushStatus=="successPush"){
+ Notification.success("Policy pushed successfully");
+ }
+ Notification.success("Policy Saved Successfully.");
+ }else if ($scope.data == 'PolicyExists'){
+ $scope.savebutton = true;
+ Notification.error("Policy Already Exists with Same Name in Scope.");
+ }
+ });
+ },
+ error : function(data){
+ Notification.error("Error Occured while saving Policy.");
+ }
+ });
};
$scope.validatePolicy = function(policy){
- console.log(policy);
- document.getElementById("validate").innerHTML = "";
+ document.getElementById("validate").innerHTML = "";
var uuu = "policyController/validate_policy.htm";
- var postData={policyData: policy};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.validateData = data.data.replace(/\"/g, "");
- $scope.data=data.data.substring(1,8);
- var size = data.data.length;
- if($scope.data == 'success'){
- Notification.success("Validation Success.");
- $scope.savebutton = false;
- if (size > 18){
- var displayWarning = data.data.substring(19,size);
- document.getElementById("validate").innerHTML = "Safe Policy Warning Message : "+displayWarning;
- document.getElementById("validate").style.color = "white";
- document.getElementById("validate").style.backgroundColor = "skyblue";
- }
- }else{
- Notification.error("Validation Failed.");
- document.getElementById("validate").innerHTML = $scope.validateData;
- document.getElementById("validate").style.color = "white";
- document.getElementById("validate").style.backgroundColor = "red";
- $scope.savebutton = true;
- }
-
- });
- console.log($scope.data);
-
- },
- error : function(data){
- Notification.error("Validation Failed.");
- $scope.savebutton = true;
- }
- });
+ var postData={policyData: policy};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.validateData = data.data.replace(/\"/g, "");
+ $scope.data=data.data.substring(1,8);
+ var size = data.data.length;
+ if($scope.data == 'success'){
+ Notification.success("Validation Success.");
+ $scope.savebutton = false;
+ if (size > 18){
+ var displayWarning = data.data.substring(19,size);
+ document.getElementById("validate").innerHTML = "Safe Policy Warning Message : "+displayWarning;
+ document.getElementById("validate").style.color = "white";
+ document.getElementById("validate").style.backgroundColor = "skyblue";
+ }
+ }else{
+ Notification.error("Validation Failed.");
+ document.getElementById("validate").innerHTML = $scope.validateData;
+ document.getElementById("validate").style.color = "white";
+ document.getElementById("validate").style.backgroundColor = "red";
+ $scope.savebutton = true;
+ }
+
+ });
+
+ },
+ error : function(data){
+ Notification.error("Validation Failed.");
+ $scope.savebutton = true;
+ }
+ });
};
if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
- $scope.temp.policy.attributes = [];
- $scope.temp.policy.fwattributes = [];
+ $scope.temp.policy.attributes = [];
+ $scope.temp.policy.fwattributes = [];
}else{
if($scope.temp.policy.attributes.length == 0){
- $scope.temp.policy.attributes = [];
+ $scope.temp.policy.attributes = [];
}
if($scope.temp.policy.fwPolicyType == 'Parent Policy'){
- if($scope.temp.policy.fwattributes.length == 0){
- $scope.temp.policy.fwattributes = [];
- }
+ if($scope.temp.policy.fwattributes.length == 0){
+ $scope.temp.policy.fwattributes = [];
+ }
}
}
@@ -258,4 +224,4 @@ angular.module('abs').controller('fwPolicyController', ['$scope', '$window', 'Po
$scope.temp.policy.fwattributes.splice(lastItem);
};
-}]); \ No newline at end of file
+}]);
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/OptimizationPolicyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/OptimizationPolicyController.js
index cdeaefdea..58594bc43 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/OptimizationPolicyController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/OptimizationPolicyController.js
@@ -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.
@@ -17,7 +17,9 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-angular.module('abs').controller('optimizationController', ['$scope', '$window', '$compile', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification', function ($scope, $window, $compile, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) {
+angular.module('abs').controller('optimizationController',
+ ['$scope', '$window', '$compile', 'PolicyAppService', 'policyNavigator', 'modalService', '$modal', 'Notification',
+ function ($scope, $window, $compile, PolicyAppService, PolicyNavigator, modalService, $modal, Notification) {
$("#dialog").hide();
$scope.policyNavigator;
@@ -26,18 +28,18 @@ angular.module('abs').controller('optimizationController', ['$scope', '$window',
$scope.refreshCheck = false;
if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
- $scope.temp.policy = {
- policyType : "Config",
- configPolicyType : "Optimization"
- }
- };
+ $scope.temp.policy = {
+ policyType : "Config",
+ configPolicyType : "Optimization"
+ }
+ }
$scope.refresh = function(){
- if($scope.refreshCheck){
- $scope.policyNavigator.refresh();
- }
- $scope.modal('createNewPolicy', true);
- $scope.temp.policy = "";
+ if($scope.refreshCheck){
+ $scope.policyNavigator.refresh();
+ }
+ $scope.modal('createNewPolicy', true);
+ $scope.temp.policy = "";
};
$scope.modal = function(id, hide) {
@@ -45,247 +47,226 @@ angular.module('abs').controller('optimizationController', ['$scope', '$window',
};
$('#ttlDate').datepicker({
- dateFormat: 'dd/mm/yy',
- changeMonth: true,
- changeYear: true,
- onSelect: function(date) {
- angular.element($('#ttlDate')).triggerHandler('input');
- }
+ dateFormat: 'dd/mm/yy',
+ changeMonth: true,
+ changeYear: true,
+ onSelect: function(date) {
+ angular.element($('#ttlDate')).triggerHandler('input');
+ }
});
- if ($scope.temp.policy.editPolicy != undefined|| $scope.temp.policy.readOnly != undefined){
- if ($scope.temp.policy.configName == undefined){
- $scope.isCheck = false;
- }else{
- $scope.isCheck = true;
- }
- }else {
- $scope.isCheck = false;
- }
-
- 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);
- console.log($scope.onapNameDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ if ($scope.temp.policy.editPolicy != undefined|| $scope.temp.policy.readOnly != undefined){
+ if ($scope.temp.policy.configName == undefined){
+ $scope.isCheck = false;
+ }else{
+ $scope.isCheck = true;
+ }
+ }else {
+ $scope.isCheck = false;
+ }
+
+ PolicyAppService.getData('getDictionary/get_OnapNameDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
+ });
- PolicyAppService.getData('get_DCAEPriorityValues').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.priorityDatas = JSON.parse($scope.data.priorityDatas);
- console.log($scope.priorityDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('get_DCAEPriorityValues').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.priorityDatas = JSON.parse($scope.data.priorityDatas);
+ });
- PolicyAppService.getData('getDictionary/get_OptimizationModelsDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- var inputModelList = JSON.parse($scope.data.optimizationModelsDictionaryDatas);
- var unique = {};
- var uniqueList = [];
- for(var i = 0; i < inputModelList.length; i++){
- if(typeof unique[inputModelList[i]] == "undefined"){
- unique[inputModelList[i]] = "";
- uniqueList.push(inputModelList[i]);
- }
- }
- $scope.optimizationModelsDictionaryDatas = uniqueList;
- console.log($scope.optimizationModelsDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_OptimizationModelsDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ var inputModelList = JSON.parse($scope.data.optimizationModelsDictionaryDatas);
+ var unique = {};
+ var uniqueList = [];
+ for(var i = 0; i < inputModelList.length; i++){
+ if(typeof unique[inputModelList[i]] == "undefined"){
+ unique[inputModelList[i]] = "";
+ uniqueList.push(inputModelList[i]);
+ }
+ }
+ $scope.optimizationModelsDictionaryDatas = uniqueList;
+ });
- PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
- var j = data;
- $scope.data = JSON.parse(j.data);
- console.log($scope.data);
- $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
- console.log($scope.riskTypeDictionaryDatas);
- }, function (error) {
- console.log("failed");
- });
+ PolicyAppService.getData('getDictionary/get_RiskTypeDataByName').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.riskTypeDictionaryDatas = JSON.parse($scope.data.riskTypeDictionaryDatas);
+ });
- $scope.choices = [];
- $scope.attributeDatas = [{"attributes" : $scope.choices}];
- $scope.isInitEditTemplate = true; //just initially create the edit template, didn't click add button yet.
- $scope.addNewChoice = function(value) {
- console.log("input value : " + value);
- if(value != undefined){
- if (value.startsWith('div.')){
- value = value.replace('div.','');
- }
- var parentElement = document.getElementById("div."+value);
- var div = document.getElementById(value+"@0");
- if(div != null){
- var clone = div.cloneNode(true);
- var addElement = parentElement.childElementCount;
- clone.id = ''+value+'@'+addElement;
- clone.value = '';
- if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){ //if it's view or edit
- if($scope.temp.policy.ruleData[clone.id] || ($scope.temp.policy.editPolicy && !$scope.isInitEditTemplate)){ // Only append child if its value found in ruleData or edit mode
- if($scope.temp.policy.ruleData[clone.id]){
- clone.value = $scope.temp.policy.ruleData[clone.id];
- }
- if(!clone.className.includes("child_single")){
- clone.className += ' child_single'; //single element clone
- }
- document.getElementById("div."+value).appendChild(clone);
- plainAttributeKeys.push(''+value+'@'+addElement);
- }
- }else{ //not view or edit
- if(!clone.className.includes("child_single")){
- clone.className += ' child_single'; //single element clone
- }
- document.getElementById("div."+value).appendChild(clone);
- plainAttributeKeys.push(''+value+'@'+addElement);
- }
- }else{
- div = document.getElementById("div."+value+"@0");
-
- if(div){
- div.className += ' children_group'; //div with a group of children.
- }
- var childElement = parentElement.firstElementChild;
- var countParent = parentElement.childElementCount;
- var childElementString = childElement.innerHTML;
- var find = value+"@0";
- var re = new RegExp(find, 'g');
- childElementString = childElementString.replace(re,value+'@' + countParent);
- var clone = childElement.cloneNode(true);
- for (var ii = 0; ii < parentElement.childNodes.length; ii++){
- var childId = parentElement.childNodes[ii].id;
- if(ii = parentElement.childNodes.length){
- var childnewId = childId.slice(0, -1);
- var count = childId.slice(-1);
- }
- }
- var countvalue = parseInt(count) + 1;
- clone.id = childnewId+countvalue;
- clone.value = '';
- clone.innerHTML=childElementString;
- document.getElementById("div."+value).appendChild(clone);
- var selects = clone.getElementsByTagName("select");
- var inputs = clone.getElementsByTagName("input");
- var removeValues = [];
- for(var i=0; i<inputs.length; i++){
- if ($scope.temp.policy.ruleData!=undefined){
- var checkValue = $scope.temp.policy.ruleData[inputs[i].id];
- if (checkValue!=undefined && checkValue != "undefined"){
- if($scope.temp.policy.ruleData != null){
- var checkValue = $scope.temp.policy.ruleData[inputs[i].id];
- document.getElementById(inputs[i].id).value = $scope.temp.policy.ruleData[inputs[i].id];
- plainAttributeKeys.push(inputs[i].id);
- }
- } else {
- plainAttributeKeys.push(inputs[i].id);
- }
- }else {
- plainAttributeKeys.push(inputs[i].id);
- }
- }
-
- for(var i=0; i<selects.length; i++){
- if ($scope.temp.policy.ruleData!=undefined){
- var checkValue = $scope.temp.policy.ruleData[selects[i].id];
- if (checkValue!=undefined && checkValue!="undefined"){
- if($scope.temp.policy.ruleData != null){
- var checkValue = $scope.temp.policy.ruleData[selects[i].id];
- document.getElementById(selects[i].id).value = $scope.temp.policy.ruleData[selects[i].id];
- plainAttributeKeys.push(selects[i].id);
- }
- } else {
- plainAttributeKeys.push(selects[i].id);
- }
- }else {
- plainAttributeKeys.push(selects[i].id);
- }
- }
-
- for (var k=0; k<removeValues.length; k++){
- var elem = document.getElementById(removeValues[k]);
- elem.parentNode.removeChild(elem);
- }
- var ele = angular.element(document.getElementById("div."+value));
- $compile(ele.contents())($scope);
- $scope.$apply();
- }
- }
- };
-
- function findVal(object, key) {
- var value;
- Object.keys(object).some(function(k) {
- if (k === key) {
- value = object[k];
- return true;
- }
- if (object[k] && typeof object[k] === 'object') {
- value = findVal(object[k], key);
- return value !== undefined;
- }
- });
- return value;
- }
-
- $scope.removeChoice = function(value) {
- console.log(value);
- if(value != undefined){
- var c = document.getElementById("div."+value).childElementCount;
-
- if(c == 1){
- Notification.error("The original one is not removable.");
- return;
- }
- document.getElementById("div."+value).removeChild(document.getElementById("div."+value).lastChild);
- }
- };
-
- $scope.pullVersion = function(serviceName) {
- console.log(serviceName);
- if(serviceName != undefined){
- var uuu = "policyController/getModelServiceVersionData.htm";
- var postData={policyData: serviceName};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.optimizationModelsDictionaryVersionDatas = data[0].optimizationModelVersionData;
- });
- },
- error : function(data){
- alert("Error While Retrieving the Template Layout Pattern.");
- }
- });
- }
- };
+ $scope.choices = [];
+ $scope.attributeDatas = [{"attributes" : $scope.choices}];
+ $scope.isInitEditTemplate = true; //just initially create the edit template, didn't click add button yet.
+ $scope.addNewChoice = function(value) {
+ if(value != undefined){
+ if (value.startsWith('div.')){
+ value = value.replace('div.','');
+ }
+ var parentElement = document.getElementById("div."+value);
+ var div = document.getElementById(value+"@0");
+ if(div != null){
+ var clone = div.cloneNode(true);
+ var addElement = parentElement.childElementCount;
+ clone.id = ''+value+'@'+addElement;
+ clone.value = '';
+ if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){ //if it's view or edit
+ if($scope.temp.policy.ruleData[clone.id] || ($scope.temp.policy.editPolicy && !$scope.isInitEditTemplate)){ // Only append child if its value found in ruleData or edit mode
+ if($scope.temp.policy.ruleData[clone.id]){
+ clone.value = $scope.temp.policy.ruleData[clone.id];
+ }
+ if(!clone.className.includes("child_single")){
+ clone.className += ' child_single'; //single element clone
+ }
+ document.getElementById("div."+value).appendChild(clone);
+ plainAttributeKeys.push(''+value+'@'+addElement);
+ }
+ }else{ //not view or edit
+ if(!clone.className.includes("child_single")){
+ clone.className += ' child_single'; //single element clone
+ }
+ document.getElementById("div."+value).appendChild(clone);
+ plainAttributeKeys.push(''+value+'@'+addElement);
+ }
+ }else{
+ div = document.getElementById("div."+value+"@0");
+
+ if(div){
+ div.className += ' children_group'; //div with a group of children.
+ }
+ var childElement = parentElement.firstElementChild;
+ var countParent = parentElement.childElementCount;
+ var childElementString = childElement.innerHTML;
+ var find = value+"@0";
+ var re = new RegExp(find, 'g');
+ childElementString = childElementString.replace(re,value+'@' + countParent);
+ var clone = childElement.cloneNode(true);
+ for (var ii = 0; ii < parentElement.childNodes.length; ii++){
+ var childId = parentElement.childNodes[ii].id;
+ if(ii = parentElement.childNodes.length){
+ var childnewId = childId.slice(0, -1);
+ var count = childId.slice(-1);
+ }
+ }
+ var countvalue = parseInt(count) + 1;
+ clone.id = childnewId+countvalue;
+ clone.value = '';
+ clone.innerHTML=childElementString;
+ document.getElementById("div."+value).appendChild(clone);
+ var selects = clone.getElementsByTagName("select");
+ var inputs = clone.getElementsByTagName("input");
+ var removeValues = [];
+ for(var i=0; i<inputs.length; i++){
+ if ($scope.temp.policy.ruleData!=undefined){
+ var checkValue = $scope.temp.policy.ruleData[inputs[i].id];
+ if (checkValue!=undefined && checkValue != "undefined"){
+ if($scope.temp.policy.ruleData != null){
+ var checkValue = $scope.temp.policy.ruleData[inputs[i].id];
+ document.getElementById(inputs[i].id).value = $scope.temp.policy.ruleData[inputs[i].id];
+ plainAttributeKeys.push(inputs[i].id);
+ }
+ } else {
+ plainAttributeKeys.push(inputs[i].id);
+ }
+ }else {
+ plainAttributeKeys.push(inputs[i].id);
+ }
+ }
+
+ for(var i=0; i<selects.length; i++){
+ if ($scope.temp.policy.ruleData!=undefined){
+ var checkValue = $scope.temp.policy.ruleData[selects[i].id];
+ if (checkValue!=undefined && checkValue!="undefined"){
+ if($scope.temp.policy.ruleData != null){
+ var checkValue = $scope.temp.policy.ruleData[selects[i].id];
+ document.getElementById(selects[i].id).value = $scope.temp.policy.ruleData[selects[i].id];
+ plainAttributeKeys.push(selects[i].id);
+ }
+ } else {
+ plainAttributeKeys.push(selects[i].id);
+ }
+ }else {
+ plainAttributeKeys.push(selects[i].id);
+ }
+ }
+
+ for (var k=0; k<removeValues.length; k++){
+ var elem = document.getElementById(removeValues[k]);
+ elem.parentNode.removeChild(elem);
+ }
+ var ele = angular.element(document.getElementById("div."+value));
+ $compile(ele.contents())($scope);
+ $scope.$apply();
+ }
+ }
+ };
+
+ function findVal(object, key) {
+ var value;
+ Object.keys(object).some(function(k) {
+ if (k === key) {
+ value = object[k];
+ return true;
+ }
+ if (object[k] && typeof object[k] === 'object') {
+ value = findVal(object[k], key);
+ return value !== undefined;
+ }
+ });
+ return value;
+ }
+
+ $scope.removeChoice = function(value) {
+ if(value != undefined){
+ var c = document.getElementById("div."+value).childElementCount;
+
+ if(c == 1){
+ Notification.error("The original one is not removable.");
+ return;
+ }
+ document.getElementById("div."+value).removeChild(document.getElementById("div."+value).lastChild);
+ }
+ };
+
+ $scope.pullVersion = function(serviceName) {
+ if(serviceName != undefined){
+ var uuu = "policyController/getModelServiceVersionData.htm";
+ var postData={policyData: serviceName};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.optimizationModelsDictionaryVersionDatas = data[0].optimizationModelVersionData;
+ });
+ },
+ error : function(data){
+ Notification.error("Error While Retrieving the Template Layout Pattern.");
+ }
+ });
+ }
+ };
- var splitDash = '-';
- var splitEqual = '=';
- var splitComma = ',';
- var splitcolon = ':';
- var splitsemicolon = ";";
- var splitEnum = "],";
- var plainAttributeKeys = [];
- var matching = [];
- var enumKeyList = [];
- var dictionaryList = [];
- var dictionaryNameList = [];
+ var splitEqual = '=';
+ var splitComma = ',';
+ var splitcolon = ':';
+ var splitEnum = "],";
+ var plainAttributeKeys = [];
+ var matching = [];
+ var enumKeyList = [];
+ var dictionaryList = [];
+ var dictionaryNameList = [];
$scope.addDataToFields = function(serviceName, version){
if(serviceName != null && version !=null){
- var service=serviceName+"-v"+version;
- var myNode = document.getElementById("DynamicTemplate");
- myNode.innerHTML = '';
+ var service=serviceName+"-v"+version;
+ var myNode = document.getElementById("DynamicTemplate");
+ myNode.innerHTML = '';
var uuu = "policyController/getOptimizationTemplateData.htm";
var postData={policyData: service};
var dataOrderInfo = "";
@@ -298,967 +279,931 @@ angular.module('abs').controller('optimizationController', ['$scope', '$window',
data: JSON.stringify(postData),
success : function(data){
$scope.$apply(function(){
- var plainAttributeKeys = [];
- $scope.optimizationModelData = data[0].optimizationModelData;
- $scope.optimizationJsonDate = data[0].jsonValue;
+ $scope.optimizationModelData = data[0].optimizationModelData;
+ $scope.optimizationJsonDate = data[0].jsonValue;
$scope.dataOrderInfo = null;
- $scope.dataOrderInfo = data[0].dataOrderInfo;
- console.log("data[0].dataOrderInfo: " + data[0].dataOrderInfo);
- console.log("$scope.dataOrderInfo: " + $scope.dataOrderInfo);
- if(data[0].allManyTrueKeys){
- console.log("$scope.allManyTrueKeys: " + $scope.allManyTrueKeys);
- }
- console.log("$scope.optimizationJsonDate: " + $scope.optimizationJsonDate);
- var attributes = $scope.optimizationModelData.attributes;
- var refAttributes = $scope.optimizationModelData.ref_attributes;
- var subAttributes = $scope.optimizationModelData.sub_attributes;
- console.log("attributes: " +attributes);
- console.log("subAttributes: " + subAttributes);
- console.log("refAttributes: " + refAttributes);
-
- var headDefautlsData = data[0].headDefautlsData;
- if(headDefautlsData != null){
- $scope.temp.policy.onapName = headDefautlsData.onapName;
- $scope.temp.policy.guard = headDefautlsData.guard;
- $scope.temp.policy.riskType = headDefautlsData.riskType;
- $scope.temp.policy.riskLevel = headDefautlsData.riskLevel;
- $scope.temp.policy.priority = headDefautlsData.priority;
-
- }else if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
- $scope.temp.policy.onapName = "";
- $scope.temp.policy.guard = "";
- $scope.temp.policy.riskType = "";
- $scope.temp.policy.riskLevel = "";
- $scope.temp.policy.priority = "";
- }
-
- var enumAttributes = $scope.optimizationModelData.enumValues;
- var annotation = $scope.optimizationModelData.annotation;
- var dictionary = $scope.microServiceAttributeDictionaryDatas;
+ var headDefautlsData = data[0].headDefautlsData;
+ if(headDefautlsData != null){
+ $scope.temp.policy.onapName = headDefautlsData.onapName;
+ $scope.temp.policy.guard = headDefautlsData.guard;
+ $scope.temp.policy.riskType = headDefautlsData.riskType;
+ $scope.temp.policy.riskLevel = headDefautlsData.riskLevel;
+ $scope.temp.policy.priority = headDefautlsData.priority;
+
+ }else if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
+ $scope.temp.policy.onapName = "";
+ $scope.temp.policy.guard = "";
+ $scope.temp.policy.riskType = "";
+ $scope.temp.policy.riskLevel = "";
+ $scope.temp.policy.priority = "";
+ }
+
+ var annotation = $scope.optimizationModelData.annotation;
+ var dictionary = $scope.microServiceAttributeDictionaryDatas;
- if (annotation == null || annotation.length<1){
- $scope.isCheck = true;
- }else {
- $scope.isCheck = false;
- var annoationList = annotation.split(splitComma);
- for (k = 0; k < annoationList.length; k++){
- var splitAnnotation = annoationList[k].split(splitEqual);
- if (splitAnnotation[1].includes("matching-true")){
- matching.push(splitAnnotation[0].trim());
- }
- }
+ if (annotation == null || annotation.length<1){
+ $scope.isCheck = true;
+ }else {
+ $scope.isCheck = false;
+ var annoationList = annotation.split(splitComma);
+ for (k = 0; k < annoationList.length; k++){
+ var splitAnnotation = annoationList[k].split(splitEqual);
+ if (splitAnnotation[1].includes("matching-true")){
+ matching.push(splitAnnotation[0].trim());
+ }
+ }
- }
+ }
- if (dictionary!= null && dictionary.length>1){
- for (m=0; m < dictionary.length; m += 1){
- var keyCompare = dictionary[m].name;
- var valueCompare = dictionary[m].value;
- var valueModel = dictionary[m].modelName;
- var conpairService = serviceName;
- if (valueModel.includes('-v')){
- conpairService = service;
- }
- if(valueModel.localeCompare(conpairService) == 0){
- console.log(valueCompare);
- dictionaryList.push(dictionary[m]);
- if (!dictionaryNameList.includes(dictionary[m].name)){
- dictionaryNameList.push(dictionary[m].name)
- }
- }
- }
- }
+ if (dictionary!= null && dictionary.length>1){
+ for (m=0; m < dictionary.length; m += 1){
+ var valueCompare = dictionary[m].value;
+ var valueModel = dictionary[m].modelName;
+ var conpairService = serviceName;
+ if (valueModel.includes('-v')){
+ conpairService = service;
+ }
+ if(valueModel.localeCompare(conpairService) == 0){
+ dictionaryList.push(dictionary[m]);
+ if (!dictionaryNameList.includes(dictionary[m].name)){
+ dictionaryNameList.push(dictionary[m].name)
+ }
+ }
+ }
+ }
- $scope.temp.policy.ruleGridData = [];
-
- if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){
- dataOrderInfo = $scope.dataOrderInfo;
- }
-
- $scope.jsonLayout($scope.optimizationJsonDate);
-
+ $scope.temp.policy.ruleGridData = [];
+
+ if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){
+ dataOrderInfo = $scope.dataOrderInfo;
+ }
+
+ $scope.jsonLayout($scope.optimizationJsonDate);
+
});
if($scope.temp.policy.editPolicy || $scope.temp.policy.readOnly){ // If it's veiw or edit
-
- if($scope.temp.policy.editPolicy){
- $scope.isInitEditTemplate = true;
- }
-
- var checkData = [];
- var data = [];
- // If ruleData contains extra elements created by clicked add button
- if($scope.temp.policy.ruleData != null){
- var propNames = Object.getOwnPropertyNames($scope.temp.policy.ruleData);
- propNames.forEach(function(name) {
- data.push(name);
- });
-
- var extraElements = data;
-
- if(plainAttributeKeys != null){
- for(b = 0; b < plainAttributeKeys.length; b++){ // Remove already populated elements from data array
- var newValue = plainAttributeKeys[b].split("*");
- for(a = 0; a < data.length; a++){
- if(data[a] === newValue[0] || data[a] === (newValue[0]+"@0")){
- extraElements.splice(a, 1);
- }
- }
-
- }
-
- //--- Populate these extra elements created by clicked add button
- for(a = 0; a < extraElements.length; a++){
- if(extraElements[a].includes("@")){
- var index = extraElements[a].lastIndexOf("@");
- if(index > 0){
- // Get the number after @
- var n = getNumOfDigits(extraElements[a], index+1);
-
- var key = extraElements[a].substring(0, index+n+1); //include @x in key also by n+2 since x can be 1,12, etc
- console.log("key: " + key);
- checkData.push(key);
- }
- }
- }
- var unique = checkData.filter(onlyUnique);
- //if no layout order info, keep the process as before
- if(!dataOrderInfo){
- for(i =0; i < unique.length; i++){
- //remove @x and let addNewChoice add @1 or @2...
- //var newKey = unique[i].substring(0, unique[i].length-2);
- var index = unique[i].lastIndexOf("@");
- var newKey = unique[i].substring(0, index);
- console.log("newKey: " + newKey);
- $scope.addNewChoice(newKey);
- }
- }else{
+
+ if($scope.temp.policy.editPolicy){
+ $scope.isInitEditTemplate = true;
+ }
+
+ var checkData = [];
+ var data = [];
+ // If ruleData contains extra elements created by clicked add button
+ if($scope.temp.policy.ruleData != null){
+ var propNames = Object.getOwnPropertyNames($scope.temp.policy.ruleData);
+ propNames.forEach(function(name) {
+ data.push(name);
+ });
+
+ var extraElements = data;
+
+ if(plainAttributeKeys != null){
+ for(b = 0; b < plainAttributeKeys.length; b++){ // Remove already populated elements from data array
+ var newValue = plainAttributeKeys[b].split("*");
+ for(a = 0; a < data.length; a++){
+ if(data[a] === newValue[0] || data[a] === (newValue[0]+"@0")){
+ extraElements.splice(a, 1);
+ }
+ }
+
+ }
+
+ //--- Populate these extra elements created by clicked add button
+ for(a = 0; a < extraElements.length; a++){
+ if(extraElements[a].includes("@")){
+ var index = extraElements[a].lastIndexOf("@");
+ if(index > 0){
+ // Get the number after @
+ var n = getNumOfDigits(extraElements[a], index+1);
+
+ var key = extraElements[a].substring(0, index+n+1); //include @x in key also by n+2 since x can be 1,12, etc
+ checkData.push(key);
+ }
+ }
+ }
+ var unique = checkData.filter(onlyUnique);
+ //if no layout order info, keep the process as before
+ if(!dataOrderInfo){
+ for(i =0; i < unique.length; i++){
+ //remove @x and let addNewChoice add @1 or @2...
+ //var newKey = unique[i].substring(0, unique[i].length-2);
+ var index = unique[i].lastIndexOf("@");
+ var newKey = unique[i].substring(0, index);
+ $scope.addNewChoice(newKey);
+ }
+ }else{
- for (i = 0; i < $scope.labelManyKeys.length; i++) {
- console.log("dataOrderInfo["+i+"]"+ dataOrderInfo[i]);
- var label = $scope.labelManyKeys[i];
- // first add parent/label level
- for (k = 0; k < unique.length; k++){
- var newindex = unique[k].lastIndexOf("@");
- var newKey = unique[k].substring(0, index);
- if(label == newKey){
+ for (i = 0; i < $scope.labelManyKeys.length; i++) {
+ var label = $scope.labelManyKeys[i];
+ // first add parent/label level
+ for (k = 0; k < unique.length; k++){
+ var newKey = unique[k].substring(0, index);
+ if(label == newKey){
//Check this label has bee created or not
- if(!document.getElementById(unique[k])){
- $scope.addNewChoice(newKey);
- }
- unique[k] = "*processed*";
- break;
- }
- }
- }
-
- //---reset to default
- dataOrderInfo = [];
- $scope.labelManyKeys = [];
-
- //---process none labels
- for (j = 0; j < unique.length; j++){
- if(unique[j] != "*processed*"){
- // if not created yet
- if(!document.getElementById(unique[j])){
- var index = unique[j].lastIndexOf("@");
- var newKey = unique[j].substring(0, index);
- $scope.addNewChoice(newKey);
- }
- }
- }
- }
- }
- }
-
- if($scope.temp.policy.editPolicy){
- //clean all the events of addNewChoice
- $scope.$on('$destroy', addNewChoice);
- }
-
+ if(!document.getElementById(unique[k])){
+ $scope.addNewChoice(newKey);
+ }
+ unique[k] = "*processed*";
+ break;
+ }
+ }
+ }
+
+ //---reset to default
+ dataOrderInfo = [];
+ $scope.labelManyKeys = [];
+
+ //---process none labels
+ for (j = 0; j < unique.length; j++){
+ if(unique[j] != "*processed*"){
+ // if not created yet
+ if(!document.getElementById(unique[j])){
+ var index = unique[j].lastIndexOf("@");
+ var newKey = unique[j].substring(0, index);
+ $scope.addNewChoice(newKey);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if($scope.temp.policy.editPolicy){
+ //clean all the events of addNewChoice
+ $scope.$on('$destroy', addNewChoice);
+ }
+
}
var ele = angular.element(document.getElementById("DynamicTemplate"));
- $compile(ele.contents())($scope);
+ $compile(ele.contents())($scope);
$scope.$apply();
},
error : function(data){
- alert("Error While Retrieving the Template Layout Pattern.");
+ Notification.error("Error While Retrieving the Template Layout Pattern.");
}
});
}
};
function getNumOfDigits(str_value, index){
- // Get the number after @
- var str = str_value.substring(index, str_value.length);
- var c = '';
- var n = 0;
- for (var x = 0; x < str.length; x++){
- c = str.charAt(x);
- if(!isNaN(c)){
+ // Get the number after @
+ var str = str_value.substring(index, str_value.length);
+ var c = '';
+ var n = 0;
+ for (var x = 0; x < str.length; x++){
+ c = str.charAt(x);
+ if(!isNaN(c)){
n++;
- }else{
+ }else{
break;
}
- }
- return n;
+ }
+ return n;
}
function getDictionary(attribute){
- var dicName = attribute;
- if(attribute){
- if(attribute.includes(":")){
- dicName = attribute.split(":")[0];
- }
- }
- var dictionaryRegExp = new RegExp(dicName);
- listemunerateValues = [];
- if (dictionaryRegExp.test(dictionaryNameList)) {
- for (p=0; p < dictionaryList.length; p += 1) {
- if (dicName == dictionaryList[p].name) {
- listemunerateValues.push(dictionaryList[p].value);
- }
- }
- }
- return listemunerateValues;
+ var dicName = attribute;
+ if(attribute){
+ if(attribute.includes(":")){
+ dicName = attribute.split(":")[0];
+ }
+ }
+ var dictionaryRegExp = new RegExp(dicName);
+ listemunerateValues = [];
+ if (dictionaryRegExp.test(dictionaryNameList)) {
+ for (p=0; p < dictionaryList.length; p += 1) {
+ if (dicName == dictionaryList[p].name) {
+ listemunerateValues.push(dictionaryList[p].value);
+ }
+ }
+ }
+ return listemunerateValues;
}
function getList(attribute) {
- var enumName = attribute;
- console.log("In getList: attribute => " + attribute);
- if(attribute){
- if(attribute.includes(":")){
- enumName = attribute.split(":")[0];
- }
- }
+ var enumName = attribute;
+ if(attribute){
+ if(attribute.includes(":")){
+ enumName = attribute.split(":")[0];
+ }
+ }
var baseEnum = $scope.optimizationModelData.enumValues;
var enumList = [];
if(baseEnum != null){
- enumList = baseEnum.split(splitEnum);
+ enumList = baseEnum.split(splitEnum);
}
- var enumAttributes;
- var patternTest = new RegExp(enumName);
- for (k=0; k < enumList.length; k += 1){
- if(patternTest.test(enumList[k]) == true){
- enumAttributes = enumList[k].trim();
- }
- }
+ var enumAttributes;
+ var patternTest = new RegExp(enumName);
+ for (k=0; k < enumList.length; k += 1){
+ if(patternTest.test(enumList[k]) == true){
+ enumAttributes = enumList[k].trim();
+ }
+ }
- if(enumAttributes){
- enumAttributes = enumAttributes.replace("[", "");
- enumAttributes = enumAttributes.replace("]", "");
- enumAttributes = enumAttributes.replace(/ /g, '');
- var dropListAfterCommaSplit = enumAttributes.split(splitEqual);
- listemunerateValues = dropListAfterCommaSplit[1].split(splitComma);
- return listemunerateValues;
- }
+ if(enumAttributes){
+ enumAttributes = enumAttributes.replace("[", "");
+ enumAttributes = enumAttributes.replace("]", "");
+ enumAttributes = enumAttributes.replace(/ /g, '');
+ var dropListAfterCommaSplit = enumAttributes.split(splitEqual);
+ listemunerateValues = dropListAfterCommaSplit[1].split(splitComma);
+ return listemunerateValues;
+ }
return [];
}
-
+
function getBooleanList(){
- var booleanList = [];
- booleanList.push(true);
- booleanList.push(false);
- return booleanList;
+ var booleanList = [];
+ booleanList.push(true);
+ booleanList.push(false);
+ return booleanList;
}
function isArray(arrayTest) {
return Object.prototype.toString.call(arrayTest) === '[object Array]';
}
-
- var lableList = [];
-
+
+ var lableList = [];
+
$scope.layOutElementList = [];
$scope.layOutOnlyLableList = [];
var elementOrderNum = 0;
-
- function deconstructJSON(layOutData, level , name) {
+
+ function deconstructJSON(layOutData, level , name) {
- var array = false;
- var label = level;
- var stringValue = "java.lang.String";
- var string = "string";
- var intValue = "int";
- var integerValue = "integer";
- var double = "double";
- var boolean = "boolean";
- var baseLevel = level;
- var list = "list";
- var String = "String";
-
- var attributekey = "";
-
- if (name.length > 1){
- label = label + name + '.';
- }
-
- for (key in layOutData) {
- array = isArray(layOutData[key]);
- console.log("key: " + key , "value: " + layOutData[key]);
-
- if (!!layOutData[key] && typeof(layOutData[key])=="object") {
-
- if (array==false && key!=="0"){
-
- if($scope.dataOrderInfo){
- var labelObject = {"label" : key, "level" : label, "array" : array};
- //save it to the list
- $scope.layOutOnlyLableList.push(labelObject);
-
- }else {
- //call label layout
- $scope.labelLayout(label, key, array );
- }
-
- }
-
- if (array == true && key!=0){
- lableList.push(key);
- }
-
- if (lableList.length > 0){
- array = true;
- }
- if ( key==="0"){
- var newKey = lableList.pop();
-
- if($scope.dataOrderInfo){
-
- var labelObject = {"label" : newKey, "level" : baseLevel, "array" : array};
- //save it to the list
- $scope.layOutOnlyLableList.push(labelObject);
-
- }else {
- //call label layout
- $scope.labelLayout(baseLevel, newKey, array );
- }
-
- if (array){
- label = baseLevel + newKey + '@0.';
- } else {
- label = baseLevel + newKey + '.';
- }
- }
- deconstructJSON(layOutData[key] , label, key);
- } else {
- var attirbuteLabel = label;
- var defaultValue='';
- var isRequired = false;
- if (layOutData[key].includes('defaultValue-')){
- defaultValue = layOutData[key].split('defaultValue-')[1];
- }
+ var array = false;
+ var label = level;
+ var stringValue = "java.lang.String";
+ var string = "string";
+ var intValue = "int";
+ var integerValue = "integer";
+ var double = "double";
+ var boolean = "boolean";
+ var baseLevel = level;
+ var list = "list";
+ var String = "String";
+
+ var attributekey = "";
+
+ if (name.length > 1){
+ label = label + name + '.';
+ }
+
+ for (key in layOutData) {
+ array = isArray(layOutData[key]);
+
+ if (!!layOutData[key] && typeof(layOutData[key])=="object") {
+
+ if (array==false && key!=="0"){
+
+ if($scope.dataOrderInfo){
+ var labelObject = {"label" : key, "level" : label, "array" : array};
+ //save it to the list
+ $scope.layOutOnlyLableList.push(labelObject);
+
+ }else {
+ //call label layout
+ $scope.labelLayout(label, key, array );
+ }
+
+ }
+
+ if (array == true && key!=0){
+ lableList.push(key);
+ }
+
+ if (lableList.length > 0){
+ array = true;
+ }
+ if ( key==="0"){
+ var newKey = lableList.pop();
+
+ if($scope.dataOrderInfo){
+
+ var labelObject = {"label" : newKey, "level" : baseLevel, "array" : array};
+ //save it to the list
+ $scope.layOutOnlyLableList.push(labelObject);
+
+ }else {
+ //call label layout
+ $scope.labelLayout(baseLevel, newKey, array );
+ }
+
+ if (array){
+ label = baseLevel + newKey + '@0.';
+ } else {
+ label = baseLevel + newKey + '.';
+ }
+ }
+ deconstructJSON(layOutData[key] , label, key);
+ } else {
+ var attirbuteLabel = label;
+ var defaultValue='';
+ var isRequired = false;
+ if (layOutData[key].includes('defaultValue-')){
+ defaultValue = layOutData[key].split('defaultValue-')[1];
+ }
- if (key==="0"){
- array = true;
- attributekey = lableList.pop();
- attirbuteLabel = baseLevel;
- } else {
- attributekey = key.split();
- }
-
- if (layOutData[key].includes('required-true')){
- isRequired = true;
- }
-
- var subAttributes = $scope.optimizationModelData.sub_attributes;
-
- if(subAttributes){
- var jsonObject = JSON.parse(subAttributes);
- var allkeys = Object.keys(jsonObject);
- if(allkeys){
- for (var k = 0; k < allkeys.length; k++) {
- var keyValue = allkeys[k];
- console.log(" keyValue:jsonObject["+keyValue+ "]: " + jsonObject[keyValue]);
- if(jsonObject[keyValue]){
- var tempObject = jsonObject[keyValue];
- if(tempObject && tempObject[key]){
- if (tempObject[key].includes('required-true')){
- isRequired = true;
- }
- }
- }
- }
- }
- }
-
- var elementObject = {};
- switch (layOutData[key].split(splitcolon)[0]){
-
- case stringValue:
- case string:
- if($scope.dataOrderInfo){
- elementOrderNum++;
- elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue, "isRequired": isRequired, "type":"text"};
- $scope.layOutElementList.push(elementObject);
- }else{
- $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
- }
- break;
- case intValue:
- case integerValue:
- if($scope.dataOrderInfo){
- elementOrderNum++;
- elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"number"};
- $scope.layOutElementList.push(elementObject);
- }else{
- $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "number");
- }
- break;
- case double:
- if($scope.dataOrderInfo){
- elementOrderNum++;
- elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"double"};
- $scope.layOutElementList.push(elementObject);
- }else{
- $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "double");
- }
- break;
- case boolean:
- if($scope.dataOrderInfo){
- elementOrderNum++;
- elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": layOutData[key], "list": getBooleanList, "isRequired": isRequired, "type":"dropBox"};
- $scope.layOutElementList.push(elementObject);
- }else{
- $scope.dropBoxLayout(attirbuteLabel, attributekey, array, layOutData[key], getBooleanList());
- }
- break;
- default:
- if (layOutData[key].includes('dictionary-')){
- var list = getDictionary(layOutData[key].split('dictionary-')[1]);
- }else{
- //--- get dropdown values from enumValues
- var list = getList(layOutData[key]);
- }
- if (list.length===0){ //not dropdown element
- if($scope.dataOrderInfo){
- elementOrderNum++;
- elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"text"};
- $scope.layOutElementList.push(elementObject);
-
- }else{
- $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
- }
- }else{
- if($scope.dataOrderInfo){
- elementOrderNum++;
- elementObject = {"id": elementOrderNum, "attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": layOutData[key],"isRequired": isRequired, "list":list, "type":"dropBox"};
- $scope.layOutElementList.push(elementObject);
- }else{
- $scope.dropBoxLayout(attirbuteLabel, attributekey, array, layOutData[key], list, isRequired);
- }
- }
- break;
- }
- }
- }
- }
+ if (key==="0"){
+ array = true;
+ attributekey = lableList.pop();
+ attirbuteLabel = baseLevel;
+ } else {
+ attributekey = key.split();
+ }
+
+ if (layOutData[key].includes('required-true')){
+ isRequired = true;
+ }
+
+ var subAttributes = $scope.optimizationModelData.sub_attributes;
+
+ if(subAttributes){
+ var jsonObject = JSON.parse(subAttributes);
+ var allkeys = Object.keys(jsonObject);
+ if(allkeys){
+ for (var k = 0; k < allkeys.length; k++) {
+ var keyValue = allkeys[k];
+ if(jsonObject[keyValue]){
+ var tempObject = jsonObject[keyValue];
+ if(tempObject && tempObject[key]){
+ if (tempObject[key].includes('required-true')){
+ isRequired = true;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ var elementObject = {};
+ switch (layOutData[key].split(splitcolon)[0]){
+
+ case stringValue:
+ case string:
+ if($scope.dataOrderInfo){
+ elementOrderNum++;
+ elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue, "isRequired": isRequired, "type":"text"};
+ $scope.layOutElementList.push(elementObject);
+ }else{
+ $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
+ }
+ break;
+ case intValue:
+ case integerValue:
+ if($scope.dataOrderInfo){
+ elementOrderNum++;
+ elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"number"};
+ $scope.layOutElementList.push(elementObject);
+ }else{
+ $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "number");
+ }
+ break;
+ case double:
+ if($scope.dataOrderInfo){
+ elementOrderNum++;
+ elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"double"};
+ $scope.layOutElementList.push(elementObject);
+ }else{
+ $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "double");
+ }
+ break;
+ case boolean:
+ if($scope.dataOrderInfo){
+ elementOrderNum++;
+ elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": layOutData[key], "list": getBooleanList, "isRequired": isRequired, "type":"dropBox"};
+ $scope.layOutElementList.push(elementObject);
+ }else{
+ $scope.dropBoxLayout(attirbuteLabel, attributekey, array, layOutData[key], getBooleanList());
+ }
+ break;
+ default:
+ if (layOutData[key].includes('dictionary-')){
+ var list = getDictionary(layOutData[key].split('dictionary-')[1]);
+ }else{
+ //--- get dropdown values from enumValues
+ var list = getList(layOutData[key]);
+ }
+ if (list.length===0){ //not dropdown element
+ if($scope.dataOrderInfo){
+ elementOrderNum++;
+ elementObject = {"id": elementOrderNum,"attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": defaultValue,"isRequired": isRequired, "type":"text"};
+ $scope.layOutElementList.push(elementObject);
+
+ }else{
+ $scope.attributeBox(attributekey, array, attirbuteLabel, defaultValue, isRequired, "text");
+ }
+ }else{
+ if($scope.dataOrderInfo){
+ elementOrderNum++;
+ elementObject = {"id": elementOrderNum, "attributekey" : attributekey, "array": array, "attirbuteLabel" : attirbuteLabel, "defaultValue": layOutData[key],"isRequired": isRequired, "list":list, "type":"dropBox"};
+ $scope.layOutElementList.push(elementObject);
+ }else{
+ $scope.dropBoxLayout(attirbuteLabel, attributekey, array, layOutData[key], list, isRequired);
+ }
+ }
+ break;
+ }
+ }
+ }
+ }
$scope.validContionalRequired = function(parentId) {
- console.log("ng-blur event: parentId : " + parentId);
var c = document.getElementById(parentId).children;
var i;
var hasValue = false;
for (i = 0; i < c.length; i++) {
- if(c[i].getAttribute("data-conditional")){
- console.log(c[i].getAttribute("data-conditional"));
- console.log(c[i].value);
- if(c[i].value != null && c[i].value.trim() != ""){
- hasValue = true;
- }
- }
+ if(c[i].getAttribute("data-conditional")){
+ if(c[i].value != null && c[i].value.trim() != ""){
+ hasValue = true;
+ }
+ }
}
- for (i = 0; i < c.length; i++) {
- if(c[i].getAttribute("data-conditional")){
- if(hasValue){
- c[i].setAttribute("required", true);
- }else{
- c[i].removeAttribute("required");
- }
- }
- }
+ for (i = 0; i < c.length; i++) {
+ if(c[i].getAttribute("data-conditional")){
+ if(hasValue){
+ c[i].setAttribute("required", true);
+ }else{
+ c[i].removeAttribute("required");
+ }
+ }
+ }
}
-
+
$scope.jsonLayout = function(layOutData){
-
+
deconstructJSON(layOutData , "", "");
-
- var orderValue = $scope.dataOrderInfo;
- var layOutElementList = $scope.layOutElementList;
- var labelList = $scope.layOutOnlyLableList;
-
- //reset to default
- elementOrderNum = 0;
- $scope.layOutElementList = [];
- $scope.layOutOnlyLableList = [];
-
- // Only layout in order if order info provided
- if(orderValue){
-
- if(orderValue.includes("[")){
- orderValue = orderValue.replace("[", "") ;
- orderValue = orderValue.replace("]", "") ;
- }
-
- orderValue = orderValue.split(',') ;
-
- for (i = 0; i < orderValue.length; i++) {
- console.log("orderValue["+i+"]"+ orderValue[i]);
- var key = orderValue[i].trim();
-
- //--- Create labels first {"label" : newKey, "level" : baseLevel, "array" : array};
- if(labelList){
- for (k = 0; k < labelList.length; k++){
-
- var label = labelList[k].label.toString().trim();
- var level = labelList[k].level.toString().trim();
- var array = labelList[k].array;
-
- if(key == label){
- $scope.labelLayout(level, label, array);
- //in case to have duplicate label names
- labelList[k].label = "*processed*";
- break;
- }
- }
- }
- //--- then layout each element based on its order defined in YAML file
- for (j = 0; j < layOutElementList.length; j++) {
-
- var attributekey = layOutElementList[j].attributekey.toString().trim();
-
- if(key == attributekey){
-
- var attirbuteLabel = layOutElementList[j].attirbuteLabel.toString().trim();
- var defaultValue = layOutElementList[j].defaultValue.toString().trim();
- var isRequired = layOutElementList[j].isRequired;
-
- console.log("layOutElementList[" +j+ "]: id:" + layOutElementList[j].id + ", attributekey:"+ layOutElementList[j].attributekey + ", attirbuteLabel:" + layOutElementList[j].attirbuteLabel);
-
- if (layOutElementList[j].type == "dropBox"){
- $scope.dropBoxLayout(attirbuteLabel, attributekey, layOutElementList[j].array, defaultValue, layOutElementList[j].list, isRequired);
-
- }else{
- $scope.attributeBox(attributekey, layOutElementList[j].array, attirbuteLabel, defaultValue, isRequired, layOutElementList[j].type);
-
- }
-
- //in case to have duplicate attribute names
- layOutElementList[j].attributekey = "*processed*";
- break;
- }
-
- }
-
- }
- }
+
+ var orderValue = $scope.dataOrderInfo;
+ var layOutElementList = $scope.layOutElementList;
+ var labelList = $scope.layOutOnlyLableList;
+
+ //reset to default
+ elementOrderNum = 0;
+ $scope.layOutElementList = [];
+ $scope.layOutOnlyLableList = [];
+
+ // Only layout in order if order info provided
+ if(orderValue){
+
+ if(orderValue.includes("[")){
+ orderValue = orderValue.replace("[", "") ;
+ orderValue = orderValue.replace("]", "") ;
+ }
+
+ orderValue = orderValue.split(',') ;
+
+ for (i = 0; i < orderValue.length; i++) {
+ var key = orderValue[i].trim();
+
+ //--- Create labels first {"label" : newKey, "level" : baseLevel, "array" : array};
+ if(labelList){
+ for (k = 0; k < labelList.length; k++){
+
+ var label = labelList[k].label.toString().trim();
+ var level = labelList[k].level.toString().trim();
+ var array = labelList[k].array;
+
+ if(key == label){
+ $scope.labelLayout(level, label, array);
+ //in case to have duplicate label names
+ labelList[k].label = "*processed*";
+ break;
+ }
+ }
+ }
+ //--- then layout each element based on its order defined in YAML file
+ for (j = 0; j < layOutElementList.length; j++) {
+
+ var attributekey = layOutElementList[j].attributekey.toString().trim();
+
+ if(key == attributekey){
+
+ var attirbuteLabel = layOutElementList[j].attirbuteLabel.toString().trim();
+ var defaultValue = layOutElementList[j].defaultValue.toString().trim();
+ var isRequired = layOutElementList[j].isRequired;
+
+
+ if (layOutElementList[j].type == "dropBox"){
+ $scope.dropBoxLayout(attirbuteLabel, attributekey, layOutElementList[j].array, defaultValue, layOutElementList[j].list, isRequired);
+
+ }else{
+ $scope.attributeBox(attributekey, layOutElementList[j].array, attirbuteLabel, defaultValue, isRequired, layOutElementList[j].type);
+
+ }
+
+ //in case to have duplicate attribute names
+ layOutElementList[j].attributekey = "*processed*";
+ break;
+ }
+
+ }
+
+ }
+ }
}
$scope.attributeBox = function(attibuteKey, attributeManyKey, labelValue, defaultValue, isRequired, dataType ){
- $scope.temp.policy.ruleGridData.push(attibuteKey);
- var br = document.createElement("BR");
-
- var label = document.createElement("Label");
- var labeltext = null;
- var requiredLabName = "";
- if (matching.includes(attibuteKey)){
- labeltext = document.createTextNode(attibuteKey + "*!");
- isRequired = true; //set required as true for matching element
- }else {
- if(isRequired){
- requiredLabName = attibuteKey + " * ";
- labeltext = document.createTextNode(requiredLabName);
- }else{
- labeltext = document.createTextNode(attibuteKey);
- }
- }
+ $scope.temp.policy.ruleGridData.push(attibuteKey);
+ var br = document.createElement("BR");
+
+ var label = document.createElement("Label");
+ var labeltext = null;
+ var requiredLabName = "";
+ if (matching.includes(attibuteKey)){
+ labeltext = document.createTextNode(attibuteKey + "*!");
+ isRequired = true; //set required as true for matching element
+ }else {
+ if(isRequired){
+ requiredLabName = attibuteKey + " * ";
+ labeltext = document.createTextNode(requiredLabName);
+ }else{
+ labeltext = document.createTextNode(attibuteKey);
+ }
+ }
-
- var divID = labelValue;
-
- if (labelValue.length < 1){
- divID = "DynamicTemplate";
- }else if (labelValue.endsWith('.')){
- var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
- }
-
- label.appendChild(labeltext);
-
- var textField = document.createElement("INPUT");
-
- textField.setAttribute("class" , "form-control");
- if(dataType){
- if(dataType == "double"){
- textField.setAttribute("type" , "number");
- textField.setAttribute("step" , "any");
- }else{
- textField.setAttribute("type" , dataType);
- }
- }
- textField.setAttribute("style" , "width:300px;");
- textField.setAttribute("ng-disabled" , "temp.policy.readOnly");
- var checkKey;
- var id = "";
- if(attributeManyKey){
- checkKey = labelValue + attibuteKey+'@0';
- textField.setAttribute("id" , ''+labelValue + attibuteKey+'@0'+'');
- var divTag = document.createElement("div");
- divTag.setAttribute("id", "div."+ labelValue +attibuteKey);
- var addButton = document.createElement("BUTTON");
- var buttonaddLabel = document.createTextNode("+");
- addButton.appendChild(buttonaddLabel);
- addButton.setAttribute("id", labelValue + attibuteKey);
- addButton.setAttribute("class", "btn btn-add-remove");
- addButton.setAttribute("ng-click" , 'addNewChoice("'+labelValue + attibuteKey+'");');
- addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
- var removeButton = document.createElement("BUTTON");
- var buttonremoveLabel = document.createTextNode("-");
- removeButton.appendChild(buttonremoveLabel);
- removeButton.setAttribute("class", "btn btn-add-remove");
- removeButton.setAttribute("ng-click" , 'removeChoice("'+labelValue + attibuteKey+'");');
- removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
- document.getElementById(divID).appendChild(addButton);
- document.getElementById(divID).appendChild(removeButton);
- document.getElementById(divID).appendChild(label);
- id = "div."+labelValue+attibuteKey;
- divTag.setAttribute("id", id);
- document.getElementById(divID).appendChild(divTag);
- textField.className += ' first_child';
- if(isRequired){
- textField.setAttribute("required", "true");
- }
- divTag.appendChild(textField);
- document.getElementById(divID).appendChild(divTag);
-
- }else{
- checkKey = labelValue + attibuteKey;
- textField.setAttribute("id" , ''+labelValue +attibuteKey+'');
- if(document.getElementById(divID).hasAttribute('required') || !document.getElementById(divID).hasAttribute('data-conditional')){
- if(requiredLabName.includes("*") || isRequired){
- textField.setAttribute("required", "true");
- }
- }else if (document.getElementById(divID).hasAttribute('data-conditional')){
- if(requiredLabName.includes("*")){
- var requiredNode = document.createElement('span');
- requiredNode.setAttribute("class", "mstooltip");
- requiredNode.textContent = "?";
- label.appendChild(requiredNode);
-
- var requiredNodeToolTip = document.createElement('span');
- requiredNodeToolTip.setAttribute("class", "tooltiptext");
- requiredNodeToolTip.textContent = "Conditional Required";
- requiredNode.appendChild(requiredNodeToolTip);
-
- textField.setAttribute("data-conditional", divID);
- textField.setAttribute("ng-blur", "validContionalRequired('"+divID+"')");
- }
- }
-
- document.getElementById(divID).appendChild(label);
- document.getElementById(divID).appendChild(textField);
- document.getElementById(divID).appendChild(br);
-
- }
+
+ var divID = labelValue;
+
+ if (labelValue.length < 1){
+ divID = "DynamicTemplate";
+ }else if (labelValue.endsWith('.')){
+ var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
+ }
+
+ label.appendChild(labeltext);
+
+ var textField = document.createElement("INPUT");
+
+ textField.setAttribute("class" , "form-control");
+ if(dataType){
+ if(dataType == "double"){
+ textField.setAttribute("type" , "number");
+ textField.setAttribute("step" , "any");
+ }else{
+ textField.setAttribute("type" , dataType);
+ }
+ }
+ textField.setAttribute("style" , "width:300px;");
+ textField.setAttribute("ng-disabled" , "temp.policy.readOnly");
+ var checkKey;
+ var id = "";
+ if(attributeManyKey){
+ checkKey = labelValue + attibuteKey+'@0';
+ textField.setAttribute("id" , ''+labelValue + attibuteKey+'@0'+'');
+ var divTag = document.createElement("div");
+ divTag.setAttribute("id", "div."+ labelValue +attibuteKey);
+ var addButton = document.createElement("BUTTON");
+ var buttonaddLabel = document.createTextNode("+");
+ addButton.appendChild(buttonaddLabel);
+ addButton.setAttribute("id", labelValue + attibuteKey);
+ addButton.setAttribute("class", "btn btn-add-remove");
+ addButton.setAttribute("ng-click" , 'addNewChoice("'+labelValue + attibuteKey+'");');
+ addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
+ var removeButton = document.createElement("BUTTON");
+ var buttonremoveLabel = document.createTextNode("-");
+ removeButton.appendChild(buttonremoveLabel);
+ removeButton.setAttribute("class", "btn btn-add-remove");
+ removeButton.setAttribute("ng-click" , 'removeChoice("'+labelValue + attibuteKey+'");');
+ removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
+ document.getElementById(divID).appendChild(addButton);
+ document.getElementById(divID).appendChild(removeButton);
+ document.getElementById(divID).appendChild(label);
+ id = "div."+labelValue+attibuteKey;
+ divTag.setAttribute("id", id);
+ document.getElementById(divID).appendChild(divTag);
+ textField.className += ' first_child';
+ if(isRequired){
+ textField.setAttribute("required", "true");
+ }
+ divTag.appendChild(textField);
+ document.getElementById(divID).appendChild(divTag);
+
+ }else{
+ checkKey = labelValue + attibuteKey;
+ textField.setAttribute("id" , ''+labelValue +attibuteKey+'');
+ if(document.getElementById(divID).hasAttribute('required') || !document.getElementById(divID).hasAttribute('data-conditional')){
+ if(requiredLabName.includes("*") || isRequired){
+ textField.setAttribute("required", "true");
+ }
+ }else if (document.getElementById(divID).hasAttribute('data-conditional')){
+ if(requiredLabName.includes("*")){
+ var requiredNode = document.createElement('span');
+ requiredNode.setAttribute("class", "mstooltip");
+ requiredNode.textContent = "?";
+ label.appendChild(requiredNode);
+
+ var requiredNodeToolTip = document.createElement('span');
+ requiredNodeToolTip.setAttribute("class", "tooltiptext");
+ requiredNodeToolTip.textContent = "Conditional Required";
+ requiredNode.appendChild(requiredNodeToolTip);
+
+ textField.setAttribute("data-conditional", divID);
+ textField.setAttribute("ng-blur", "validContionalRequired('"+divID+"')");
+ }
+ }
+
+ document.getElementById(divID).appendChild(label);
+ document.getElementById(divID).appendChild(textField);
+ document.getElementById(divID).appendChild(br);
+
+ }
- if(divID.includes("@0") && divID.includes("div.")){
- var firstChild_Id = divID.split("@0")[0];
- var firstChild_element = document.getElementById(firstChild_Id);
- if(firstChild_element){
- firstChild_element.className += ' children_group'; //here is a div with a group of children.
- }
- }
- console.log('firstChild_Id: ' + firstChild_Id);
- console.log('divID: ' + divID);
-
- if (defaultValue.length > 0){
- if(defaultValue.includes(":")){
- defaultValue = defaultValue.split(":")[0];
- if(defaultValue === "NA") {
- defaultValue = "";
- }
- }
- if(defaultValue != "undefined" && defaultValue != undefined && defaultValue != "null"){
- document.getElementById(checkKey).value = defaultValue;
- }
- }
-
- if($scope.temp.policy.ruleData != null){
- if (attributeManyKey){
- var newCheckKey = checkKey.replace(attibuteKey + '@0',attibuteKey);
- if($scope.temp.policy.ruleData[newCheckKey +'@0'] != undefined && $scope.temp.policy.ruleData[newCheckKey +'@0'] != "undefined"){
- document.getElementById(newCheckKey +'@0').value = $scope.temp.policy.ruleData[newCheckKey +'@0'];
- }
- }else{
- if($scope.temp.policy.ruleData[checkKey] != undefined && $scope.temp.policy.ruleData[checkKey] != "undefined"){
- document.getElementById(checkKey).value = $scope.temp.policy.ruleData[checkKey];
- }
- }
- }
- plainAttributeKeys.push(labelValue + attibuteKey+'*'+attributeManyKey);
+ if(divID.includes("@0") && divID.includes("div.")){
+ var firstChild_Id = divID.split("@0")[0];
+ var firstChild_element = document.getElementById(firstChild_Id);
+ if(firstChild_element){
+ firstChild_element.className += ' children_group'; //here is a div with a group of children.
+ }
+ }
+
+ if (defaultValue.length > 0){
+ if(defaultValue.includes(":")){
+ defaultValue = defaultValue.split(":")[0];
+ if(defaultValue === "NA") {
+ defaultValue = "";
+ }
+ }
+ if(defaultValue != "undefined" && defaultValue != undefined && defaultValue != "null"){
+ document.getElementById(checkKey).value = defaultValue;
+ }
+ }
+
+ if($scope.temp.policy.ruleData != null){
+ if (attributeManyKey){
+ var newCheckKey = checkKey.replace(attibuteKey + '@0',attibuteKey);
+ if($scope.temp.policy.ruleData[newCheckKey +'@0'] != undefined && $scope.temp.policy.ruleData[newCheckKey +'@0'] != "undefined"){
+ document.getElementById(newCheckKey +'@0').value = $scope.temp.policy.ruleData[newCheckKey +'@0'];
+ }
+ }else{
+ if($scope.temp.policy.ruleData[checkKey] != undefined && $scope.temp.policy.ruleData[checkKey] != "undefined"){
+ document.getElementById(checkKey).value = $scope.temp.policy.ruleData[checkKey];
+ }
+ }
+ }
+ plainAttributeKeys.push(labelValue + attibuteKey+'*'+attributeManyKey);
};
$scope.labelManyKeys = [];
$scope.labelLayout = function(labelValue, lableName, labelManyKey ){
- var label = document.createElement("Label")
- var divID = labelValue;
- if (labelValue.endsWith('.')){
- var workingLabel = labelValue.substring(0, labelValue.length-1);
- }else {
- var workingLabel = labelValue;
- }
-
- if (labelValue.length < 1){
- divID = "DynamicTemplate";
- } else if (labelValue.endsWith('.')){
- var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
- }
-
- var subAttributes = $scope.optimizationModelData.subattributes;
- var jsonObject = JSON.parse(subAttributes);
- var lablInfo = findVal(jsonObject, lableName);
- console.log("findValue : " + lableName +": "+ lablInfo);
- var star = "";
- var required = null;
- if(lablInfo){
- if(lablInfo.includes("required-true")){
- star = " *";
- required = true;
- }else if (lablInfo.includes("required-false")){
- required = false
- }
- }
-
- var labeltext = document.createTextNode(lableName + star);
-
- label.appendChild(labeltext);
+ var label = document.createElement("Label")
+ var divID = labelValue;
+ if (labelValue.endsWith('.')){
+ var workingLabel = labelValue.substring(0, labelValue.length-1);
+ }else {
+ var workingLabel = labelValue;
+ }
+
+ if (labelValue.length < 1){
+ divID = "DynamicTemplate";
+ } else if (labelValue.endsWith('.')){
+ var divID = 'div.'+ labelValue.substring(0, labelValue.length-1);
+ }
+
+ var subAttributes = $scope.optimizationModelData.subattributes;
+ var jsonObject = JSON.parse(subAttributes);
+ var lablInfo = findVal(jsonObject, lableName);
+ var star = "";
+ var required = null;
+ if(lablInfo){
+ if(lablInfo.includes("required-true")){
+ star = " *";
+ required = true;
+ }else if (lablInfo.includes("required-false")){
+ required = false
+ }
+ }
+
+ var labeltext = document.createTextNode(lableName + star);
+
+ label.appendChild(labeltext);
- if(labelManyKey){
- var addButton = document.createElement("BUTTON");
- var buttonLabel = document.createTextNode("+");
- addButton.appendChild(buttonLabel);
- addButton.setAttribute("class", "btn btn-add-remove");
- addButton.setAttribute("ng-click" , 'addNewChoice("'+labelValue + lableName+'");');
- addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
- var removeButton = document.createElement("BUTTON");
- var buttonremoveLabel = document.createTextNode("-");
- removeButton.appendChild(buttonremoveLabel);
- removeButton.setAttribute("class", "btn btn-add-remove");
- removeButton.setAttribute("ng-click" , 'removeChoice("'+labelValue +lableName+'");');
- removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
- document.getElementById(divID).appendChild(addButton);
- document.getElementById(divID).appendChild(removeButton);
- document.getElementById(divID).appendChild(label);
- var id = "div."+labelValue+lableName;
- var divTag = document.createElement("div");
- divTag.setAttribute("id", id);
- document.getElementById(divID).appendChild(divTag);
-
- var divTag = document.createElement("div");
- divTag.setAttribute("id", id +'@0');
-
- divTag.className += ' children_group'; //here is div with a group of children.
-
- if(required){
- divTag.setAttribute("required", required);
- }else if(required == false){
- divTag.setAttribute("data-conditional", "yes");
- }
-
- document.getElementById(id).appendChild(divTag);
-
- $scope.labelManyKeys.push(lableName);
-
- }else{
- var divTag = document.createElement("div");
- divTag.setAttribute("id", "div."+labelValue+lableName);
- divTag.className += ' children_group'; //here is div with a group of children.
- if(required){
- divTag.setAttribute("required", required);
- }else if(required == false){
- divTag.setAttribute("data-conditional", "yes");
- }
- document.getElementById(divID).appendChild(label);
- document.getElementById(divID).appendChild(divTag);
- }
+ if(labelManyKey){
+ var addButton = document.createElement("BUTTON");
+ var buttonLabel = document.createTextNode("+");
+ addButton.appendChild(buttonLabel);
+ addButton.setAttribute("class", "btn btn-add-remove");
+ addButton.setAttribute("ng-click" , 'addNewChoice("'+labelValue + lableName+'");');
+ addButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
+ var removeButton = document.createElement("BUTTON");
+ var buttonremoveLabel = document.createTextNode("-");
+ removeButton.appendChild(buttonremoveLabel);
+ removeButton.setAttribute("class", "btn btn-add-remove");
+ removeButton.setAttribute("ng-click" , 'removeChoice("'+labelValue +lableName+'");');
+ removeButton.setAttribute("ng-disabled" , "temp.policy.readOnly");
+ document.getElementById(divID).appendChild(addButton);
+ document.getElementById(divID).appendChild(removeButton);
+ document.getElementById(divID).appendChild(label);
+ var id = "div."+labelValue+lableName;
+ var divTag = document.createElement("div");
+ divTag.setAttribute("id", id);
+ document.getElementById(divID).appendChild(divTag);
+
+ var divTag = document.createElement("div");
+ divTag.setAttribute("id", id +'@0');
+
+ divTag.className += ' children_group'; //here is div with a group of children.
+
+ if(required){
+ divTag.setAttribute("required", required);
+ }else if(required == false){
+ divTag.setAttribute("data-conditional", "yes");
+ }
+
+ document.getElementById(id).appendChild(divTag);
+
+ $scope.labelManyKeys.push(lableName);
+
+ }else{
+ var divTag = document.createElement("div");
+ divTag.setAttribute("id", "div."+labelValue+lableName);
+ divTag.className += ' children_group'; //here is div with a group of children.
+ if(required){
+ divTag.setAttribute("required", required);
+ }else if(required == false){
+ divTag.setAttribute("data-conditional", "yes");
+ }
+ document.getElementById(divID).appendChild(label);
+ document.getElementById(divID).appendChild(divTag);
+ }
};
$scope.dropBoxLayout = function(labelLevel, attributeName, many , refValue, listemunerateValues, isRequired){
- var br = document.createElement("BR");
-
- if (labelLevel.length < 1){
- var divID = "DynamicTemplate";
- } else if (labelLevel.endsWith('.')){
- var divID = 'div.'+ labelLevel.substring(0, labelLevel.length-1);
- }
-
-
- var label = document.createElement("Label")
-
- var refAttributes = $scope.optimizationModelData.ref_attributes;
- if(isRequired != true && refAttributes){ //check refAttributes also
- var refAttributesList = refAttributes.split(splitComma);
- for (k = 0; k < refAttributesList.length; k++){
- var refAttribute = refAttributesList[k].split(splitEqual);
- if (attributeName == refAttribute[0].trim() && refAttribute[1].includes("required-true")){
- isRequired = true;
- }
- }
- }
-
- if (matching.includes(attributeName)){
- var labeltext = document.createTextNode(attributeName + "*!");
- label.appendChild(labeltext);
- isRequired = true; //set required as true for matching element
- }else {
- var labeltext = document.createTextNode(attributeName);
- if(isRequired){
- var requiredLabName = attributeName+ " * ";
- labeltext = document.createTextNode(requiredLabName);
- }else{
- labeltext = document.createTextNode(attributeName);
- }
-
- label.appendChild(labeltext);
- }
- label.appendChild(labeltext);
- // if this field is required, but its parent is not required
- if(isRequired && document.getElementById(divID).hasAttribute('data-conditional')){
- var requiredNode = document.createElement('span');
- requiredNode.setAttribute("class", "mstooltip");
- requiredNode.textContent = "?";
- label.appendChild(requiredNode);
-
- var requiredNodeToolTip = document.createElement('span');
- requiredNodeToolTip.setAttribute("class", "tooltiptext");
- requiredNodeToolTip.textContent = "Conditional Required";
- requiredNode.appendChild(requiredNodeToolTip);
+ var br = document.createElement("BR");
+
+ if (labelLevel.length < 1){
+ var divID = "DynamicTemplate";
+ } else if (labelLevel.endsWith('.')){
+ var divID = 'div.'+ labelLevel.substring(0, labelLevel.length-1);
+ }
+
+
+ var label = document.createElement("Label")
+
+ var refAttributes = $scope.optimizationModelData.ref_attributes;
+ if(isRequired != true && refAttributes){ //check refAttributes also
+ var refAttributesList = refAttributes.split(splitComma);
+ for (k = 0; k < refAttributesList.length; k++){
+ var refAttribute = refAttributesList[k].split(splitEqual);
+ if (attributeName == refAttribute[0].trim() && refAttribute[1].includes("required-true")){
+ isRequired = true;
+ }
+ }
+ }
+
+ if (matching.includes(attributeName)){
+ var labeltext = document.createTextNode(attributeName + "*!");
+ label.appendChild(labeltext);
+ isRequired = true; //set required as true for matching element
+ }else {
+ var labeltext = document.createTextNode(attributeName);
+ if(isRequired){
+ var requiredLabName = attributeName+ " * ";
+ labeltext = document.createTextNode(requiredLabName);
+ }else{
+ labeltext = document.createTextNode(attributeName);
+ }
+
+ label.appendChild(labeltext);
+ }
+ label.appendChild(labeltext);
+ // if this field is required, but its parent is not required
+ if(isRequired && document.getElementById(divID).hasAttribute('data-conditional')){
+ var requiredNode = document.createElement('span');
+ requiredNode.setAttribute("class", "mstooltip");
+ requiredNode.textContent = "?";
+ label.appendChild(requiredNode);
+
+ var requiredNodeToolTip = document.createElement('span');
+ requiredNodeToolTip.setAttribute("class", "tooltiptext");
+ requiredNodeToolTip.textContent = "Conditional Required";
+ requiredNode.appendChild(requiredNodeToolTip);
- }
-
- var listField = document.createElement("SELECT");
- listField.setAttribute("class" , "form-control");
- listField.setAttribute("style" , "width:300px;");
- listField.setAttribute("ng-disabled" , "temp.policy.readOnly");
-
- if(isRequired){
- if(document.getElementById(divID).hasAttribute('data-conditional')){
- listField.setAttribute("data-conditional", divID);
- listField.setAttribute("ng-blur", "validContionalRequired('"+divID+"')");
- }else{
- listField.setAttribute("required", true);
- }
- }
- if( many != true || isRequired != true){ // add an empty option for not required or not multiple select element
- var optionFirst = document.createElement('option');
- optionFirst.setAttribute('value', "");
- listField.appendChild(optionFirst);
- }
-
- for (var i=0; i < listemunerateValues.length; i += 1) {
- if(typeof listemunerateValues[i] == "string" && listemunerateValues[i].includes("equal-sign")){
- listemunerateValues[i] = listemunerateValues[i].replace('equal-sign','=');
- }
- var option = document.createElement('option');
- option.setAttribute('value', listemunerateValues[i]);
- option.appendChild(document.createTextNode(listemunerateValues[i]));
- option.setAttribute('value', listemunerateValues[i]);
- listField.appendChild(option);
- }
- listField.setAttribute("id" , ''+ labelLevel + attributeName + '');
-
- enumKeyList.push(attributeName);
-
- document.getElementById(divID).appendChild(label);
- document.getElementById(divID).appendChild(br);
-
- if(many == true){
- document.getElementById(divID).appendChild(listField).multiple = true;
- plainAttributeKeys.push(labelLevel + attributeName+'*'+true);
- }else {
- document.getElementById(divID).appendChild(listField).multiple = false;
- plainAttributeKeys.push(labelLevel + attributeName+'*'+false);
- }
-
- if($scope.temp.policy.ruleData != null){
- if (many == true){
- document.getElementById(labelLevel +attributeName).options[0].selected = false;
- for (i=0; i < listemunerateValues.length; i += 1) {
- var testValue = $scope.temp.policy.ruleData[labelLevel +attributeName+'@' + i];
- if (testValue === undefined){
- testValue = $scope.temp.policy.ruleData[labelLevel +attributeName];
- }
- var location = listemunerateValues.indexOf(testValue);
- if (location!=-1){
- document.getElementById(labelLevel +attributeName).options[location].selected = true;
- }
- }
- }else {
- if($scope.temp.policy.ruleData[labelLevel + attributeName] != undefined && $scope.temp.policy.ruleData[labelLevel + attributeName] != "undefined"){
- document.getElementById(labelLevel + attributeName).value = $scope.temp.policy.ruleData[labelLevel + attributeName];
- }
- }
- }
- };
+ }
+
+ var listField = document.createElement("SELECT");
+ listField.setAttribute("class" , "form-control");
+ listField.setAttribute("style" , "width:300px;");
+ listField.setAttribute("ng-disabled" , "temp.policy.readOnly");
+
+ if(isRequired){
+ if(document.getElementById(divID).hasAttribute('data-conditional')){
+ listField.setAttribute("data-conditional", divID);
+ listField.setAttribute("ng-blur", "validContionalRequired('"+divID+"')");
+ }else{
+ listField.setAttribute("required", true);
+ }
+ }
+ if( many != true || isRequired != true){ // add an empty option for not required or not multiple select element
+ var optionFirst = document.createElement('option');
+ optionFirst.setAttribute('value', "");
+ listField.appendChild(optionFirst);
+ }
+
+ for (var i=0; i < listemunerateValues.length; i += 1) {
+ if(typeof listemunerateValues[i] == "string" && listemunerateValues[i].includes("equal-sign")){
+ listemunerateValues[i] = listemunerateValues[i].replace('equal-sign','=');
+ }
+ var option = document.createElement('option');
+ option.setAttribute('value', listemunerateValues[i]);
+ option.appendChild(document.createTextNode(listemunerateValues[i]));
+ option.setAttribute('value', listemunerateValues[i]);
+ listField.appendChild(option);
+ }
+ listField.setAttribute("id" , ''+ labelLevel + attributeName + '');
+
+ enumKeyList.push(attributeName);
+
+ document.getElementById(divID).appendChild(label);
+ document.getElementById(divID).appendChild(br);
+
+ if(many == true){
+ document.getElementById(divID).appendChild(listField).multiple = true;
+ plainAttributeKeys.push(labelLevel + attributeName+'*'+true);
+ }else {
+ document.getElementById(divID).appendChild(listField).multiple = false;
+ plainAttributeKeys.push(labelLevel + attributeName+'*'+false);
+ }
+
+ if($scope.temp.policy.ruleData != null){
+ if (many == true){
+ document.getElementById(labelLevel +attributeName).options[0].selected = false;
+ for (i=0; i < listemunerateValues.length; i += 1) {
+ var testValue = $scope.temp.policy.ruleData[labelLevel +attributeName+'@' + i];
+ if (testValue === undefined){
+ testValue = $scope.temp.policy.ruleData[labelLevel +attributeName];
+ }
+ var location = listemunerateValues.indexOf(testValue);
+ if (location!=-1){
+ document.getElementById(labelLevel +attributeName).options[location].selected = true;
+ }
+ }
+ }else {
+ if($scope.temp.policy.ruleData[labelLevel + attributeName] != undefined && $scope.temp.policy.ruleData[labelLevel + attributeName] != "undefined"){
+ document.getElementById(labelLevel + attributeName).value = $scope.temp.policy.ruleData[labelLevel + attributeName];
+ }
+ }
+ }
+ };
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
};
$scope.savePolicy = function(policy){
- if(policy.itemContent != undefined){
- $scope.refreshCheck = true;
- $scope.policyNavigator = policy.itemContent;
- policy.itemContent = "";
- }
- $scope.savebutton = false;
- var splitAt = '*';
- var dot ='.';
- var jsonPolicy = {};
- if(plainAttributeKeys != null){
- for(a = 0; a < plainAttributeKeys.length; a++){
- var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
- console.log("splitPlainAttributeKey: " + splitPlainAttributeKey);
- var searchElement = document.getElementById(splitPlainAttributeKey[0]);
- var key = splitPlainAttributeKey[0];
-
+ if(policy.itemContent != undefined){
+ $scope.refreshCheck = true;
+ $scope.policyNavigator = policy.itemContent;
+ policy.itemContent = "";
+ }
+ $scope.savebutton = false;
+ var splitAt = '*';
+ var dot ='.';
+ var jsonPolicy = {};
+ if(plainAttributeKeys != null){
+ for(a = 0; a < plainAttributeKeys.length; a++){
+ var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
+ var searchElement = document.getElementById(splitPlainAttributeKey[0]);
+ var key = splitPlainAttributeKey[0];
+
if(searchElement == null || searchElement.nodeName == 'BUTTON'){
searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
key = splitPlainAttributeKey[0]+'@0';
}
- if(searchElement != null){
- var keySplit = key.split(dot);
- var elumentLocation = keySplit.length;
- var enumKey = key;
- if (elumentLocation > 1){
- enumKey = keySplit[keySplit.length - 1];
- }
- //check it is undefined or not
- if (enumKeyList != undefined && enumKeyList.indexOf(enumKey) != -1){
- if (splitPlainAttributeKey[1]!= undefined && splitPlainAttributeKey[1].indexOf("true") !== -1){
- var multiSlect = [];
- for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
- multiSlect.push(searchElement.selectedOptions[i].value);
- }
- jsonPolicy[key]= multiSlect;
- }else{
- console.log(" searchElement.value = > " + searchElement.value);
- jsonPolicy[key]= searchElement.value;
- }
- } else {
- if(searchElement.value != null){
- console.log(" searchElement.value = > " + searchElement.value);
- jsonPolicy[key]= searchElement.value;
- }
- }
- }
- }
- }
+ if(searchElement != null){
+ var keySplit = key.split(dot);
+ var elumentLocation = keySplit.length;
+ var enumKey = key;
+ if (elumentLocation > 1){
+ enumKey = keySplit[keySplit.length - 1];
+ }
+ //check it is undefined or not
+ if (enumKeyList != undefined && enumKeyList.indexOf(enumKey) != -1){
+ if (splitPlainAttributeKey[1]!= undefined && splitPlainAttributeKey[1].indexOf("true") !== -1){
+ var multiSlect = [];
+ for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
+ multiSlect.push(searchElement.selectedOptions[i].value);
+ }
+ jsonPolicy[key]= multiSlect;
+ }else{
+ jsonPolicy[key]= searchElement.value;
+ }
+ } else {
+ if(searchElement.value != null){
+ jsonPolicy[key]= searchElement.value;
+ }
+ }
+ }
+ }
+ }
var uuu = "policycreation/save_policy";
var postData={policyData: policy, policyJSON : jsonPolicy};
$.ajax({
@@ -1269,113 +1214,110 @@ angular.module('abs').controller('optimizationController', ['$scope', '$window',
data: JSON.stringify(postData),
success : function(data){
$scope.$apply(function(){
- $scope.data=data.policyData;
- if($scope.data == 'success'){
- $scope.temp.policy.readOnly = 'true';
- $scope.safetyChecker = data.policyData.split("#")[2];
- if ($scope.safetyChecker!=undefined) {
- Notification.success($scope.safetyChecker);
- }
- $scope.pushStatus=data.policyData.split("&")[1];
- if($scope.pushStatus=="successPush"){
- Notification.success("Policy pushed successfully");
- }
- Notification.success("Policy Saved Successfully.");
- }else if ($scope.data == 'PolicyExists'){
- $scope.savebutton = true;
- Notification.error("Policy Already Exists with Same Name in Scope.");
- }
+ $scope.data=data.policyData;
+ if($scope.data == 'success'){
+ $scope.temp.policy.readOnly = 'true';
+ $scope.safetyChecker = data.policyData.split("#")[2];
+ if ($scope.safetyChecker!=undefined) {
+ Notification.success($scope.safetyChecker);
+ }
+ $scope.pushStatus=data.policyData.split("&")[1];
+ if($scope.pushStatus=="successPush"){
+ Notification.success("Policy pushed successfully");
+ }
+ Notification.success("Policy Saved Successfully.");
+ }else if ($scope.data == 'PolicyExists'){
+ $scope.savebutton = true;
+ Notification.error("Policy Already Exists with Same Name in Scope.");
+ }
});
- console.log($scope.data);
},
error : function(data){
- Notification.error("Error Occured while saving Policy.");
+ Notification.error("Error Occured while saving Policy.");
}
});
};
$scope.validatePolicy = function(policy){
- document.getElementById("validate").innerHTML = "";
- var splitAt = '*';
- var dot ='.';
- var jsonPolicy = {};
- if(plainAttributeKeys != null){
- for(a = 0; a < plainAttributeKeys.length; a++){
- var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
- console.log(splitPlainAttributeKey[1]);
- var searchElement = document.getElementById(splitPlainAttributeKey[0]);
- var key = splitPlainAttributeKey[0];
- if(searchElement == null || searchElement.nodeName == 'BUTTON'){
- searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
- key = splitPlainAttributeKey[0]+'@0';
- }
- if(searchElement != null){
- if (enumKeyList.indexOf(key) != -1){
- if (splitPlainAttributeKey[1].indexOf("true") !== -1){
- var multiSlect = [];
- for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
- multiSlect.push(searchElement.selectedOptions[i].value);
- }
- jsonPolicy[key]= multiSlect;
- }else{
- jsonPolicy[key]= searchElement.value;
- }
- if(searchElement.getAttribute("required")){
- if(!searchElement.value){
- return;
- }
- }
- } else {
- if(searchElement.value != null){
- jsonPolicy[key]= searchElement.value;
- if(searchElement.getAttribute("required")){
- if(!searchElement.value){
- return;
- }
- }
- }
- }
- }
- }
- }
+ document.getElementById("validate").innerHTML = "";
+ var splitAt = '*';
+ var dot ='.';
+ var jsonPolicy = {};
+ if(plainAttributeKeys != null){
+ for(a = 0; a < plainAttributeKeys.length; a++){
+ var splitPlainAttributeKey = plainAttributeKeys[a].split(splitAt);
+ var searchElement = document.getElementById(splitPlainAttributeKey[0]);
+ var key = splitPlainAttributeKey[0];
+ if(searchElement == null || searchElement.nodeName == 'BUTTON'){
+ searchElement = document.getElementById(splitPlainAttributeKey[0]+'@0');
+ key = splitPlainAttributeKey[0]+'@0';
+ }
+ if(searchElement != null){
+ if (enumKeyList.indexOf(key) != -1){
+ if (splitPlainAttributeKey[1].indexOf("true") !== -1){
+ var multiSlect = [];
+ for ( var i = 0; i < searchElement.selectedOptions.length; i++) {
+ multiSlect.push(searchElement.selectedOptions[i].value);
+ }
+ jsonPolicy[key]= multiSlect;
+ }else{
+ jsonPolicy[key]= searchElement.value;
+ }
+ if(searchElement.getAttribute("required")){
+ if(!searchElement.value){
+ return;
+ }
+ }
+ } else {
+ if(searchElement.value != null){
+ jsonPolicy[key]= searchElement.value;
+ if(searchElement.getAttribute("required")){
+ if(!searchElement.value){
+ return;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
var uuu = "policyController/validate_policy.htm";
var postData={policyData: policy, policyJSON : jsonPolicy};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- $scope.validateData = data.data.replace(/\"/g, "");
- $scope.data=data.data.substring(1,8);
- var size = data.data.length;
- if($scope.data == 'success'){
- Notification.success("Validation Success.");
- $scope.savebutton = false;
- if (size > 18){
- var displayWarning = data.data.substring(19,size - 1);
- document.getElementById("validate").innerHTML = "Safe Policy Warning Message : "+displayWarning;
- document.getElementById("validate").style.color = "white";
- document.getElementById("validate").style.backgroundColor = "skyblue";
- }
- }else{
- Notification.error("Validation Failed.");
- document.getElementById("validate").innerHTML = $scope.validateData;
- document.getElementById("validate").style.color = "white";
- document.getElementById("validate").style.backgroundColor = "red";
- $scope.savebutton = true;
- }
-
- });
- console.log($scope.data);
- },
- error : function(data){
- Notification.error("Validation Failed.");
- $scope.savebutton = true;
- }
- });
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ $scope.validateData = data.data.replace(/\"/g, "");
+ $scope.data=data.data.substring(1,8);
+ var size = data.data.length;
+ if($scope.data == 'success'){
+ Notification.success("Validation Success.");
+ $scope.savebutton = false;
+ if (size > 18){
+ var displayWarning = data.data.substring(19,size - 1);
+ document.getElementById("validate").innerHTML = "Safe Policy Warning Message : "+displayWarning;
+ document.getElementById("validate").style.color = "white";
+ document.getElementById("validate").style.backgroundColor = "skyblue";
+ }
+ }else{
+ Notification.error("Validation Failed.");
+ document.getElementById("validate").innerHTML = $scope.validateData;
+ document.getElementById("validate").style.color = "white";
+ document.getElementById("validate").style.backgroundColor = "red";
+ $scope.savebutton = true;
+ }
+
+ });
+ },
+ error : function(data){
+ Notification.error("Validation Failed.");
+ $scope.savebutton = true;
+ }
+ });
};
function extend(obj, src) {
@@ -1386,4 +1328,4 @@ angular.module('abs').controller('optimizationController', ['$scope', '$window',
}
}]);/**
*
- */ \ 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 0aec30c1d..0cf655398 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,13 +2,13 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017, 2019-2020 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
+ * 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,
@@ -18,326 +18,308 @@
* ============LICENSE_END=========================================================
*/
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', '$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;
- $scope.importPolicyId = false;
- $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;
- 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.isDisabled = true;
+ $scope.superAdminId = false;
+ $scope.exportPolicyId = false;
+ $scope.importPolicyId = false;
+ $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;
+ 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;
+ }
+ }, function(error) {
+ });
- 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");
- });
+ PolicyAppService.getData('getDictionary/get_DescriptiveScopeByName').then(function(data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.descriptiveScopeDictionaryDatas = JSON.parse($scope.data.descriptiveScopeDictionaryDatas);
+ });
- 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_OnapNameDataByName').then(function(data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
+ });
- 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");
- });
-
- 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");
- });
+ PolicyAppService.getData('getDictionary/get_VSCLActionDataByName').then(function(data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.vsclActionDictionaryDatas = JSON.parse($scope.data.vsclActionDictionaryDatas);
+ });
+ PolicyAppService.getData('getDictionary/get_VNFTypeDataByName').then(function(data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.vnfTypeDictionaryDatas = JSON.parse($scope.data.vnfTypeDictionaryDatas);
+ });
- 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;
- } 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'];
- $scope.order = function(predicate) {
- $scope.reverse = ($scope.predicate[1] === predicate) ? !$scope.reverse : false;
- $scope.predicate[1] = predicate;
- };
+ PolicyAppService.getData('get_UserRolesData').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.userRolesDatas = JSON.parse($scope.data.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;
+ }
+ });
- $scope.query = '';
- $scope.temp = new Item();
- $scope.policyNavigator = new PolicyNavigator();
- $scope.policyUploader = PolicyUploader;
- $scope.uploadFileList = [];
+ $scope.config = policyManagerConfig;
+ $scope.reverse = false;
+ $scope.predicate = ['model.type', 'model.name'];
+ $scope.order = function(predicate) {
+ $scope.reverse = ($scope.predicate[1] === predicate) ? !$scope.reverse : false;
+ $scope.predicate[1] = predicate;
+ };
- $scope.setTemplate = function(name) {
- $scope.viewTemplate = $cookies.viewTemplate = name;
- };
+ $scope.query = '';
+ $scope.temp = new Item();
+ $scope.policyNavigator = new PolicyNavigator();
+ $scope.policyUploader = PolicyUploader;
+ $scope.uploadFileList = [];
- $scope.touch = function(item) {
- 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.setTemplate = function(name) {
+ $scope.viewTemplate = $cookies.viewTemplate = name;
+ };
- $scope.smartClick = function(item) {
- if (item.isFolder()) {
- return $scope.policyNavigator.folderClick(item);
- }
- if (item.isEditable()) {
- return $scope.openEditItem(item);
- }
- };
+ $scope.touch = function(item) {
+ 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.openEditItem = function(item) {
- item.getContent();
- $scope.modal('createNewPolicy');
- return $scope.touch(item);
- };
+ $scope.smartClick = function(item) {
+ if (item.isFolder()) {
+ return $scope.policyNavigator.folderClick(item);
+ }
+ if (item.isEditable()) {
+ return $scope.openEditItem(item);
+ }
+ };
- $scope.modal = function(id, hide) {
- return $('#' + id).modal(hide ? 'hide' : 'show');
- };
+ $scope.openEditItem = function(item) {
+ item.getContent();
+ $scope.modal('createNewPolicy');
+ return $scope.touch(item);
+ };
- $scope.isInThisPath = function(path) {
- var currentPath = $scope.policyNavigator.currentPath.join('/');
- return currentPath.indexOf(path) !== -1;
- };
-
- $scope.watchPolicy = function(item) {
- var uuu = "watchPolicy";
- var data = {name : item.model.name,
- path : item.model.path};
- var postData={watchData: data};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data) {
- $scope.$apply(function() {
- $scope.watchData=data.watchData;});
- Notification.success($scope.watchData);
- console.log($scope.watchData);
- },
- error : function(data) {
- alert("Error while saving.");
- }
- });
- };
+ $scope.modal = function(id, hide) {
+ return $('#' + id).modal(hide ? 'hide' : 'show');
+ };
- $scope.refresh = function() {
- $scope.policyNavigator.refresh();
- };
+ $scope.isInThisPath = function(path) {
+ var currentPath = $scope.policyNavigator.currentPath.join('/');
+ return currentPath.indexOf(path) !== -1;
+ };
+
+ $scope.watchPolicy = function(item) {
+ var uuu = "watchPolicy";
+ var data = {name : item.model.name,
+ path : item.model.path};
+ var postData={watchData: data};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data) {
+ $scope.$apply(function() {
+ $scope.watchData=data.watchData;});
+ Notification.success($scope.watchData);
+ },
+ error : function(data) {
+ Notification.error("Error while saving.");
+ }
+ });
+ };
- $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);
- });
+ $scope.refresh = function() {
+ $scope.policyNavigator.refresh();
};
- $scope.copy = function(item) {
- var samePath = item.tempModel.path.join() === item.model.path.join();
- if (samePath && $scope.policyNavigator.fileNameExists(item.tempModel.name)) {
- item.error = 'Invalid filename or already exists, specify another name';
- return false;
- }
- item.copy().then(function() {
- $scope.policyNavigator.refresh();
- $scope.modal('copy', true);
- });
- };
+ $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);
+ });
+ };
- $scope.remove = function(item) {
- item.remove().then(function() {
- $scope.policyNavigator.refresh();
- $scope.modal('delete', true);
- });
- };
+ $scope.copy = function(item) {
+ var samePath = item.tempModel.path.join() === item.model.path.join();
+ if (samePath && $scope.policyNavigator.fileNameExists(item.tempModel.name)) {
+ item.error = 'Invalid filename or already exists, specify another name';
+ return false;
+ }
+ item.copy().then(function() {
+ $scope.policyNavigator.refresh();
+ $scope.modal('copy', true);
+ });
+ };
- $scope.removePolicy = function(item) {
- item.removePolicy().then(function() {
- $scope.policyNavigator.refresh();
- $scope.modal('deletePolicy', true);
- });
- };
+ $scope.remove = function(item) {
+ item.remove().then(function() {
+ $scope.policyNavigator.refresh();
+ $scope.modal('delete', true);
+ });
+ };
- $scope.rename = function(item) {
- var samePath = item.tempModel.path.join() === item.model.path.join();
- if (samePath && $scope.policyNavigator.fileNameExists(item.tempModel.name)) {
- item.error = 'Invalid filename or already exists, specify another name';
- return false;
- }
- item.rename().then(function() {
- $scope.policyNavigator.refresh();
- $scope.modal('rename', true);
- });
- };
+ $scope.removePolicy = function(item) {
+ item.removePolicy().then(function() {
+ $scope.policyNavigator.refresh();
+ $scope.modal('deletePolicy', true);
+ });
+ };
- $scope.move = function(item) {
- var samePath = item.tempModel.path.join() === item.model.path.join();
- if (samePath && $scope.policyNavigator.fileNameExists(item.tempModel.name)) {
- item.error = 'Invalid filename or already exists, specify another name';
- return false;
- }
- item.move().then(function() {
- $scope.policyNavigator.refresh();
- $scope.modal('move', true);
- });
- };
+ $scope.rename = function(item) {
+ var samePath = item.tempModel.path.join() === item.model.path.join();
+ if (samePath && $scope.policyNavigator.fileNameExists(item.tempModel.name)) {
+ item.error = 'Invalid filename or already exists, specify another name';
+ return false;
+ }
+ item.rename().then(function() {
+ $scope.policyNavigator.refresh();
+ $scope.modal('rename', true);
+ });
+ };
- $scope.createFolder = function(item) {
- var name = item.tempModel.name && item.tempModel.name.trim();
- item.tempModel.type = 'dir';
- item.tempModel.path = $scope.policyNavigator.currentPath;
- if (name && !$scope.policyNavigator.fileNameExists(name)) {
- item.createFolder().then(function() {
- $scope.policyNavigator.refresh();
- $scope.modal('newfolder', true);
- });
- } else {
- item.error = 'Invalid filename or already exists, specify another name';
- return false;
- }
- };
+ $scope.move = function(item) {
+ var samePath = item.tempModel.path.join() === item.model.path.join();
+ if (samePath && $scope.policyNavigator.fileNameExists(item.tempModel.name)) {
+ item.error = 'Invalid filename or already exists, specify another name';
+ return false;
+ }
+ item.move().then(function() {
+ $scope.policyNavigator.refresh();
+ $scope.modal('move', true);
+ });
+ };
- $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;
- }
- };
+ $scope.createFolder = function(item) {
+ var name = item.tempModel.name && item.tempModel.name.trim();
+ item.tempModel.type = 'dir';
+ item.tempModel.path = $scope.policyNavigator.currentPath;
+ if (name && !$scope.policyNavigator.fileNameExists(name)) {
+ item.createFolder().then(function() {
+ $scope.policyNavigator.refresh();
+ $scope.modal('newfolder', true);
+ });
+ } else {
+ item.error = 'Invalid filename or already exists, specify another name';
+ return false;
+ }
+ };
- $scope.closefunction = function(fianlPath) {
- $scope.policyNavigator.policyrefresh(fianlPath);
- };
+ $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;
+ }
+ };
- $scope.uploadFiles = function() {
- $scope.policyUploader.upload($scope.uploadFileList, $scope.policyNavigator.currentPath).then(function() {
- $scope.policyNavigator.refresh();
- $scope.modal('uploadfile', true);
- }, function(data) {
- var errorMsg = data.result && data.result.error || 'Error Occured while Uploading....';
- $scope.temp.error = errorMsg;
- });
- };
+ $scope.closefunction = function(fianlPath) {
+ $scope.policyNavigator.policyrefresh(fianlPath);
+ };
- $scope.getQueryParam = function(param) {
- var found;
- window.location.search.substr(1).split('&').forEach(function(item) {
- if (param === item.split('=')[0]) {
- found = item.split('=')[1];
- return false;
- }
- });
- return found;
- };
+ $scope.uploadFiles = function() {
+ $scope.policyUploader.upload($scope.uploadFileList, $scope.policyNavigator.currentPath).then(function() {
+ $scope.policyNavigator.refresh();
+ Notification.success('Policy Import Complete');
+ $scope.modal('uploadfile', true);
+ }, function(data) {
+ var errorMsg = data.result && data.result.error || 'Error Occured while Uploading....';
+ $scope.temp.error = errorMsg;
+ });
+ };
- $scope.isWindows = $scope.getQueryParam('server') === 'Windows';
- $scope.policyNavigator.refresh();
- }]);
+ $scope.getQueryParam = function(param) {
+ var found;
+ window.location.search.substr(1).split('&').forEach(function(item) {
+ if (param === item.split('=')[0]) {
+ found = item.split('=')[1];
+ return false;
+ }
+ });
+ return found;
+ };
+
+ $scope.isWindows = $scope.getQueryParam('server') === 'Windows';
+ $scope.policyNavigator.refresh();
+ }]);
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policySearchManager.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policySearchManager.js
index 42e6796cd..edca7e47c 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policySearchManager.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/js/controllers/policySearchManager.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,194 +18,176 @@
* ============LICENSE_END=========================================================
*/
app.controller('PolicySearchController', [
- '$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;
- $scope.importPolicyId = false;
- $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;
- 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', '$q', '$window', '$cookies', 'policyManagerConfig', 'item', 'policyNavigator', 'policyUploader', 'Notification','PolicyAppService',
+ function($scope, $q, $Window, $cookies, policyManagerConfig, Item, PolicyNavigator, PolicyUploader, Notification, PolicyAppService ) {
- 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");
- });
+ $scope.isDisabled = true;
+ $scope.superAdminId = false;
+ $scope.exportPolicyId = false;
+ $scope.importPolicyId = false;
+ $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;
+ 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;
+ }
+ },function(error){
+ });
+
+ PolicyAppService.getData('getDictionary/get_DescriptiveScopeByName').then(function(data){
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.descriptiveScopeDictionaryDatas = JSON.parse($scope.data.descriptiveScopeDictionaryDatas);
+ });
- 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_OnapNameDataByName').then(function(data){
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.onapNameDictionaryDatas = JSON.parse($scope.data.onapNameDictionaryDatas);
+ });
- 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");
- });
+ PolicyAppService.getData('getDictionary/get_VSCLActionDataByName').then(function(data){
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.vsclActionDictionaryDatas = JSON.parse($scope.data.vsclActionDictionaryDatas);
+ });
- 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");
- });
+ PolicyAppService.getData('getDictionary/get_VNFTypeDataByName').then(function(data){
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.vnfTypeDictionaryDatas = JSON.parse($scope.data.vnfTypeDictionaryDatas);
+ });
-
- 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.createPolicyId = true;
- $scope.editPolicyId = true;
- $scope.describePolicyId = true;
- $scope.viewPolicyId = true;
- }else if($scope.userRolesDatas[0] == 'super-editor' || $scope.userRolesDatas[0] == 'editor' || $scope.userRolesDatas[0] == 'admin'){
- $scope.editPolicyId = true;
- $scope.createPolicyId = true;
- $scope.describePolicyId = true;
- $scope.viewPolicyId = true;
- }else if($scope.userRolesDatas[0] == 'super-guest' || $scope.userRolesDatas[0] == 'guest'){
- $scope.describePolicyId = true;
- $scope.viewPolicyId = true;
- }
- }, function (error) {
- console.log("failed");
- });
-
- $scope.config = policyManagerConfig;
- $scope.reverse = false;
- $scope.predicate = ['model.type', 'model.name'];
- $scope.order = function(predicate) {
- $scope.reverse = ($scope.predicate[1] === predicate) ? !$scope.reverse : false;
- $scope.predicate[1] = predicate;
- };
+
+ PolicyAppService.getData('get_UserRolesData').then(function (data) {
+ var j = data;
+ $scope.data = JSON.parse(j.data);
+ $scope.userRolesDatas = JSON.parse($scope.data.userRolesDatas);
+ if($scope.userRolesDatas[0] == 'super-admin'){
+ $scope.superAdminId = true;
+ $scope.createPolicyId = true;
+ $scope.editPolicyId = true;
+ $scope.describePolicyId = true;
+ $scope.viewPolicyId = true;
+ }else if($scope.userRolesDatas[0] == 'super-editor' || $scope.userRolesDatas[0] == 'editor' || $scope.userRolesDatas[0] == 'admin'){
+ $scope.editPolicyId = true;
+ $scope.createPolicyId = true;
+ $scope.describePolicyId = true;
+ $scope.viewPolicyId = true;
+ }else if($scope.userRolesDatas[0] == 'super-guest' || $scope.userRolesDatas[0] == 'guest'){
+ $scope.describePolicyId = true;
+ $scope.viewPolicyId = true;
+ }
+ });
+
+ $scope.config = policyManagerConfig;
+ $scope.reverse = false;
+ $scope.predicate = ['model.type', 'model.name'];
+ $scope.order = function(predicate) {
+ $scope.reverse = ($scope.predicate[1] === predicate) ? !$scope.reverse : false;
+ $scope.predicate[1] = predicate;
+ };
- $scope.query = '';
- $scope.temp = new Item();
- $scope.policyNavigator = new PolicyNavigator();
+ $scope.query = '';
+ $scope.temp = new Item();
+ $scope.policyNavigator = new PolicyNavigator();
- $scope.setTemplate = function(name) {
- $scope.viewTemplate = $cookies.viewTemplate = name;
- };
+ $scope.setTemplate = function(name) {
+ $scope.viewTemplate = $cookies.viewTemplate = name;
+ };
- $scope.touch = function(item) {
- item = item instanceof Item ? item : new Item();
- item.revert();
- $scope.temp = item;
- };
+ $scope.touch = function(item) {
+ item = item instanceof Item ? item : new Item();
+ item.revert();
+ $scope.temp = item;
+ };
- $scope.smartClick = function(item) {
- if (item.isFolder()) {
- return $scope.policyNavigator.folderClick(item);
- }
- if (item.isEditable()) {
- return $scope.openEditItem(item);
- }
- };
+ $scope.smartClick = function(item) {
+ if (item.isFolder()) {
+ return $scope.policyNavigator.folderClick(item);
+ }
+ if (item.isEditable()) {
+ return $scope.openEditItem(item);
+ }
+ };
- $scope.openEditItem = function(item) {
- item.getContent();
- $scope.modal('createNewPolicy');
- return $scope.touch(item);
- };
+ $scope.openEditItem = function(item) {
+ item.getContent();
+ $scope.modal('createNewPolicy');
+ return $scope.touch(item);
+ };
- $scope.modal = function(id, hide) {
- return $('#' + id).modal(hide ? 'hide' : 'show');
- };
+ $scope.modal = function(id, hide) {
+ return $('#' + id).modal(hide ? 'hide' : 'show');
+ };
- $scope.isInThisPath = function(path) {
- var currentPath = $scope.policyNavigator.currentPath.join('/');
- return currentPath.indexOf(path) !== -1;
- };
+ $scope.isInThisPath = function(path) {
+ var currentPath = $scope.policyNavigator.currentPath.join('/');
+ return currentPath.indexOf(path) !== -1;
+ };
- $scope.searchPolicy = function(searchContent){
- if(searchContent != undefined){
- var uuu = "searchPolicy";
- var postData = {searchdata : searchContent};
- $.ajax({
- type : 'POST',
- url : uuu,
- dataType: 'json',
- contentType: 'application/json',
- data: JSON.stringify(postData),
- success : function(data){
- $scope.$apply(function(){
- var searchdata = data.result;
- if(searchdata.length > 0){
- if(searchdata[0] == "Exception"){
- Notification.error(searchdata[1]);
- }else{
- $scope.policyNavigator.searchrefresh(searchdata);
- }
- }else{
- Notification.info("No Matches Found with your Search");
- }
- });
- },
- error : function(data){
- Notification.error("Error while Searching.");
- }
- });
- }else{
- Notification.error("No data has been entered or selected to search");
- }
- };
+ $scope.searchPolicy = function(searchContent){
+ if(searchContent != undefined){
+ var uuu = "searchPolicy";
+ var postData = {searchdata : searchContent};
+ $.ajax({
+ type : 'POST',
+ url : uuu,
+ dataType: 'json',
+ contentType: 'application/json',
+ data: JSON.stringify(postData),
+ success : function(data){
+ $scope.$apply(function(){
+ var searchdata = data.result;
+ if(searchdata.length > 0){
+ if(searchdata[0] == "Exception"){
+ Notification.error(searchdata[1]);
+ }else{
+ $scope.policyNavigator.searchrefresh(searchdata);
+ }
+ }else{
+ Notification.info("No Matches Found with your Search");
+ }
+ });
+ },
+ error : function(data){
+ Notification.error("Error while Searching.");
+ }
+ });
+ }else{
+ Notification.error("No data has been entered or selected to search");
+ }
+ };
$scope.refresh = function(searchData){
- $scope.policyNavigator.searchrefresh(null);
+ $scope.policyNavigator.searchrefresh(null);
};
-
- $scope.getQueryParam = function(param) {
- var found;
- window.location.search.substr(1).split('&').forEach(function(item) {
- if (param === item.split('=')[0]) {
- found = item.split('=')[1];
- return false;
- }
- });
- return found;
- };
+
+ $scope.getQueryParam = function(param) {
+ var found;
+ window.location.search.substr(1).split('&').forEach(function(item) {
+ if (param === item.split('=')[0]) {
+ found = item.split('=')[1];
+ return false;
+ }
+ });
+ return found;
+ };
- $scope.isWindows = $scope.getQueryParam('server') === 'Windows';
- $scope.policyNavigator.searchrefresh(null);
- $scope.policyNavigator.setSearchModalActiveStatus();
+ $scope.isWindows = $scope.getQueryParam('server') === 'Windows';
+ $scope.policyNavigator.searchrefresh(null);
+ $scope.policyNavigator.setSearchModalActiveStatus();
}]);
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 26cdf67c3..017f49ddc 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
@@ -51,10 +51,6 @@ angular.module('abs').factory('item', ['$http', '$q', 'policyManagerConfig', fun
this.model = angular.copy(rawModel);
this.tempModel = angular.copy(rawModel);
- function parseMySQLDate(mysqlDate) {
- var d = (mysqlDate || '').toString().split(/[- :]/);
- return new Date(d[0], d[1] - 1, d[2], d[3], d[4], d[5]);
- }
};
Item.prototype.update = function() {
@@ -263,7 +259,6 @@ angular.module('abs').factory('item', ['$http', '$q', 'policyManagerConfig', fun
self.error = '';
$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) {
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/service/modalService.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/service/modalService.js
index 381db7f9a..ceb2ec39f 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/service/modalService.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/service/modalService.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.
@@ -21,7 +21,7 @@ angular.module("modalServices",[]).service('modalService', ['$modal', function (
this.showSuccess = function(heading, messageBody){
- var modalInstance = $modal.open({
+ $modal.open({
templateUrl: 'modal_informative.html',
controller: 'modalpopupController',
resolve: {
@@ -38,7 +38,7 @@ angular.module("modalServices",[]).service('modalService', ['$modal', function (
});
};
this.showFailure = function(heading, messageBody){
- var modalInstance = $modal.open({
+ $modal.open({
templateUrl: 'modal_warning.html',
controller: 'modalpopupController',
resolve: {
@@ -54,7 +54,7 @@ angular.module("modalServices",[]).service('modalService', ['$modal', function (
};
this.showMessage = function(heading, messageBody){
- var modalInstance = $modal.open({
+ $modal.open({
templateUrl: 'modal_message.html',
controller: 'modalpopupController',
resolve: {
@@ -70,7 +70,7 @@ angular.module("modalServices",[]).service('modalService', ['$modal', function (
};
this.showWarning = function(heading, messageBody){
- var modalInstance = $modal.open({
+ $modal.open({
templateUrl: 'modal_warning_message.html',
controller: 'modalpopupController',
resolve: {
@@ -201,4 +201,4 @@ angular.module("modalServices",[]).service('modalService', ['$modal', function (
modalInstance = undefined;
});
};
- }]); \ No newline at end of file
+ }]);