summaryrefslogtreecommitdiffstats
path: root/POLICY-SDK-APP/src
diff options
context:
space:
mode:
authorRavindra Bakkamanthala <rb7147@att.com>2017-05-31 15:54:24 -0400
committerRavindra Bakkamanthala <rb7147@att.com>2017-05-31 15:57:02 -0400
commitd9007d680d19734d5dc106479784c420236cca4b (patch)
treeb3356847c3d6e1543098b447c1df7d49e7118652 /POLICY-SDK-APP/src
parent6a5e800771311208c66ad79ce1bdf76affd144b2 (diff)
[Policy-17] Removed the sql scripts from sdk app
Change-Id: I5b017aad569014c7f12eab35e1dbd1c215f90ebe Signed-off-by: Ravindra Bakkamanthala <rb7147@att.com>
Diffstat (limited to 'POLICY-SDK-APP/src')
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/CheckPDP.java100
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java100
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyNotificationMail.java50
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyRestController.java174
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/RESTfulPAPEngine.java51
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/components/HumanPolicyComponent.java20
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/conf/HibernateSession.java10
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AdminTabController.java19
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AutoPushController.java41
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java269
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java49
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DashboardController.java20
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PDPController.java366
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyController.java412
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyExportAndImportController.java13
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/SystemLogDbDaoImpl.java4
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/PDPGroupContainer.java26
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/PDPPolicyContainer.java12
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/ConfigurableRESTUtils.java6
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/AutoPushController.js2
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/templates/navbar.html2
-rw-r--r--POLICY-SDK-APP/src/test/java/org/openecomp/policy/admin/PolicyManagerServletTest.java155
-rw-r--r--POLICY-SDK-APP/src/test/java/org/openecomp/policy/controller/AdminTabControllerTest.java74
-rw-r--r--POLICY-SDK-APP/src/test/java/org/openecomp/policy/controller/CreateDcaeMicroServiceControllerTest.java647
-rw-r--r--POLICY-SDK-APP/src/test/java/org/openecomp/policy/controller/PDPControllerTest.java98
-rw-r--r--POLICY-SDK-APP/src/test/java/org/openecomp/policy/controller/PolicyControllerTest.java66
-rw-r--r--POLICY-SDK-APP/src/test/resources/Config_SampleTest1206.1.xml90
-rw-r--r--POLICY-SDK-APP/src/test/resources/logback.xml254
-rw-r--r--POLICY-SDK-APP/src/test/resources/policy_tosca_tca_v1707.yml65
-rw-r--r--POLICY-SDK-APP/src/test/resources/schedulerPolicies1707.xmi156
30 files changed, 2681 insertions, 670 deletions
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/CheckPDP.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/CheckPDP.java
index 4f026ff10..ca5aff193 100644
--- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/CheckPDP.java
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/CheckPDP.java
@@ -25,7 +25,6 @@ import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
-import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
@@ -37,22 +36,22 @@ import java.util.HashMap;
import java.util.List;
import java.util.Properties;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
import org.openecomp.policy.rest.XACMLRestProperties;
-
import org.openecomp.policy.xacml.api.XACMLErrorConstants;
-import com.att.research.xacml.util.XACMLProperties;
-import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
-import org.openecomp.policy.common.logging.flexlogger.Logger;
+import com.att.research.xacml.util.XACMLProperties;
public class CheckPDP {
private static Path pdpPath = null;
- private static Properties pdpProp = null;
private static Long oldModified = null;
- private static Long newModified = null;
private static HashMap<String, String> pdpMap = null;
private static final Logger LOGGER = FlexLogger.getLogger(CheckPDP.class);
-
+
+ private CheckPDP(){
+ //default constructor
+ }
public static boolean validateID(String id) {
// ReadFile
try {
@@ -62,41 +61,37 @@ public class CheckPDP {
return false;
}
// Check ID
- if (pdpMap.containsKey(id)) {
- return true;
- }
- return false;
+ return (pdpMap.containsKey(id))? true: false;
}
- private static void readFile() throws Exception {
+ private static void readFile(){
String pdpFile = null;
+ Long newModified = null;
try{
pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE);
}catch (Exception e){
- LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot read the PDP ID File");
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot read the PDP ID File" + e);
return;
}
if (pdpFile == null) {
LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PDP File name not Valid : " + pdpFile);
- throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"PDP File name not Valid : " + pdpFile);
}
if (pdpPath == null) {
pdpPath = Paths.get(pdpFile);
- if (Files.notExists(pdpPath)) {
+ if (!pdpPath.toFile().exists()) {
LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path : " + pdpPath.toString());
- throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"File doesn't exist in the specified Path : "+ pdpPath.toString());
+
}
if (pdpPath.toString().endsWith(".properties")) {
readProps();
} else {
LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file " + pdpFile);
- throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Not a .properties file");
}
}
// Check if File is updated recently
else {
newModified = pdpPath.toFile().lastModified();
- if (newModified != oldModified) {
+ if (!newModified.equals(oldModified)) {
// File has been updated.
readProps();
}
@@ -104,51 +99,52 @@ public class CheckPDP {
}
@SuppressWarnings({ "unchecked", "rawtypes" })
- private static void readProps() throws Exception {
- InputStream in;
+ private static void readProps() {
+ Properties pdpProp = null;
pdpProp = new Properties();
try {
- in = new FileInputStream(pdpPath.toFile());
+ InputStream in = new FileInputStream(pdpPath.toFile());
oldModified = pdpPath.toFile().lastModified();
pdpProp.load(in);
+ // Read the Properties and Load the PDPs and encoding.
+ pdpMap = new HashMap<>();
+ // Check the Keys for PDP_URLs
+ Collection<Object> unsorted = pdpProp.keySet();
+ List<String> sorted = new ArrayList(unsorted);
+ Collections.sort(sorted);
+ for (String propKey : sorted) {
+ loadPDPProperties(propKey, pdpProp);
+ }
+ if (pdpMap == null || pdpMap.isEmpty()) {
+ LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Proceed without PDP_URLs");
+ }
+ in.close();
} catch (IOException e) {
LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
- throw new Exception("Cannot Load the Properties file", e);
}
- // Read the Properties and Load the PDPs and encoding.
- pdpMap = new HashMap<String, String>();
- // Check the Keys for PDP_URLs
- Collection<Object> unsorted = pdpProp.keySet();
- List<String> sorted = new ArrayList(unsorted);
- Collections.sort(sorted);
- for (String propKey : sorted) {
- if (propKey.startsWith("PDP_URL")) {
- String check_val = pdpProp.getProperty(propKey);
- if (check_val == null) {
- throw new Exception("Properties file doesn't have the PDP_URL parameter");
- }
- if (check_val.contains(";")) {
- List<String> pdp_default = new ArrayList<String>(Arrays.asList(check_val.split("\\s*;\\s*")));
- int pdpCount = 0;
- while (pdpCount < pdp_default.size()) {
- String pdpVal = pdp_default.get(pdpCount);
- readPDPParam(pdpVal);
- pdpCount++;
- }
- } else {
- readPDPParam(check_val);
+ }
+
+ private static void loadPDPProperties(String propKey, Properties pdpProp){
+ if (propKey.startsWith("PDP_URL")) {
+ String check_val = pdpProp.getProperty(propKey);
+ if (check_val == null) {
+ LOGGER.error("Properties file doesn't have the PDP_URL parameter");
+ }
+ if (check_val != null && check_val.contains(";")) {
+ List<String> pdp_default = new ArrayList<>(Arrays.asList(check_val.split("\\s*;\\s*")));
+ int pdpCount = 0;
+ while (pdpCount < pdp_default.size()) {
+ String pdpVal = pdp_default.get(pdpCount);
+ readPDPParam(pdpVal);
+ pdpCount++;
}
}
}
- if (pdpMap == null || pdpMap.isEmpty()) {
- LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Proceed without PDP_URLs");
- throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Cannot Proceed without PDP_URLs");
- }
}
- private static void readPDPParam(String pdpVal) throws Exception{
+ private static void readPDPParam(String pdpVal){
if(pdpVal.contains(",")){
- List<String> pdpValues = new ArrayList<String>(Arrays.asList(pdpVal.split("\\s*,\\s*")));
+ List<String> pdpValues = new ArrayList<>(Arrays.asList(pdpVal.split("\\s*,\\s*")));
if(pdpValues.size()==3){
// 1:2 will be UserID:Password
String userID = pdpValues.get(1);
@@ -158,11 +154,9 @@ public class CheckPDP {
pdpMap.put(pdpValues.get(0), encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8)));
}else{
LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpValues);
- throw new Exception(XACMLErrorConstants.ERROR_PERMISSIONS + "No enough Credentials to send Request. " + pdpValues);
}
}else{
LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpVal);
- throw new Exception(XACMLErrorConstants.ERROR_PERMISSIONS +"No enough Credentials to send Request.");
}
}
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java
index a3f4ada0a..fdf43264f 100644
--- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java
@@ -95,6 +95,15 @@ public class PolicyManagerServlet extends HttpServlet {
LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT, SEARCHLIST
}
+ private PolicyController policyController;
+ public PolicyController getPolicyController() {
+ return policyController;
+ }
+
+ public void setPolicyController(PolicyController policyController) {
+ this.policyController = policyController;
+ }
+
private static String CONTENTTYPE = "application/json";
private static String SUPERADMIN = "super-admin";
private static String SUPEREDITOR = "super-editor";
@@ -106,6 +115,7 @@ public class PolicyManagerServlet extends HttpServlet {
private static Path closedLoopJsonLocation;
private static JsonArray policyNames;
+ private String testUserId = null;
public static JsonArray getPolicyNames() {
return policyNames;
@@ -139,11 +149,11 @@ public class PolicyManagerServlet extends HttpServlet {
closedLoopJsonLocation = Paths.get(XACMLProperties
.getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP));
FileInputStream inputStream = null;
+ JsonReader jsonReader = null;
String location = closedLoopJsonLocation.toString();
try {
inputStream = new FileInputStream(location);
- if (location.endsWith("json")) {
- JsonReader jsonReader = null;
+ if (location.endsWith("json")) {
jsonReader = Json.createReader(inputStream);
policyNames = jsonReader.readArray();
serviceTypeNamesList = new ArrayList<>();
@@ -152,13 +162,17 @@ public class PolicyManagerServlet extends HttpServlet {
String name = policyName.getJsonString("serviceTypePolicyName").getString();
serviceTypeNamesList.add(name);
}
- jsonReader.close();
}
} catch (FileNotFoundException e) {
LOGGER.error("Exception Occured while initializing the JSONConfig file"+e);
}finally{
try {
- inputStream.close();
+ if(inputStream != null){
+ inputStream.close();
+ }
+ if(jsonReader != null){
+ jsonReader.close();
+ }
} catch (IOException e) {
LOGGER.error("Exception Occured while closing the File InputStream"+e);
}
@@ -208,9 +222,10 @@ public class PolicyManagerServlet extends HttpServlet {
// Process form file field (input type="file").
files.put(item.getName(), item.getInputStream());
if(item.getName().endsWith(".xls")){
+ OutputStream outputStream = null;
try{
File file = new File(item.getName());
- OutputStream outputStream = new FileOutputStream(file);
+ outputStream = new FileOutputStream(file);
IOUtils.copy(item.getInputStream(), outputStream);
outputStream.close();
newFile = file.toString();
@@ -218,6 +233,10 @@ public class PolicyManagerServlet extends HttpServlet {
importController.importRepositoryFile(newFile, request);
}catch(Exception e){
LOGGER.error("Upload error : " + e);
+ }finally{
+ if(outputStream != null){
+ outputStream.close();
+ }
}
}
}
@@ -307,13 +326,13 @@ public class PolicyManagerServlet extends HttpServlet {
if(params.has("policyList")){
policyList = (JSONArray) params.get("policyList");
}
- PolicyController controller = new PolicyController();
+ PolicyController controller = getPolicyControllerInstance();
List<JSONObject> resultList = new ArrayList<>();
try {
//Get the Login Id of the User from Request
String userId = UserUtils.getUserSession(request).getOrgUserId();
//Check if the Role and Scope Size are Null get the values from db.
- List<Object> userRoles = PolicyController.getRoles(userId);
+ List<Object> userRoles = controller.getRoles(userId);
roles = new ArrayList<>();
scopes = new HashSet<>();
for(Object role: userRoles){
@@ -412,7 +431,7 @@ public class PolicyManagerServlet extends HttpServlet {
}
String activePolicy = null;
- PolicyController controller = new PolicyController();
+ PolicyController controller = getPolicyControllerInstance();
if(params.toString().contains("activeVersion")){
String activeVersion = params.getString("activeVersion");
String highestVersion = params.get("highestVersion").toString();
@@ -477,6 +496,7 @@ public class PolicyManagerServlet extends HttpServlet {
path = path.replace("/", ".");
}else{
path = path.replace("/", ".");
+ policyName = path;
}
if(path.contains("Config_")){
path = path.replace(".Config_", ":Config_");
@@ -485,16 +505,17 @@ public class PolicyManagerServlet extends HttpServlet {
}else if(path.contains("Decision_")){
path = path.replace(".Decision_", ":Decision_");
}
- PolicyController controller = new PolicyController();
+ PolicyController controller = getPolicyControllerInstance();
String[] split = path.split(":");
String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'";
List<Object> queryData = controller.getDataByQuery(query);
if(!queryData.isEmpty()){
PolicyEntity entity = (PolicyEntity) queryData.get(0);
File temp = null;
+ BufferedWriter bw = null;
try {
temp = File.createTempFile(policyName, ".tmp");
- BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
+ bw = new BufferedWriter(new FileWriter(temp));
bw.write(entity.getPolicyData());
bw.close();
object = HumanPolicyComponent.DescribePolicy(temp);
@@ -504,6 +525,13 @@ public class PolicyManagerServlet extends HttpServlet {
if(temp != null){
temp.delete();
}
+ if(bw != null){
+ try {
+ bw.close();
+ } catch (IOException e) {
+ LOGGER.error("Exception Occured while Closing the File Writer"+e);
+ }
+ }
}
}else{
return error("Error Occured while Describing the Policy");
@@ -517,10 +545,12 @@ public class PolicyManagerServlet extends HttpServlet {
Set<String> scopes = null;
List<String> roles = null;
try {
+ PolicyController controller = getPolicyControllerInstance();
//Get the Login Id of the User from Request
- String userId = UserUtils.getUserSession(request).getOrgUserId();
+ String testUserID = getTestUserId();
+ String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId();
//Check if the Role and Scope Size are Null get the values from db.
- List<Object> userRoles = PolicyController.getRoles(userId);
+ List<Object> userRoles = controller.getRoles(userId);
roles = new ArrayList<>();
scopes = new HashSet<>();
for(Object role: userRoles){
@@ -604,22 +634,22 @@ public class PolicyManagerServlet extends HttpServlet {
}else{
scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"'";
}
- PolicyController controller = new PolicyController();
+ PolicyController controller = getPolicyControllerInstance();
List<Object> scopesList = controller.getDataByQuery(scopeNamequery);
return scopesList;
}
//Get Active Policy List based on Scope Selection form Policy Version table
private void activePolicyList(String scopeName, List<JSONObject> resultList, List<String> roles, Set<String> scopes, boolean onlyFolders){
- PolicyController controller = new PolicyController();
+ PolicyController controller = getPolicyControllerInstance();
if(scopeName.contains("/")){
scopeName = scopeName.replace("/", File.separator);
}
if(scopeName.contains("\\")){
scopeName = scopeName.replace("\\", "\\\\\\\\");
}
- String query = "from PolicyVersion where POLICY_NAME like'" +scopeName+"%'";
- String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"%'";
+ String query = "from PolicyVersion where POLICY_NAME like '" +scopeName+"%'";
+ String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like '" +scopeName+"%'";
List<Object> activePolicies = controller.getDataByQuery(query);
List<Object> scopesList = controller.getDataByQuery(scopeNamequery);
for(Object list : scopesList){
@@ -686,7 +716,7 @@ public class PolicyManagerServlet extends HttpServlet {
}
private String getUserName(String loginId){
- PolicyController controller = new PolicyController();
+ PolicyController controller = getPolicyControllerInstance();
UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId);
if(userInfo == null){
return SUPERADMIN;
@@ -721,7 +751,7 @@ public class PolicyManagerServlet extends HttpServlet {
scopeName = scopeName.replace("\\", "\\\\\\\\");
newScopeName = newScopeName.replace("\\", "\\\\\\\\");
}
- PolicyController controller = new PolicyController();
+ PolicyController controller = getPolicyControllerInstance();
String query = "from PolicyVersion where POLICY_NAME like'" +scopeName+"%'";
String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"%'";
List<Object> activePolicies = controller.getDataByQuery(query);
@@ -784,7 +814,7 @@ public class PolicyManagerServlet extends HttpServlet {
private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException {
try {
PolicyEntity entity = null;
- PolicyController controller = new PolicyController();
+ PolicyController controller = getPolicyControllerInstance();
String policyVersionName = newPath.replace(".xml", "");
String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")).replace("/", File.separator);
@@ -861,7 +891,7 @@ public class PolicyManagerServlet extends HttpServlet {
try {
ConfigurationDataEntity configEntity = entity.getConfigurationData();
ActionBodyEntity actionEntity = entity.getActionBodyEntity();
- PolicyController controller = new PolicyController();
+ PolicyController controller = getPolicyControllerInstance();
String oldPolicyNameWithoutExtension = removeoldPolicyExtension;
String newPolicyNameWithoutExtension = removenewPolicyExtension;
@@ -878,9 +908,9 @@ public class PolicyManagerServlet extends HttpServlet {
configEntity.setConfigurationName(configEntity.getConfigurationName().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
controller.updateData(configEntity);
String newConfigurationName = configEntity.getConfigurationName();
- File file = new File(PolicyController.configHome + File.separator + oldConfigurationName);
+ File file = new File(PolicyController.getConfigHome() + File.separator + oldConfigurationName);
if(file.exists()){
- File renamefile = new File(PolicyController.configHome + File.separator + newConfigurationName);
+ File renamefile = new File(PolicyController.getConfigHome() + File.separator + newConfigurationName);
file.renameTo(renamefile);
}
}else if(newpolicyName.contains("Action_")){
@@ -888,9 +918,9 @@ public class PolicyManagerServlet extends HttpServlet {
actionEntity.setActionBody(actionEntity.getActionBody().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension));
controller.updateData(actionEntity);
String newConfigurationName = actionEntity.getActionBodyName();
- File file = new File(PolicyController.actionHome + File.separator + oldConfigurationName);
+ File file = new File(PolicyController.getActionHome() + File.separator + oldConfigurationName);
if(file.exists()){
- File renamefile = new File(PolicyController.actionHome + File.separator + newConfigurationName);
+ File renamefile = new File(PolicyController.getActionHome() + File.separator + newConfigurationName);
file.renameTo(renamefile);
}
}
@@ -916,7 +946,7 @@ public class PolicyManagerServlet extends HttpServlet {
private JSONObject cloneRecord(String newpolicyName, String oldScope, String removeoldPolicyExtension, String newScope, String removenewPolicyExtension, PolicyEntity entity, String userId) throws ServletException{
String queryEntityName = null;
- PolicyController controller = new PolicyController();
+ PolicyController controller = getPolicyControllerInstance();
PolicyEntity cloneEntity = new PolicyEntity();
cloneEntity.setPolicyName(newpolicyName);
removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", "");
@@ -994,7 +1024,7 @@ public class PolicyManagerServlet extends HttpServlet {
}
String[] oldPolicySplit = oldPolicyCheck.split(":");
- PolicyController controller = new PolicyController();
+ PolicyController controller = getPolicyControllerInstance();
PolicyEntity entity = null;
boolean success = false;
@@ -1063,7 +1093,7 @@ public class PolicyManagerServlet extends HttpServlet {
//Delete Policy or Scope Functionality
private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException {
- PolicyController controller = new PolicyController();
+ PolicyController controller = getPolicyControllerInstance();
PolicyRestController restController = new PolicyRestController();
PolicyEntity policyEntity = null;
String policyNamewithoutExtension;
@@ -1272,7 +1302,7 @@ public class PolicyManagerServlet extends HttpServlet {
private JSONObject editFile(JSONObject params) throws ServletException {
// get content
try {
- PolicyController controller = new PolicyController();
+ PolicyController controller = getPolicyControllerInstance();
String mode = params.getString("mode");
String path = params.getString("path");
LOGGER.debug("editFile path: {}"+ path);
@@ -1333,7 +1363,7 @@ public class PolicyManagerServlet extends HttpServlet {
//Add Scopes
private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException {
- PolicyController controller = new PolicyController();
+ PolicyController controller = getPolicyControllerInstance();
String name = "";
try {
String userId = UserUtils.getUserSession(request).getOrgUserId();
@@ -1413,4 +1443,16 @@ public class PolicyManagerServlet extends HttpServlet {
throw new ServletException(e);
}
}
+
+ private PolicyController getPolicyControllerInstance(){
+ return policyController != null ? getPolicyController() : new PolicyController();
+ }
+
+ public String getTestUserId() {
+ return testUserId;
+ }
+
+ public void setTestUserId(String testUserId) {
+ this.testUserId = testUserId;
+ }
} \ No newline at end of file
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyNotificationMail.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyNotificationMail.java
index 5d8460bf6..9bd6e4f43 100644
--- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyNotificationMail.java
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyNotificationMail.java
@@ -46,15 +46,15 @@ import org.springframework.mail.javamail.MimeMessageHelper;
@Configurable
public class PolicyNotificationMail{
- private static Logger LOGGER = FlexLogger.getLogger(PolicyNotificationMail.class);
+ private static Logger policyLogger = FlexLogger.getLogger(PolicyNotificationMail.class);
@Bean
public JavaMailSenderImpl javaMailSenderImpl(){
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
- mailSender.setHost(PolicyController.smtpHost);
- mailSender.setPort(Integer.parseInt(PolicyController.smtpPort));
- mailSender.setUsername(PolicyController.smtpUsername);
- mailSender.setPassword(PolicyController.smtpPassword);
+ mailSender.setHost(PolicyController.getSmtpHost());
+ mailSender.setPort(Integer.parseInt(PolicyController.getSmtpPort()));
+ mailSender.setUsername(PolicyController.getSmtpUsername());
+ mailSender.setPassword(PolicyController.getSmtpPassword());
Properties prop = mailSender.getJavaMailProperties();
prop.put("mail.transport.protocol", "smtp");
prop.put("mail.smtp.auth", "true");
@@ -64,7 +64,7 @@ public class PolicyNotificationMail{
}
public void sendMail(PolicyVersion entityItem, String policyName, String mode, CommonClassDao policyNotificationDao) throws MessagingException {
- String from = PolicyController.smtpUsername;
+ String from = PolicyController.getSmtpUsername();
String to = "";
String subject = "";
String message = "";
@@ -72,37 +72,37 @@ public class PolicyNotificationMail{
Date date = new Date();
if("EditPolicy".equalsIgnoreCase(mode)){
subject = "Policy has been Updated : "+entityItem.getPolicyName();
- message = "The Policy Which you are watching in " + PolicyController.smtpApplicationName + " has been Updated" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + "Active Version : " +entityItem.getActiveVersion()
+ message = "The Policy Which you are watching in " + 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' + "Policy Notification System (please don't respond to this email)";
}
if("Rename".equalsIgnoreCase(mode)){
subject = "Policy has been Renamed : "+entityItem.getPolicyName();
- message = "The Policy Which you are watching in " + PolicyController.smtpApplicationName + " has been Renamed" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + "Active Version : " +entityItem.getActiveVersion()
+ message = "The Policy Which you are watching in " + 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' + "Policy Notification System (please don't respond to this email)";
}
if("DeleteAll".equalsIgnoreCase(mode)){
subject = "Policy has been Deleted : "+entityItem.getPolicyName();
- message = "The Policy Which you are watching in " + PolicyController.smtpApplicationName + " has been Deleted with All Versions" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n'
+ message = "The Policy Which you are watching in " + 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' + "Policy Notification System (please don't respond to this email)";
}
if("DeleteOne".equalsIgnoreCase(mode)){
subject = "Policy has been Deleted : "+entityItem.getPolicyName();
- message = "The Policy Which you are watching in " + PolicyController.smtpApplicationName + " has been Deleted" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' +"Policy Version : " +entityItem.getActiveVersion()
+ message = "The Policy Which you are watching in " + 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' + "Policy Notification System (please don't respond to this email)";
}
if("DeleteScope".equalsIgnoreCase(mode)){
subject = "Scope has been Deleted : "+entityItem.getPolicyName();
- message = "The Scope Which you are watching in " + PolicyController.smtpApplicationName + " has been Deleted" + '\n' + '\n' + '\n'+ "Scope + Scope Name : " + policyName + '\n'
+ 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' + "Policy Notification System (please don't respond to this email)";
}
if("SwitchVersion".equalsIgnoreCase(mode)){
subject = "Policy has been SwitchedVersion : "+entityItem.getPolicyName();
- message = "The Policy Which you are watching in " + PolicyController.smtpApplicationName + " has been SwitchedVersion" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + "Active Version : " +entityItem.getActiveVersion()
+ message = "The Policy Which you are watching in " + 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' + "Policy Notification System (please don't respond to this email)";
}
if("Move".equalsIgnoreCase(mode)){
subject = "Policy has been Moved to Other Scope : "+entityItem.getPolicyName();
- message = "The Policy Which you are watching in " + PolicyController.smtpApplicationName + " has been Moved to Other Scope" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + "Active Version : " +entityItem.getActiveVersion()
+ message = "The Policy Which you are watching in " + 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' + "Policy Notification System (please don't respond to this email)";
}
String policyFileName = entityItem.getPolicyName();
@@ -120,29 +120,21 @@ public class PolicyNotificationMail{
boolean sendFlag = false;
List<Object> watchList = policyNotificationDao.getDataByQuery(query);
if(watchList != null){
- if(watchList.size() > 0){
+ if(watchList.isEmpty()){
for(Object watch : watchList){
WatchPolicyNotificationTable list = (WatchPolicyNotificationTable) watch;
String watchPolicyName = list.getPolicyName();
- if(watchPolicyName.contains("Config_")){
+ if(watchPolicyName.contains("Config_") || watchPolicyName.contains("Action_") || watchPolicyName.contains("Decision_")){
if(watchPolicyName.equals(checkPolicyName)){
sendFlag = true;
+ }else{
+ sendFlag = false;
}
- }else if(watchPolicyName.contains("Action_")){
- if(watchPolicyName.equals(checkPolicyName)){
- sendFlag = true;
- }
- }else if(watchPolicyName.contains("Decision_")){
- if(watchPolicyName.equals(checkPolicyName)){
- sendFlag = true;
- }
- }else{
- sendFlag = true;
}
if(sendFlag){
AnnotationConfigApplicationContext ctx = null;
try {
- to = list.getLoginIds()+"@"+PolicyController.smtpEmailExtension;
+ to = list.getLoginIds()+"@"+PolicyController.getSmtpApplicationName();
to = to.trim();
ctx = new AnnotationConfigApplicationContext();
ctx.register(PolicyNotificationMail.class);
@@ -156,9 +148,11 @@ public class PolicyNotificationMail{
mailMsg.setText(message);
mailSender.send(mimeMessage);
} catch (Exception e) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Exception Occured in Policy Notification" +e);
+ policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Exception Occured in Policy Notification" +e);
}finally{
- ctx.close();
+ if(ctx != null){
+ ctx.close();
+ }
}
}
}
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyRestController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyRestController.java
index 4f0710b3e..582dd6c68 100644
--- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyRestController.java
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyRestController.java
@@ -77,9 +77,10 @@ import com.fasterxml.jackson.databind.SerializationFeature;
@RequestMapping("/")
public class PolicyRestController extends RestrictedBaseController{
- private static final Logger LOGGER = FlexLogger.getLogger(PolicyRestController.class);
+ private static final Logger policyLogger = FlexLogger.getLogger(PolicyRestController.class);
- private String boundary = null;
+ private static final String modal = "model";
+ private static final String importDictionary = "import_dictionary";
@Autowired
CommonClassDao commonClassDao;
@@ -92,38 +93,38 @@ public class PolicyRestController extends RestrictedBaseController{
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode root = mapper.readTree(request.getReader());
- PolicyRestAdapter policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class);
+ PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class);
- if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){
- policyData.isEditPolicy = true;
+ if("file".equals(root.get(PolicyController.getPolicydata()).get(modal).get("type").toString().replace("\"", ""))){
+ policyData.setEditPolicy(true);
}
- if(root.get("policyData").get("model").get("path").size() != 0){
+ if(root.get(PolicyController.getPolicydata()).get(modal).get("path").size() != 0){
String dirName = "";
- for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){
- dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator;
+ for(int i = 0; i < root.get(PolicyController.getPolicydata()).get(modal).get("path").size(); i++){
+ dirName = dirName.replace("\"", "") + root.get(PolicyController.getPolicydata()).get(modal).get("path").get(i).toString().replace("\"", "") + File.separator;
}
- if(policyData.isEditPolicy){
+ if(policyData.isEditPolicy()){
policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator)));
}else{
- policyData.setDomainDir(dirName + root.get("policyData").get("model").get("name").toString().replace("\"", ""));
+ policyData.setDomainDir(dirName + root.get(PolicyController.getPolicydata()).get(modal).get("name").toString().replace("\"", ""));
}
}else{
- String domain = root.get("policyData").get("model").get("name").toString();
+ String domain = root.get(PolicyController.getPolicydata()).get("model").get("name").toString();
if(domain.contains("/")){
- domain = domain.substring(0, domain.lastIndexOf("/")).replace("/", File.separator);
+ domain = domain.substring(0, domain.lastIndexOf('/')).replace("/", File.separator);
}
domain = domain.replace("\"", "");
policyData.setDomainDir(domain);
}
if(policyData.getConfigPolicyType() != null){
- if(policyData.getConfigPolicyType().equalsIgnoreCase("ClosedLoop_Fault")){
+ if("ClosedLoop_Fault".equalsIgnoreCase(policyData.getConfigPolicyType())){
CreateClosedLoopFaultController faultController = new CreateClosedLoopFaultController();
policyData = faultController.setDataToPolicyRestAdapter(policyData, root);
- }else if(policyData.getConfigPolicyType().equalsIgnoreCase("Firewall Config")){
+ }else if("Firewall Config".equalsIgnoreCase(policyData.getConfigPolicyType())){
CreateFirewallController fwController = new CreateFirewallController();
policyData = fwController.setDataToPolicyRestAdapter(policyData);
- }else if(policyData.getConfigPolicyType().equalsIgnoreCase("Micro Service")){
+ }else if("Micro Service".equalsIgnoreCase(policyData.getConfigPolicyType())){
CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController();
policyData = msController.setDataToPolicyRestAdapter(policyData, root);
}
@@ -134,34 +135,34 @@ public class PolicyRestController extends RestrictedBaseController{
String result;
String body = PolicyUtils.objectToJsonString(policyData);
String uri = request.getRequestURI();
- ResponseEntity<?> responseEntity = sendToPAP(body, uri, request, HttpMethod.POST);
- if(responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)){
+ ResponseEntity<?> responseEntity = sendToPAP(body, uri, HttpMethod.POST);
+ if(responseEntity != null && responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)){
result = "PolicyExists";
- }else{
+ }else if(responseEntity != null){
result = responseEntity.getBody().toString();
- String policyName = responseEntity.getHeaders().get("policyName").get(0).toString();
- if(policyData.isEditPolicy){
- if(result.equalsIgnoreCase("success")){
- PolicyNotificationMail email = new PolicyNotificationMail();
- String mode = "EditPolicy";
- String watchPolicyName = policyName.replace(".xml", "");
- String version = watchPolicyName.substring(watchPolicyName.lastIndexOf(".")+1);
- watchPolicyName = watchPolicyName.substring(0, watchPolicyName.lastIndexOf(".")).replace(".", File.separator);
- String policyVersionName = watchPolicyName.replace(".", File.separator);
- watchPolicyName = watchPolicyName + "." + version + ".xml";
- PolicyVersion entityItem = new PolicyVersion();
- entityItem.setPolicyName(policyVersionName);
- entityItem.setActiveVersion(Integer.parseInt(version));
- entityItem.setModifiedBy(userId);
- email.sendMail(entityItem, watchPolicyName, mode, commonClassDao);
- }
+ String policyName = responseEntity.getHeaders().get("policyName").get(0);
+ if(policyData.isEditPolicy() && "success".equalsIgnoreCase(result)){
+ PolicyNotificationMail email = new PolicyNotificationMail();
+ String mode = "EditPolicy";
+ String watchPolicyName = policyName.replace(".xml", "");
+ String version = watchPolicyName.substring(watchPolicyName.lastIndexOf('.')+1);
+ watchPolicyName = watchPolicyName.substring(0, watchPolicyName.lastIndexOf('.')).replace(".", File.separator);
+ String policyVersionName = watchPolicyName.replace(".", File.separator);
+ watchPolicyName = watchPolicyName + "." + version + ".xml";
+ PolicyVersion entityItem = new PolicyVersion();
+ entityItem.setPolicyName(policyVersionName);
+ entityItem.setActiveVersion(Integer.parseInt(version));
+ entityItem.setModifiedBy(userId);
+ email.sendMail(entityItem, watchPolicyName, mode, commonClassDao);
}
+ }else{
+ result = "Response is null from PAP";
}
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
+ response.setCharacterEncoding(PolicyController.getCharacterencoding());
+ response.setContentType(PolicyController.getContenttype());
+ request.setCharacterEncoding(PolicyController.getCharacterencoding());
PrintWriter out = response.getWriter();
String responseString = mapper.writeValueAsString(result);
@@ -172,17 +173,16 @@ public class PolicyRestController extends RestrictedBaseController{
}
- private ResponseEntity<?> sendToPAP(String body, String requestURI, HttpServletRequest request, HttpMethod method) throws Exception{
- String papUrl = PolicyController.papUrl;
+ private ResponseEntity<?> sendToPAP(String body, String requestURI, HttpMethod method){
+ String papUrl = PolicyController.getPapUrl();
String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS);
- LOGGER.info("User Id is " + papID + "Pass is: " + papPass);
Base64.Encoder encoder = Base64.getEncoder();
String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Basic " + encoding);
- headers.set("Content-Type", "application/json");
+ headers.set("Content-Type", PolicyController.getContenttype());
RestTemplate restTemplate = new RestTemplate();
HttpEntity<?> requestEntity = new HttpEntity<>(body, headers);
@@ -190,55 +190,52 @@ public class PolicyRestController extends RestrictedBaseController{
HttpClientErrorException exception = null;
try{
- result = ((ResponseEntity<?>) restTemplate.exchange(papUrl + requestURI, method, requestEntity, String.class));
+ result = restTemplate.exchange(papUrl + requestURI, method, requestEntity, String.class);
}catch(Exception e){
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e);
+ policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e);
exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
- if(e.getMessage().equals("409 Conflict")){
- return (ResponseEntity<?>) ResponseEntity.ok(HttpServletResponse.SC_CONFLICT);
+ if("409 Conflict".equals(e.getMessage())){
+ return ResponseEntity.ok(HttpServletResponse.SC_CONFLICT);
}
}
if(exception != null && exception.getStatusCode()!=null){
if(exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){
String message = XACMLErrorConstants.ERROR_PERMISSIONS +":"+exception.getStatusCode()+":" + "ERROR_AUTH_GET_PERM" ;
- LOGGER.error(message);
- throw new Exception(message, exception);
+ policyLogger.error(message);
}
if(exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)){
String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
- LOGGER.error(message);
- throw new Exception(message, exception);
+ policyLogger.error(message);
}
if(exception.getStatusCode().equals(HttpStatus.NOT_FOUND)){
String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + exception;
- LOGGER.error(message);
- throw new Exception(message, exception);
+ policyLogger.error(message);
}
String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
- LOGGER.error(message);
- throw new Exception(message, exception);
+ policyLogger.error(message);
}
return result;
}
- private String callPAP(HttpServletRequest request, HttpServletResponse response, String method, String uri){
- String papUrl = PolicyController.papUrl;
+ private String callPAP(HttpServletRequest request , String method, String uriValue){
+ String uri = uriValue;
+ String boundary = null;
+ String papUrl = PolicyController.getPapUrl();
String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS);
- LOGGER.info("User Id is " + papID + "Pass is: " + papPass);
-
+
Base64.Encoder encoder = Base64.getEncoder();
String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Basic " + encoding);
- headers.set("Content-Type", "application/json");
+ headers.set("Content-Type", PolicyController.getContenttype());
HttpURLConnection connection = null;
List<FileItem> items;
FileItem item = null;
File file = null;
- if(uri.contains("import_dictionary")){
+ if(uri.contains(importDictionary)){
try {
items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
item = items.get(0);
@@ -246,7 +243,7 @@ public class PolicyRestController extends RestrictedBaseController{
String newFile = file.toString();
uri = uri +"&dictionaryName="+newFile;
} catch (Exception e2) {
- LOGGER.error("Exception Occured while calling PAP with import dictionary request"+e2);
+ policyLogger.error("Exception Occured while calling PAP with import dictionary request"+e2);
}
}
@@ -262,15 +259,15 @@ public class PolicyRestController extends RestrictedBaseController{
if(!uri.contains("searchPolicy?action=delete&")){
- if(!(uri.endsWith("set_BRMSParamData") || uri.contains("import_dictionary"))){
- connection.setRequestProperty("Content-Type","application/json");
+ if(!(uri.endsWith("set_BRMSParamData") || uri.contains(importDictionary))){
+ connection.setRequestProperty("Content-Type",PolicyController.getContenttype());
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode root = null;
try {
root = mapper.readTree(request.getReader());
}catch (Exception e1) {
- LOGGER.error("Exception Occured while calling PAP"+e1);
+ policyLogger.error("Exception Occured while calling PAP"+e1);
}
ObjectMapper mapper1 = new ObjectMapper();
@@ -285,14 +282,14 @@ public class PolicyRestController extends RestrictedBaseController{
// send current configuration
try (OutputStream os = connection.getOutputStream()) {
int count = IOUtils.copy((InputStream) content, os);
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("copied to output, bytes=" + count);
+ if (policyLogger.isDebugEnabled()) {
+ policyLogger.debug("copied to output, bytes=" + count);
}
}
}
}else{
if(uri.endsWith("set_BRMSParamData")){
- connection.setRequestProperty("Content-Type","application/json");
+ connection.setRequestProperty("Content-Type",PolicyController.getContenttype());
try (OutputStream os = connection.getOutputStream()) {
IOUtils.copy((InputStream) request.getInputStream(), os);
}
@@ -319,34 +316,26 @@ public class PolicyRestController extends RestrictedBaseController{
scanner.useDelimiter("\\A");
responseJson = scanner.hasNext() ? scanner.next() : "";
scanner.close();
- LOGGER.info("JSON response from PAP: " + responseJson);
+ policyLogger.info("JSON response from PAP: " + responseJson);
return responseJson;
}
} catch (Exception e) {
- LOGGER.error("Exception Occured"+e);
+ policyLogger.error("Exception Occured"+e);
}finally{
- if(file != null){
- if(file.exists()){
- file.delete();
- }
+ if(file != null && file.exists() && file.delete()){
+ policyLogger.info("File Deleted Successfully");
}
if (connection != null) {
try {
// For some reason trying to get the inputStream from the connection
// throws an exception rather than returning null when the InputStream does not exist.
- InputStream is = null;
- try {
- is = connection.getInputStream();
- } catch (Exception e1) {
- // ignore this
- }
+ InputStream is = connection.getInputStream();
if (is != null) {
is.close();
}
-
} catch (IOException ex) {
- LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
+ policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
}
connection.disconnect();
}
@@ -357,18 +346,24 @@ public class PolicyRestController extends RestrictedBaseController{
@RequestMapping(value={"/getDictionary/*"}, method={RequestMethod.GET})
public void getDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{
String uri = request.getRequestURI().replace("/getDictionary", "");
- String body = sendToPAP(null, uri, request, HttpMethod.GET).getBody().toString();
+ String body = null;
+ ResponseEntity<?> responseEntity = sendToPAP(null, uri, HttpMethod.GET);
+ if(responseEntity != null){
+ body = responseEntity.getBody().toString();
+ }else{
+ body = "";
+ }
response.getWriter().write(body);
}
@RequestMapping(value={"/saveDictionary/*/*"}, method={RequestMethod.POST})
public ModelAndView saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{
String uri = request.getRequestURI().replace("/saveDictionary", "");
- if(uri.contains("import_dictionary")){
+ if(uri.contains(importDictionary)){
String userId = UserUtils.getUserSession(request).getOrgUserId();
uri = uri+ "?userId=" +userId;
}
- String body = callPAP(request, response, "POST", uri.replaceFirst("/", "").trim());
+ String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
response.getWriter().write(body);
return null;
}
@@ -376,7 +371,7 @@ public class PolicyRestController extends RestrictedBaseController{
@RequestMapping(value={"/deleteDictionary/*/*"}, method={RequestMethod.POST})
public ModelAndView deletetDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{
String uri = request.getRequestURI().replace("/deleteDictionary", "");
- String body = callPAP(request, response, "POST", uri.replaceFirst("/", "").trim());
+ String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
response.getWriter().write(body);
return null;
}
@@ -385,7 +380,7 @@ public class PolicyRestController extends RestrictedBaseController{
public ModelAndView searchDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{
Object resultList = null;
String uri = request.getRequestURI();
- String body = callPAP(request, response, "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");
@@ -395,8 +390,8 @@ public class PolicyRestController extends RestrictedBaseController{
resultList = json.get("policyresult");
}
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
+ response.setCharacterEncoding(PolicyController.getCharacterencoding());
+ response.setContentType(PolicyController.getContenttype());
PrintWriter out = response.getWriter();
JSONObject j = new JSONObject("{result: " + resultList + "}");
out.write(j.toString());
@@ -407,7 +402,7 @@ public class PolicyRestController extends RestrictedBaseController{
public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{
Object resultList = null;
String uri = request.getRequestURI()+"?action=search";
- String body = callPAP(request, response, "POST", uri.replaceFirst("/", "").trim());
+ String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
JSONObject json = new JSONObject(body);
try{
@@ -416,6 +411,7 @@ public class PolicyRestController extends RestrictedBaseController{
List<String> data = new ArrayList<>();
data.add("Elastic Search Server is down");
resultList = data;
+ policyLogger.error("Exception Occured while searching for Policy in Elastic Database" +e);
}
response.setCharacterEncoding("UTF-8");
@@ -430,7 +426,7 @@ public class PolicyRestController extends RestrictedBaseController{
public void deleteElasticData(String fileName){
String uri = "searchPolicy?action=delete&policyName='"+fileName+"'";
- callPAP(null, null, "POST", uri.trim());
+ callPAP(null, "POST", uri.trim());
}
} \ No newline at end of file
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/RESTfulPAPEngine.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/RESTfulPAPEngine.java
index 6c970ad59..090476a93 100644
--- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/RESTfulPAPEngine.java
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/RESTfulPAPEngine.java
@@ -69,6 +69,8 @@ import org.openecomp.policy.common.logging.flexlogger.Logger;
*/
public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyEngine {
private static final Logger LOGGER = FlexLogger.getLogger(RESTfulPAPEngine.class);
+
+ private static final String groupID = "groupId=";
//
// URL of the PAP Servlet that this Admin Console talks to
@@ -113,28 +115,26 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
@Override
public EcompPDPGroup getDefaultGroup() throws PAPException {
- EcompPDPGroup newGroup = (EcompPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, "groupId=", "default=");
- return newGroup;
+ return (EcompPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID, "default=");
}
@Override
public void SetDefaultGroup(EcompPDPGroup group) throws PAPException {
- sendToPAP("POST", null, null, null, "groupId=" + group.getId(), "default=true");
+ sendToPAP("POST", null, null, null, groupID + group.getId(), "default=true");
}
@SuppressWarnings("unchecked")
@Override
public Set<EcompPDPGroup> getEcompPDPGroups() throws PAPException {
Set<EcompPDPGroup> newGroupSet;
- newGroupSet = (Set<EcompPDPGroup>) this.sendToPAP("GET", null, Set.class, StdPDPGroup.class, "groupId=");
+ newGroupSet = (Set<EcompPDPGroup>) this.sendToPAP("GET", null, Set.class, StdPDPGroup.class, groupID);
return Collections.unmodifiableSet(newGroupSet);
}
@Override
public EcompPDPGroup getGroup(String id) throws PAPException {
- EcompPDPGroup newGroup = (EcompPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, "groupId=" + id);
- return newGroup;
+ return (EcompPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID + id);
}
@Override
@@ -146,10 +146,10 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
escapedName = URLEncoder.encode(name, "UTF-8");
escapedDescription = URLEncoder.encode(description, "UTF-8");
} catch (UnsupportedEncodingException e) {
- throw new PAPException("Unable to send name or description to PAP: " + e.getMessage());
+ throw new PAPException("Unable to send name or description to PAP: " + e.getMessage() +e);
}
- this.sendToPAP("POST", null, null, null, "groupId=", "groupName="+escapedName, "groupDescription=" + escapedDescription);
+ this.sendToPAP("POST", null, null, null, groupID, "groupName="+escapedName, "groupDescription=" + escapedDescription);
}
@@ -178,7 +178,7 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
// now update the group object on the PAP
- sendToPAP("PUT", group, null, null, "groupId=" + group.getId());
+ sendToPAP("PUT", group, null, null, groupID + group.getId());
} catch (Exception e) {
String message = "Unable to PUT policy '" + group.getId() + "', e:" + e;
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
@@ -194,7 +194,7 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
if (newGroup != null) {
moveToGroupString = "movePDPsToGroupId=" + newGroup.getId();
}
- sendToPAP("DELETE", null, null, null, "groupId=" + group.getId(), moveToGroupString);
+ sendToPAP("DELETE", null, null, null, groupID + group.getId(), moveToGroupString);
}
@Override
@@ -204,41 +204,39 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
public EcompPDPGroup getPDPGroup(String pdpId) throws PAPException {
- EcompPDPGroup newGroup = (EcompPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, "groupId=", "pdpId=" + pdpId, "getPDPGroup=");
- return newGroup;
+ return (EcompPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID, "pdpId=" + pdpId, "getPDPGroup=");
}
@Override
public EcompPDP getPDP(String pdpId) throws PAPException {
- EcompPDP newPDP = (EcompPDP)sendToPAP("GET", null, null, StdPDP.class, "groupId=", "pdpId=" + pdpId);
- return newPDP;
+ return (EcompPDP)sendToPAP("GET", null, null, StdPDP.class, groupID, "pdpId=" + pdpId);
}
@Override
public void newPDP(String id, EcompPDPGroup group, String name, String description, int jmxport) throws PAPException,
NullPointerException {
StdPDP newPDP = new StdPDP(id, name, description, jmxport);
- sendToPAP("PUT", newPDP, null, null, "groupId=" + group.getId(), "pdpId=" + id);
+ sendToPAP("PUT", newPDP, null, null, groupID + group.getId(), "pdpId=" + id);
return;
}
@Override
public void movePDP(EcompPDP pdp, EcompPDPGroup newGroup) throws PAPException {
- sendToPAP("POST", null, null, null, "groupId=" + newGroup.getId(), "pdpId=" + pdp.getId());
+ sendToPAP("POST", null, null, null, groupID + newGroup.getId(), "pdpId=" + pdp.getId());
return;
}
@Override
public void updatePDP(EcompPDP pdp) throws PAPException {
EcompPDPGroup group = getPDPGroup(pdp);
- sendToPAP("PUT", pdp, null, null, "groupId=" + group.getId(), "pdpId=" + pdp.getId());
+ sendToPAP("PUT", pdp, null, null, groupID + group.getId(), "pdpId=" + pdp.getId());
return;
}
@Override
public void removePDP(EcompPDP pdp) throws PAPException {
EcompPDPGroup group = getPDPGroup(pdp);
- sendToPAP("DELETE", null, null, null, "groupId=" + group.getId(), "pdpId=" + pdp.getId());
+ sendToPAP("DELETE", null, null, null, groupID + group.getId(), "pdpId=" + pdp.getId());
return;
}
@@ -285,7 +283,7 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
public void copyFile(String policyId, EcompPDPGroup group, InputStream policy) throws PAPException {
// send the policy file to the PAP Servlet
try {
- sendToPAP("POST", policy, null, null, "groupId=" + group.getId(), "policyId="+policyId);
+ sendToPAP("POST", policy, null, null, groupID + group.getId(), "policyId="+policyId);
} catch (Exception e) {
String message = "Unable to PUT policy '" + policyId + "', e:" + e;
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
@@ -325,8 +323,7 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
*/
public PDPStatus getStatus(EcompPDP pdp) throws PAPException {
- StdPDPStatus status = (StdPDPStatus)sendToPAP("GET", pdp, null, StdPDPStatus.class);
- return status;
+ return (StdPDPStatus)sendToPAP("GET", pdp, null, StdPDPStatus.class);
}
@@ -356,7 +353,6 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
LOGGER.info("User Id is " + papID);
String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS);
- LOGGER.info("Pass is: " + papPass);
Base64.Encoder encoder = Base64.getEncoder();
String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
LOGGER.info("Encoding for the PAP is: " + encoding);
@@ -419,7 +415,6 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
}
} catch (Exception e) {
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to write content in '" + method + "'", e);
- throw e;
}
} else {
// The content is an object to be encoded in JSON
@@ -504,20 +499,14 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
throw new PAPException("Request/Response threw :" + e);
} finally {
// cleanup the connection
- if (connection != null) {
+ if (connection != null) {
try {
// For some reason trying to get the inputStream from the connection
// throws an exception rather than returning null when the InputStream does not exist.
- InputStream is = null;
- try {
- is = connection.getInputStream();
- } catch (Exception e1) {
- // ignore this
- }
+ InputStream is = connection.getInputStream();
if (is != null) {
is.close();
}
-
} catch (IOException ex) {
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
}
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/components/HumanPolicyComponent.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/components/HumanPolicyComponent.java
index f788fb673..b67cb261d 100644
--- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/components/HumanPolicyComponent.java
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/components/HumanPolicyComponent.java
@@ -103,6 +103,10 @@ public class HumanPolicyComponent{
private static File policyFile;
+ private HumanPolicyComponent(){
+ //Default Constructor
+ }
+
public static JSONObject DescribePolicy(final File policyFile) {
if (LOGGER.isTraceEnabled())
LOGGER.trace("ENTER");
@@ -298,7 +302,7 @@ class HtmlProcessor extends SimpleCallback {
AttributeIdentifiers value = entry.getValue();
htmlOut.println("<tr>");
htmlOut.print("<td><a name=\"" + entry.getKey() + "\"></a>" + value.category + "</td>");
- htmlOut.print("<td>" + value.type + "</td>");
+ htmlOut.print("<td>" + value.getType() + "</td>");
htmlOut.print("<td>" + value.id + "</td>");
htmlOut.println("</tr>");
}
@@ -654,7 +658,7 @@ class HtmlProcessor extends SimpleCallback {
if (assignmentObject instanceof AttributeValueType) {
AttributeValueType avt = (AttributeValueType) assignmentObject;
if (attributeIdentifiers != null) {
- attributeIdentifiers.type = avt.getDataType();
+ attributeIdentifiers.setType(avt.getDataType());
}
int numContent = avt.getContent().size();
int countContent = 0;
@@ -968,12 +972,20 @@ class HtmlProcessor extends SimpleCallback {
class AttributeIdentifiers {
public final String category;
- public String type;
+ private String type;
public final String id;
public AttributeIdentifiers(String category, String type, String id) {
this.category = category;
- this.type = type;
+ this.setType(type);
this.id = id;
}
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
}
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/conf/HibernateSession.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/conf/HibernateSession.java
index 9f7659d15..22ecb0e00 100644
--- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/conf/HibernateSession.java
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/conf/HibernateSession.java
@@ -44,11 +44,11 @@ public class HibernateSession{
static {
try {
Properties prop= new Properties();
- prop.setProperty("hibernate.connection.url", PolicyController.logdbUrl);
- prop.setProperty("hibernate.connection.username", PolicyController.logdbUserName);
- prop.setProperty("hibernate.connection.password", PolicyController.logdbPassword);
- prop.setProperty("dialect", PolicyController.logdbDialect);
- prop.setProperty("hibernate.connection.driver_class", PolicyController.logdbDriver);
+ 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.openecomp.policy.*").addProperties(prop)
.addAnnotatedClass(SystemLogDB.class).buildSessionFactory();
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AdminTabController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AdminTabController.java
index 6824101df..650b5872f 100644
--- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AdminTabController.java
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AdminTabController.java
@@ -51,9 +51,25 @@ public class AdminTabController extends RestrictedBaseController{
private static final Logger LOGGER = FlexLogger.getLogger(AdminTabController.class);
+ private static CommonClassDao commonClassDao;
+
+ public static CommonClassDao getCommonClassDao() {
+ return commonClassDao;
+ }
+
+ public static void setCommonClassDao(CommonClassDao commonClassDao) {
+ AdminTabController.commonClassDao = commonClassDao;
+ }
+
@Autowired
- CommonClassDao commonClassDao;
+ private AdminTabController(CommonClassDao commonClassDao){
+ AdminTabController.commonClassDao = commonClassDao;
+ }
+ public AdminTabController() {
+ //default constructor
+ }
+
@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{
@@ -92,6 +108,7 @@ public class AdminTabController extends RestrictedBaseController{
return null;
}
catch (Exception e){
+ LOGGER.error("Exception Occured"+e);
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AutoPushController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AutoPushController.java
index 17e8f89f2..a4387d19a 100644
--- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AutoPushController.java
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AutoPushController.java
@@ -83,8 +83,16 @@ public class AutoPushController extends RestrictedBaseController{
private PDPGroupContainer container;
protected List<EcompPDPGroup> groups = Collections.synchronizedList(new ArrayList<EcompPDPGroup>());
- private static PDPPolicyContainer policyContainer;
- Set<PDPPolicy> selectedPolicies;
+ private PDPPolicyContainer policyContainer;
+
+ private PolicyController policyController;
+ public PolicyController getPolicyController() {
+ return policyController;
+ }
+
+ public void setPolicyController(PolicyController policyController) {
+ this.policyController = policyController;
+ }
private List<Object> data;
@@ -92,7 +100,8 @@ public class AutoPushController extends RestrictedBaseController{
synchronized(this.groups) {
this.groups.clear();
try {
- this.groups.addAll(PolicyController.getPapEngine().getEcompPDPGroups());
+ PolicyController controller = getPolicyControllerInstance();
+ this.groups.addAll(controller.getPapEngine().getEcompPDPGroups());
} catch (PAPException e) {
String message = "Unable to retrieve Groups from server: " + e;
logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message);
@@ -101,6 +110,10 @@ public class AutoPushController extends RestrictedBaseController{
}
}
+ private PolicyController getPolicyControllerInstance(){
+ return policyController != null ? getPolicyController() : new PolicyController();
+ }
+
@RequestMapping(value={"/get_AutoPushPoliciesContainerData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response){
try{
@@ -110,7 +123,8 @@ public class AutoPushController extends RestrictedBaseController{
String userId = UserUtils.getUserSession(request).getOrgUserId();
Map<String, Object> model = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
- List<Object> userRoles = PolicyController.getRoles(userId);
+ PolicyController controller = policyController != null ? getPolicyController() : new PolicyController();
+ List<Object> userRoles = controller.getRoles(userId);
roles = new ArrayList<>();
scopes = new HashSet<>();
for(Object role: userRoles){
@@ -163,12 +177,13 @@ public class AutoPushController extends RestrictedBaseController{
try {
ArrayList<Object> selectedPDPS = new ArrayList<>();
ArrayList<String> selectedPoliciesInUI = new ArrayList<>();
- this.groups.addAll(PolicyController.getPapEngine().getEcompPDPGroups());
+ PolicyController controller = getPolicyControllerInstance();
+ this.groups.addAll(controller.getPapEngine().getEcompPDPGroups());
ObjectMapper mapper = new ObjectMapper();
- this.container = new PDPGroupContainer(PolicyController.getPapEngine());
+ this.container = new PDPGroupContainer(controller.getPapEngine());
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode root = mapper.readTree(request.getReader());
- AutoPushTabAdapter adapter = (AutoPushTabAdapter) mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
+ AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class);
for (Object pdpGroupId : adapter.getPdpDatas()) {
LinkedHashMap<?, ?> selectedPDP = (LinkedHashMap<?, ?>)pdpGroupId;
for(EcompPDPGroup pdpGroup : this.groups){
@@ -220,10 +235,8 @@ public class AutoPushController extends RestrictedBaseController{
}else if(dbCheckName.contains("Decision_")){
dbCheckName = dbCheckName.replace(".Decision_", ":Decision_");
}
- PolicyController controller = new PolicyController();
String[] split = dbCheckName.split(":");
String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'";
- System.out.println(query);
List<Object> queryData = controller.getDataByQuery(query);
PolicyEntity policyEntity = (PolicyEntity) queryData.get(0);
File temp = new File(name);
@@ -237,7 +250,6 @@ public class AutoPushController extends RestrictedBaseController{
selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI);
} catch (IOException e) {
logger.error("Unable to create policy '" + name + "': "+ e.getMessage());
- //AdminNotification.warn("Unable to create policy '" + id + "': " + e.getMessage());
}
StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId;
if (selectedPolicy != null) {
@@ -249,7 +261,7 @@ public class AutoPushController extends RestrictedBaseController{
}
// copy policy to PAP
try {
- PolicyController.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
+ controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId);
} catch (PAPException e) {
logger.error("Exception Occured"+e);
return null;
@@ -317,7 +329,8 @@ public class AutoPushController extends RestrictedBaseController{
@RequestMapping(value={"/auto_Push/remove_GroupPolicies.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
try {
- this.container = new PDPGroupContainer(PolicyController.getPapEngine());
+ 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());
@@ -327,10 +340,10 @@ public class AutoPushController extends RestrictedBaseController{
if(removePolicyData.size() > 0){
for(int i = 0 ; i < removePolicyData.size(); i++){
String data = removePolicyData.get(i).toString();
- AutoPushController.policyContainer.removeItem(data);
+ this.policyContainer.removeItem(data);
}
Set<PDPPolicy> changedPolicies = new HashSet<>();
- changedPolicies.addAll((Collection<PDPPolicy>) AutoPushController.policyContainer.getItemIds());
+ changedPolicies.addAll((Collection<PDPPolicy>) this.policyContainer.getItemIds());
StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(), group.getDescription(),null);
updatedGroupObject.setPolicies(changedPolicies);
updatedGroupObject.setEcompPdps(group.getEcompPdps());
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java
index daab6e378..68dff19bd 100644
--- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java
@@ -70,7 +70,7 @@ import org.openecomp.policy.common.logging.flexlogger.Logger;
@Controller
@RequestMapping("/")
public class CreateBRMSParamController extends RestrictedBaseController {
- private static final Logger logger = FlexLogger.getLogger(CreateBRMSParamController.class);
+ private static final Logger policyLogger = FlexLogger.getLogger(CreateBRMSParamController.class);
private static CommonClassDao commonClassDao;
@@ -80,10 +80,12 @@ public class CreateBRMSParamController extends RestrictedBaseController {
}
public CreateBRMSParamController(){}
- protected PolicyRestAdapter policyAdapter = null;
- private ArrayList<Object> attributeList;
+ protected PolicyRestAdapter policyAdapter = null;
private HashMap<String, String> dynamicLayoutMap;
+
+ private static String brmsTemplateVlaue = "<$%BRMSParamTemplate=";
+ private static String String = "String";
@RequestMapping(value={"/policyController/getBRMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
@@ -92,11 +94,11 @@ public class CreateBRMSParamController extends RestrictedBaseController {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode root = mapper.readTree(request.getReader());
- String rule = findRule(root.get("policyData").toString().replaceAll("^\"|\"$", ""));
+ String rule = findRule(root.get(PolicyController.getPolicydata()).toString().replaceAll("^\"|\"$", ""));
generateUI(rule);
- response.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
+ response.setCharacterEncoding(PolicyController.getCharacterencoding());
+ response.setContentType(PolicyController.getContenttype());
+ request.setCharacterEncoding(PolicyController.getCharacterencoding());
PrintWriter out = response.getWriter();
String responseString = mapper.writeValueAsString(dynamicLayoutMap);
@@ -119,7 +121,7 @@ public class CreateBRMSParamController extends RestrictedBaseController {
protected void generateUI(String rule) {
if(rule!=null){
try {
- String params = "";
+ StringBuilder params = new StringBuilder("");
Boolean flag = false;
Boolean comment = false;
String lines[] = rule.split("\n");
@@ -142,6 +144,7 @@ public class CreateBRMSParamController extends RestrictedBaseController {
line = line.split("\\/\\*")[0]
+ line.split("\\*\\/")[1].replace("*/", "");
} catch (Exception e) {
+ policyLogger.info("Just for Logging"+e);
line = line.split("\\/\\*")[0];
}
} else {
@@ -153,6 +156,7 @@ public class CreateBRMSParamController extends RestrictedBaseController {
try {
line = line.split("\\*\\/")[1].replace("*/", "");
} catch (Exception e) {
+ policyLogger.info("Just for Logging"+e);
line = "";
}
}
@@ -160,38 +164,38 @@ public class CreateBRMSParamController extends RestrictedBaseController {
continue;
}
if (flag) {
- params = params + line;
+ params.append(line);
}
if (line.contains("declare Params")) {
- params = params + line;
+ params.append(line);
flag = true;
}
if (line.contains("end") && flag) {
break;
}
}
- params = params.replace("declare Params", "").replace("end", "")
- .replaceAll("\\s+", "");
- String[] components = params.split(":");
+ params = new StringBuilder(params.toString().replace("declare Params", "").replace("end", "").replaceAll("\\s+", ""));
+ String[] components = params.toString().split(":");
String caption = "";
for (int i = 0; i < components.length; i++) {
String type = "";
if (i == 0) {
caption = components[i];
}
- if(caption.equals("")){
+ if("".equals(caption)){
break;
}
String nextComponent = "";
try {
nextComponent = components[i + 1];
} catch (Exception e) {
+ policyLogger.info("Just for Logging"+e);
nextComponent = components[i];
}
- if (nextComponent.startsWith("String")) {
+ if (nextComponent.startsWith(String)) {
type = "String";
createField(caption, type);
- caption = nextComponent.replace("String", "");
+ caption = nextComponent.replace(String, "");
} else if (nextComponent.startsWith("int")) {
type = "int";
createField(caption, type);
@@ -199,7 +203,7 @@ public class CreateBRMSParamController extends RestrictedBaseController {
}
}
} catch (Exception e) {
- logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
+ policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
}
}
}
@@ -208,10 +212,11 @@ public class CreateBRMSParamController extends RestrictedBaseController {
dynamicLayoutMap.put(caption, type);
}
-
- @SuppressWarnings("unchecked")
+ /*
+ * 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
+ */
public void prePopulateBRMSParamPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
- attributeList = new ArrayList<>();
dynamicLayoutMap = new HashMap<>();
if (policyAdapter.getPolicyData() instanceof PolicyType) {
PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
@@ -219,101 +224,116 @@ public class CreateBRMSParamController extends RestrictedBaseController {
// policy name value is the policy name without any prefix and
// Extensions.
String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Param_") + 11);
- if (logger.isDebugEnabled()) {
- logger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName());
+ 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("Just for Logging"+e);
description = policy.getDescription();
}
policyAdapter.setPolicyDescription(description);
- // Set Attributes.
- AdviceExpressionsType expressionTypes = ((RuleType)policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions();
- for( AdviceExpressionType adviceExpression: expressionTypes.getAdviceExpression()){
- for(AttributeAssignmentExpressionType attributeAssignment: adviceExpression.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();
- 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<String>(Arrays.asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(",")));
- if(dependencies.contains("")){
- dependencies.remove("");
- }
- policyAdapter.setBrmsDependency(dependencies);
- }else if(attributeAssignment.getAttributeId().startsWith("controller:")){
- policyAdapter.setBrmsController(attributeAssignment.getAttributeId().replace("controller:", ""));
- }
- }
- policyAdapter.setAttributes(attributeList);
- }
+ setDataAdapterFromAdviceExpressions(policy, policyAdapter);
paramUIGenerate(policyAdapter, entity);
// Get the target data under policy.
policyAdapter.setDynamicLayoutMap(dynamicLayoutMap);
if(policyAdapter.getDynamicLayoutMap().size() > 0){
LinkedHashMap<String,String> drlRule = new LinkedHashMap<>();
for(Object keyValue: policyAdapter.getDynamicLayoutMap().keySet()){
- drlRule.put(keyValue.toString(), policyAdapter.getDynamicLayoutMap().get(keyValue).toString());
+ drlRule.put(keyValue.toString(), policyAdapter.getDynamicLayoutMap().get(keyValue));
}
policyAdapter.setRuleData(drlRule);
}
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 (attributeId.equals("RiskType")){
- policyAdapter.setRiskType(value);
- }
- if (attributeId.equals("RiskLevel")){
- policyAdapter.setRiskLevel(value);
- }
- if (attributeId.equals("guard")){
- policyAdapter.setGuard(value);
- }
- if (attributeId.equals("TTLDate") && !value.contains("NA")){
- String newDate = convertDate(value, true);
- policyAdapter.setTtlDate(newDate);
- }
- }
- }
- }
+ 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();
+ for( AdviceExpressionType adviceExpression: expressionTypes.getAdviceExpression()){
+ for(AttributeAssignmentExpressionType attributeAssignment: adviceExpression.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();
+ 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(",")));
+ if(dependencies.contains("")){
+ dependencies.remove("");
+ }
+ policyAdapter.setBrmsDependency(dependencies);
+ }else if(attributeAssignment.getAttributeId().startsWith("controller:")){
+ policyAdapter.setBrmsController(attributeAssignment.getAttributeId().replace("controller:", ""));
+ }
+ }
+ policyAdapter.setAttributes(attributeList);
+ }
+ }
+
+ private void setDataToAdapterFromTarget(TargetType target, PolicyRestAdapter policyAdapter){
+ // 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) {
+ setDataToAdapterFromMatchList(matchList, policyAdapter);
}
}
}
}
- }
+ }
+ }
+
+ private void setDataToAdapterFromMatchList(List<MatchType> matchList, PolicyRestAdapter policyAdapter){
+ 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 ("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")){
+ String newDate = convertDate(value, true);
+ policyAdapter.setTtlDate(newDate);
+ }
+ }
}
private String convertDate(String dateTTL, boolean portalType) {
@@ -336,26 +356,24 @@ public class CreateBRMSParamController extends RestrictedBaseController {
String data = entity.getConfigurationData().getConfigBody();
if(data != null){
try {
- String params = "";
+ StringBuilder params = new StringBuilder("");
Boolean flag = false;
Boolean comment = false;
for (String line : data.split("\n")) {
if (line.isEmpty() || line.startsWith("//")) {
continue;
}
- if(line.contains("<$%BRMSParamTemplate=")){
+ if(line.contains(brmsTemplateVlaue)){
String value = line.substring(line.indexOf("<$%"),line.indexOf("%$>"));
- value = value.replace("<$%BRMSParamTemplate=", "");
+ value = value.replace(brmsTemplateVlaue, "");
policyAdapter.setRuleName(value);
}
if (line.startsWith("/*")) {
comment = true;
continue;
}
- if (line.contains("//")) {
- if(!(line.contains("http://") || line.contains("https://"))){
- line = line.split("\\/\\/")[0];
- }
+ if ((line.contains("//"))&&(!(line.contains("http://") || line.contains("https://")))){
+ line = line.split("\\/\\/")[0];
}
if (line.contains("/*")) {
comment = true;
@@ -366,6 +384,7 @@ public class CreateBRMSParamController extends RestrictedBaseController {
+ line.split("\\*\\/")[1].replace(
"*/", "");
} catch (Exception e) {
+ policyLogger.info("Just for Logging"+e);
line = line.split("\\/\\*")[0];
}
} else {
@@ -378,6 +397,7 @@ public class CreateBRMSParamController extends RestrictedBaseController {
line = line.split("\\*\\/")[1]
.replace("*/", "");
} catch (Exception e) {
+ policyLogger.info("Just for Logging"+e);
line = "";
}
}
@@ -385,26 +405,27 @@ public class CreateBRMSParamController extends RestrictedBaseController {
continue;
}
if (flag) {
- params = params + line;
+ params.append(line);
}
if (line.contains("rule") && line.contains(".Params\"")) {
- params = params + line;
+ params.append(line);
flag = true;
}
if (line.contains("end") && flag) {
break;
}
}
- params = params.substring(params.indexOf(".Params\"")+ 8);
- params = params.replaceAll("\\s+", "").replace("salience1000whenthenParamsparams=newParams();","")
+ params = new StringBuilder(params.substring(params.indexOf(".Params\"")+ 8));
+ params = new StringBuilder(params.toString().replaceAll("\\s+", "").replace("salience1000whenthenParamsparams=newParams();","")
.replace("insert(params);end", "")
- .replace("params.set", "");
- String[] components = params.split(";");
+ .replace("params.set", ""));
+ String[] components = params.toString().split("\\);");
if(components!= null && components.length > 0){
for (int i = 0; i < components.length; i++) {
String value = null;
+ components[i] = components[i]+")";
String caption = components[i].substring(0,
- components[i].indexOf("("));
+ components[i].indexOf('('));
caption = caption.substring(0, 1).toLowerCase() + caption.substring(1);
if (components[i].contains("(\"")) {
value = components[i]
@@ -413,8 +434,8 @@ public class CreateBRMSParamController extends RestrictedBaseController {
.replace("(\"", "").replace("\")", "");
} else {
value = components[i]
- .substring(components[i].indexOf("("),
- components[i].indexOf(")"))
+ .substring(components[i].indexOf('('),
+ components[i].indexOf(')'))
.replace("(", "").replace(")", "");
}
dynamicLayoutMap.put(caption, value);
@@ -422,7 +443,7 @@ public class CreateBRMSParamController extends RestrictedBaseController {
}
}
} catch (Exception e) {
- logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage());
+ policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e);
}
}
@@ -436,37 +457,37 @@ public class CreateBRMSParamController extends RestrictedBaseController {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode root = mapper.readTree(request.getReader());
- PolicyRestAdapter policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class);
- policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", ""));
- if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){
- policyData.isEditPolicy = true;
+ 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("\"", ""));
+ if(root.get(PolicyController.getPolicydata()).get("model").get("type").toString().replace("\"", "").equals(PolicyController.getFile())){
+ policyData.setEditPolicy(true);
}
String body = "";
body = "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " +
- "<$%BRMSParamTemplate=" + policyData.getRuleName() + "%$> \n */ \n";
+ brmsTemplateVlaue + policyData.getRuleName() + "%$> \n */ \n";
body = body + findRule((String) policyData.getRuleName()) + "\n";
- String generatedRule = "rule \""+ policyData.getDomainDir().replace("\\", ".") +".Config_BRMS_Param_" + policyData.getPolicyName()+".Params\" \n\tsalience 1000 \n\twhen\n\tthen\n\t\tParams params = new Params();";
+ StringBuilder generatedRule = new StringBuilder();
+ generatedRule.append("rule \""+ policyData.getDomainDir().replace("\\", ".") +".Config_BRMS_Param_" + policyData.getPolicyName()+".Params\" \n\tsalience 1000 \n\twhen\n\tthen\n\t\tParams params = new Params();");
if(policyData.getRuleData().size() > 0){
for(Object keyValue: policyData.getRuleData().keySet()){
String key = keyValue.toString().substring(0, 1).toUpperCase() + keyValue.toString().substring(1);
- if (keyValue.equals("String")) {
- generatedRule = generatedRule + "\n\t\tparams.set"
+ if (String.equals(keyValue)) {
+ generatedRule.append("\n\t\tparams.set"
+ key + "(\""
- + policyData.getRuleData().get(keyValue).toString() + "\");";
+ + policyData.getRuleData().get(keyValue).toString() + "\");");
} else {
- generatedRule = generatedRule + "\n\t\tparams.set"
+ generatedRule.append("\n\t\tparams.set"
+ key + "("
- + policyData.getRuleData().get(keyValue).toString() + ");";
+ + policyData.getRuleData().get(keyValue).toString() + ");");
}
}
}
- generatedRule = generatedRule
- + "\n\t\tinsert(params);\nend";
- logger.info("New rule generated with :" + generatedRule);
- body = body + generatedRule;
+ generatedRule.append("\n\t\tinsert(params);\nend");
+ policyLogger.info("New rule generated with :" + generatedRule.toString());
+ body = body + generatedRule.toString();
// Expand the body.
Map<String,String> copyMap=new HashMap<>();
copyMap.putAll((Map<? extends String, ? extends String>) policyData.getRuleData());
@@ -499,7 +520,7 @@ public class CreateBRMSParamController extends RestrictedBaseController {
out.write(j.toString());
return null;
} catch (Exception e) {
- logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
+ policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
}
return null;
}
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java
index c3daf6d94..f3e313144 100644
--- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java
@@ -104,6 +104,15 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
private static final Logger LOGGER = FlexLogger.getLogger(CreateDcaeMicroServiceController.class);
private static CommonClassDao commonClassDao;
+
+ public static CommonClassDao getCommonClassDao() {
+ return commonClassDao;
+ }
+
+ public static void setCommonClassDao(CommonClassDao commonClassDao) {
+ CreateDcaeMicroServiceController.commonClassDao = commonClassDao;
+ }
+
private MicroServiceModels newModel;
private String newFile;
private String directory;
@@ -238,7 +247,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
}
// Second index of dot should be returned.
- public void stringBetweenDots(String str,String value){
+ public int stringBetweenDots(String str,String value){
String stringToSearch=str;
String[]ss=stringToSearch.split("\\.");
if(ss!=null){
@@ -247,6 +256,8 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
uniqueKeys.add(ss[2]);
}
}
+
+ return uniqueKeys.size();
}
public void stringBetweenDotsForDataFields(String str,String value){
@@ -1338,7 +1349,7 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
private void retreiveDependency(String workingFile, Boolean modelClass) {
- MSModelUtils utils = new MSModelUtils(PolicyController.msEcompName, PolicyController.msPolicyName);
+ MSModelUtils utils = new MSModelUtils(PolicyController.getMsEcompName(), PolicyController.getMsPolicyName());
HashMap<String, MSAttributeObject> tempMap = new HashMap<>();
tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI);
@@ -1402,23 +1413,31 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController {
return list;
}
+ public Map<String, String> getAttributesListRefMap() {
+ return attributesListRefMap;
+ }
+
+ public Map<String, LinkedList<String>> getArrayTextList() {
+ return arrayTextList;
+ }
+
}
class DCAEMicroServiceObject {
- public String service;
- public String location;
- public String uuid;
- public String policyName;
- public String description;
- public String configName;
- public String templateVersion;
- public String version;
- public String priority;
- public String policyScope;
- public String riskType;
- public String riskLevel;
- public String guard = null;
+ private String service;
+ private String location;
+ private String uuid;
+ private String policyName;
+ private String description;
+ private String configName;
+ private String templateVersion;
+ private String version;
+ private String priority;
+ private String policyScope;
+ private String riskType;
+ private String riskLevel;
+ private String guard = null;
public String getGuard() {
return guard;
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DashboardController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DashboardController.java
index 707a65d62..56ff637e9 100644
--- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DashboardController.java
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DashboardController.java
@@ -86,7 +86,18 @@ public class DashboardController extends RestrictedBaseController{
private ArrayList<Object> papStatusData;
private ArrayList<Object> policyActivityData;
+ private PolicyController policyController;
+ public PolicyController getPolicyController() {
+ return policyController;
+ }
+ public void setPolicyController(PolicyController policyController) {
+ this.policyController = policyController;
+ }
+
+ private PolicyController getPolicyControllerInstance(){
+ return policyController != null ? getPolicyController() : new PolicyController();
+ }
@RequestMapping(value={"/get_DashboardLoggingData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
public void getData(HttpServletRequest request, HttpServletResponse response){
@@ -141,7 +152,8 @@ public class DashboardController extends RestrictedBaseController{
Map<String, Object> model = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
- this.pdpConatiner = new PDPGroupContainer(PolicyController.getPapEngine());
+ PolicyController controller = getPolicyControllerInstance();
+ this.pdpConatiner = new PDPGroupContainer(controller.getPapEngine());
addPDPToTable();
model.put("pdpTableDatas", mapper.writeValueAsString(pdpStatusData));
JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
@@ -159,7 +171,8 @@ public class DashboardController extends RestrictedBaseController{
Map<String, Object> model = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
- this.pdpConatiner = new PDPGroupContainer(PolicyController.getPapEngine());
+ PolicyController controller = getPolicyControllerInstance();
+ this.pdpConatiner = new PDPGroupContainer(controller.getPapEngine());
addPolicyToTable();
model.put("policyActivityTableDatas", mapper.writeValueAsString(policyActivityData));
JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
@@ -178,7 +191,8 @@ public class DashboardController extends RestrictedBaseController{
papStatusData = new ArrayList<>();
String papStatus = null;
try {
- Set<EcompPDPGroup> groups = PolicyController.getPapEngine().getEcompPDPGroups();
+ PolicyController controller = getPolicyControllerInstance();
+ Set<EcompPDPGroup> groups = controller.getPapEngine().getEcompPDPGroups();
if (groups == null) {
papStatus = "UNKNOWN";
throw new PAPException("PAP not running");
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PDPController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PDPController.java
index 80820c129..2e9771ec8 100644
--- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PDPController.java
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PDPController.java
@@ -60,23 +60,37 @@ import com.fasterxml.jackson.databind.ObjectMapper;
@RequestMapping({"/"})
public class PDPController extends RestrictedBaseController {
private static final Logger logger = FlexLogger.getLogger(PDPController.class);
-
+
protected List<EcompPDPGroup> groups = Collections.synchronizedList(new ArrayList<EcompPDPGroup>());
private PDPGroupContainer container;
-
+
private static String SUPERADMIN = "super-admin";
private static String SUPEREDITOR = "super-editor";
private static String SUPERGUEST = "super-guest";
-
+
+ private Set<EcompPDPGroup> 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 = null;
List<String> roles = null;
- String userId = UserUtils.getUserSession(request).getOrgUserId();
- List<Object> userRoles = PolicyController.getRoles(userId);
+ String userId = isJunit() ? "Test" : UserUtils.getUserSession(request).getOrgUserId();
+ List<Object> userRoles = controller.getRoles(userId);
roles = new ArrayList<>();
scopes = new HashSet<>();
for(Object role: userRoles){
@@ -94,12 +108,16 @@ public class PDPController extends RestrictedBaseController {
}
}
if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ) {
- this.groups.addAll(PolicyController.getPapEngine().getEcompPDPGroups());
+ if(!junit){
+ this.groups.addAll(controller.getPapEngine().getEcompPDPGroups());
+ }else{
+ this.groups.addAll(this.getGroupsData());
+ }
}else{
if(!userRoles.isEmpty()){
if(!scopes.isEmpty()){
- this.groups.addAll(PolicyController.getPapEngine().getEcompPDPGroups());
- List<EcompPDPGroup> tempGroups = new ArrayList<EcompPDPGroup>();
+ this.groups.addAll(controller.getPapEngine().getEcompPDPGroups());
+ List<EcompPDPGroup> tempGroups = new ArrayList<>();
if(!groups.isEmpty()){
Iterator<EcompPDPGroup> pdpGroup = groups.iterator();
while(pdpGroup.hasNext()){
@@ -138,21 +156,7 @@ public class PDPController extends RestrictedBaseController {
}
}
}
-
- @RequestMapping(value={"/get_PDPGroupContainerData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE)
- public void getPDPGroupContainerData(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){
- logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while retrieving the PDP Group Container data" + e);
- }
- }
-
+
@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{
@@ -166,164 +170,188 @@ public class PDPController extends RestrictedBaseController {
logger.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 ModelAndView savePDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception{
- try {
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- this.container = new PDPGroupContainer(PolicyController.getPapEngine());
- 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);
- }
-
+ public ModelAndView savePDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception{
+ 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());
+ 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();
logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while creating the PDP Group" + message);
}
-
-
- 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());
-
- return null;
- }
- catch (Exception e){
- logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Saving the PDP Group" + e);
- response.setCharacterEncoding("UTF-8");
- request.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- out.write(e.getMessage());
- }
- return null;
- }
-
- @RequestMapping(value={"/pdp_Group/remove_pdp_group"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
- public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
- try{
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- this.container = new PDPGroupContainer(PolicyController.getPapEngine());
- StdPDPGroup pdpGroupData = mapper.readValue(root.get("pdpGroupData").toString(), StdPDPGroup.class);
- if(pdpGroupData.getName().equals("Default")) {
+
+
+ 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());
+
+ return null;
+ }
+ catch (Exception e){
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Saving the PDP Group" + e);
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ }
+ return null;
+ }
+
+ @RequestMapping(value={"/pdp_Group/remove_pdp_group"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ 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());
+ StdPDPGroup pdpGroupData = mapper.readValue(root.get("pdpGroupData").toString(), StdPDPGroup.class);
+ if(pdpGroupData.getName().equals("Default")) {
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());
-
- return null;
- }
- catch (Exception e){
- logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing the PDP Group" + e);
- response.setCharacterEncoding("UTF-8");
- request.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- out.write(e.getMessage());
- }
- return null;
- }
-
- @RequestMapping(value={"/pdp_Group/save_pdpTogroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
- public ModelAndView savePDPToGroup(HttpServletRequest request, HttpServletResponse response) throws Exception{
- try {
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- this.container = new PDPGroupContainer(PolicyController.getPapEngine());
- String update = root.get("update").toString();
- PdpData pdpGroupData = (PdpData)mapper.readValue(root.get("pdpInGroup").toString(), PdpData.class);
- StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);
- try {
-
- if(update.contains("false")){
- this.container.addNewPDP(pdpGroupData.getId(), activeGroupData, pdpGroupData.getName(), pdpGroupData.getDescription(), pdpGroupData.getJmxPort());
- }else{
- this.container.updateGroup(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());
+
+ return null;
+ }
+ catch (Exception e){
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing the PDP Group" + e);
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ }
+ return null;
+ }
+
+ @RequestMapping(value={"/pdp_Group/save_pdpTogroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView savePDPToGroup(HttpServletRequest request, HttpServletResponse response) throws Exception{
+ 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 = (PdpData)mapper.readValue(root.get("pdpInGroup").toString(), PdpData.class);
+ StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class);
+ 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();
- logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + message);
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + message);
}
-
-
- 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());
-
- return null;
- }
- catch (Exception e){
- logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + e);
- response.setCharacterEncoding("UTF-8");
- request.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- out.write(e.getMessage());
- }
- return null;
- }
-
- @RequestMapping(value={"/pdp_Group/remove_pdpFromGroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
- public ModelAndView removePDPFromGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
- try{
- ObjectMapper mapper = new ObjectMapper();
- mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- JsonNode root = mapper.readTree(request.getReader());
- this.container = new PDPGroupContainer(PolicyController.getPapEngine());
- 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.setCharacterEncoding("UTF-8");
- response.setContentType("application / json");
- request.setCharacterEncoding("UTF-8");
-
- PrintWriter out = response.getWriter();
- refreshGroups(request);
- String responseString = mapper.writeValueAsString(groups);
- JSONObject j = new JSONObject("{pdpEntityDatas: " + responseString + "}");
- out.write(j.toString());
-
- return null;
- }
- catch (Exception e){
- logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing Pdp from PDP Group" + e);
- response.setCharacterEncoding("UTF-8");
- request.setCharacterEncoding("UTF-8");
- PrintWriter out = response.getWriter();
- out.write(e.getMessage());
- }
- return 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());
+
+ return null;
+ }
+ catch (Exception e){
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + e);
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ }
+ return null;
+ }
+
+ @RequestMapping(value={"/pdp_Group/remove_pdpFromGroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
+ public ModelAndView removePDPFromGroup(HttpServletRequest request, HttpServletResponse response) throws Exception {
+ 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);
+
+ this.container.removePDP(deletePdp, activeGroupData);
+ response.setCharacterEncoding("UTF-8");
+ response.setContentType("application / json");
+ request.setCharacterEncoding("UTF-8");
+
+ PrintWriter out = response.getWriter();
+ refreshGroups(request);
+ String responseString = mapper.writeValueAsString(groups);
+ JSONObject j = new JSONObject("{pdpEntityDatas: " + responseString + "}");
+ out.write(j.toString());
+
+ return null;
+ }
+ catch (Exception e){
+ logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing Pdp from PDP Group" + e);
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
+ PrintWriter out = response.getWriter();
+ out.write(e.getMessage());
+ }
+ return null;
+ }
+
+ private PolicyController getPolicyControllerInstance(){
+ return policyController != null ? getPolicyController() : new PolicyController();
+ }
+
+ public boolean isJunit() {
+ return junit;
+ }
+
+ public void setJunit(boolean junit) {
+ this.junit = junit;
+ }
+
+ public Set<EcompPDPGroup> getGroupsData() {
+ return groupsData;
+ }
+
+ public void setGroupsData(Set<EcompPDPGroup> groupsData) {
+ this.groupsData = groupsData;
+ }
}
class PdpData{
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyController.java
index 42e4483ca..f89687493 100644
--- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyController.java
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyController.java
@@ -72,9 +72,10 @@ import org.openecomp.policy.common.logging.flexlogger.Logger;
@Controller
@RequestMapping("/")
public class PolicyController extends RestrictedBaseController {
- private static final Logger LOGGER = FlexLogger.getLogger(PolicyController.class);
+ private static final Logger policyLogger = FlexLogger.getLogger(PolicyController.class);
private static CommonClassDao commonClassDao;
+
// Our authorization object
//
XacmlAdminAuthorization authorizer = new XacmlAdminAuthorization();
@@ -83,8 +84,8 @@ public class PolicyController extends RestrictedBaseController {
//
private static PAPPolicyEngine papEngine;
- public static String logTableLimit;
- public static String systemAlertTableLimit;
+ private static String logTableLimit;
+ private static String systemAlertTableLimit;
protected static Map<String, String> dropDownMap = new HashMap<>();
public static Map<String, String> getDropDownMap() {
return dropDownMap;
@@ -102,42 +103,47 @@ public class PolicyController extends RestrictedBaseController {
private static Map<Datatype, List<FunctionDefinition>> mapDatatype2Function = null;
private static Map<String, FunctionDefinition> mapID2Function = null;
-
+ //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";
+
//Smtp Java Mail Properties
- public static String smtpHost = null;
- public static String smtpPort = null;
- public static String smtpUsername = null;
- public static String smtpPassword = null;
- public static String smtpApplicationName = null;
- public static String smtpEmailExtension = null;
+ private static String smtpHost = null;
+ private static String smtpPort = null;
+ private static String smtpUsername = null;
+ private static String smtpPassword = null;
+ private static String smtpApplicationName = null;
+ private static String smtpEmailExtension = null;
//log db Properties
- public static String logdbDriver = null;
- public static String logdbUrl = null;
- public static String logdbUserName = null;
- public static String logdbPassword = null;
- public static String logdbDialect = null;
+ private static String logdbDriver = null;
+ private static String logdbUrl = null;
+ private static String logdbUserName = null;
+ private static String logdbPassword = null;
+ private static String logdbDialect = null;
//Xacml db properties
- public static String xacmldbUrl = null;
- public static String xacmldbUserName = null;
- public static String xacmldbPassword = null;
+ private static String xacmldbUrl = null;
+ private static String xacmldbUserName = null;
+ private static String xacmldbPassword = null;
//AutoPush feature.
- public static String autoPushAvailable;
- public static String autoPushDSClosedLoop;
- public static String autoPushDSFirewall;
- public static String autoPushDSMicroservice;
- public static String autoPushPDPGroup;
+ private static String autoPushAvailable;
+ private static String autoPushDSClosedLoop;
+ private static String autoPushDSFirewall;
+ private static String autoPushDSMicroservice;
+ private static String autoPushPDPGroup;
//papURL
- public static String papUrl;
+ private static String papUrl;
//MicroService Model Properties
- public static String msEcompName;
- public static String msPolicyName;
+ private static String msEcompName;
+ private static String msPolicyName;
//WebApp directories
- public static String configHome;
- public static String actionHome;
+ private static String configHome;
+ private static String actionHome;
@Autowired
private PolicyController(CommonClassDao commonClassDao){
@@ -156,54 +162,54 @@ public class PolicyController extends RestrictedBaseController {
// load a properties file
prop.load(input);
//pap url
- papUrl = prop.getProperty("xacml.rest.pap.url");
+ setPapUrl(prop.getProperty("xacml.rest.pap.url"));
// get the property values
- smtpHost = prop.getProperty("ecomp.smtp.host");
- smtpPort = prop.getProperty("ecomp.smtp.port");
- smtpUsername = prop.getProperty("ecomp.smtp.userName");
- smtpPassword = prop.getProperty("ecomp.smtp.password");
- smtpApplicationName = prop.getProperty("ecomp.application.name");
- smtpEmailExtension = prop.getProperty("ecomp.smtp.emailExtension");
+ setSmtpHost(prop.getProperty("ecomp.smtp.host"));
+ setSmtpPort(prop.getProperty("ecomp.smtp.port"));
+ setSmtpUsername(prop.getProperty("ecomp.smtp.userName"));
+ setSmtpPassword(prop.getProperty("ecomp.smtp.password"));
+ setSmtpApplicationName(prop.getProperty("ecomp.application.name"));
+ setSmtpEmailExtension(prop.getProperty("ecomp.smtp.emailExtension"));
//Log Database Properties
- logdbDriver = prop.getProperty("xacml.log.db.driver");
- logdbUrl = prop.getProperty("xacml.log.db.url");
- logdbUserName = prop.getProperty("xacml.log.db.user");
- logdbPassword = prop.getProperty("xacml.log.db.password");
- logdbDialect = prop.getProperty("ecomp.dialect");
+ setLogdbDriver(prop.getProperty("xacml.log.db.driver"));
+ setLogdbUrl(prop.getProperty("xacml.log.db.url"));
+ setLogdbUserName(prop.getProperty("xacml.log.db.user"));
+ setLogdbPassword(prop.getProperty("xacml.log.db.password"));
+ setLogdbDialect(prop.getProperty("ecomp.dialect"));
//Xacml Database Properties
- xacmldbUrl = prop.getProperty("javax.persistence.jdbc.url");
- xacmldbUserName = prop.getProperty("javax.persistence.jdbc.user");
- xacmldbPassword = prop.getProperty("javax.persistence.jdbc.password");
+ setXacmldbUrl(prop.getProperty("javax.persistence.jdbc.url"));
+ setXacmldbUserName(prop.getProperty("javax.persistence.jdbc.user"));
+ setXacmldbPassword(prop.getProperty("javax.persistence.jdbc.password"));
//AutoPuh
- autoPushAvailable=prop.getProperty("xacml.automatic.push");
- autoPushDSClosedLoop=prop.getProperty("xacml.autopush.closedloop");
- autoPushDSFirewall=prop.getProperty("xacml.autopush.firewall");
- autoPushDSMicroservice=prop.getProperty("xacml.autopush.microservice");
- autoPushPDPGroup=prop.getProperty("xacml.autopush.pdpGroup");
+ setAutoPushAvailable(prop.getProperty("xacml.automatic.push"));
+ setAutoPushDSClosedLoop(prop.getProperty("xacml.autopush.closedloop"));
+ setAutoPushDSFirewall(prop.getProperty("xacml.autopush.firewall"));
+ setAutoPushDSMicroservice(prop.getProperty("xacml.autopush.microservice"));
+ setAutoPushPDPGroup(prop.getProperty("xacml.autopush.pdpGroup"));
//Micro Service Properties
- msEcompName=prop.getProperty("xacml.policy.msEcompName");
- msPolicyName=prop.getProperty("xacml.policy.msPolicyName");
+ setMsEcompName(prop.getProperty("xacml.policy.msEcompName"));
+ setMsPolicyName(prop.getProperty("xacml.policy.msPolicyName"));
//WebApp directories
- configHome = prop.getProperty("xacml.rest.config.webapps") + "Config";
- actionHome = prop.getProperty("xacml.rest.config.webapps") + "Action";
+ setConfigHome(prop.getProperty("xacml.rest.config.webapps") + "Config");
+ setActionHome(prop.getProperty("xacml.rest.config.webapps") + "Action");
//Get the Property Values for Dashboard tab Limit
try{
- logTableLimit = prop.getProperty("xacml.ecomp.dashboard.logTableLimit");
- systemAlertTableLimit = prop.getProperty("xacml.ecomp.dashboard.systemAlertTableLimit");
+ setLogTableLimit(prop.getProperty("xacml.ecomp.dashboard.logTableLimit"));
+ setSystemAlertTableLimit(prop.getProperty("xacml.ecomp.dashboard.systemAlertTableLimit"));
}catch(Exception e){
- LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Dashboard tab Property fields are missing" +e);
- logTableLimit = "5000";
- systemAlertTableLimit = "2000";
+ 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) {
- LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured while reading the Smtp properties from xacml.admin.properties file" +ex);
+ policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured while reading the Smtp properties from xacml.admin.properties file" +ex);
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
- LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured while Closing the xacml.admin.properties file" +e);
+ policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured while Closing the xacml.admin.properties file" +e);
}
}
}
@@ -211,7 +217,7 @@ public class PolicyController extends RestrictedBaseController {
//Initialize the FunctionDefinition table at Server Start up
Map<Datatype, List<FunctionDefinition>> functionMap = getFunctionDatatypeMap();
for (Datatype id : functionMap.keySet()) {
- List<FunctionDefinition> functionDefinations = (List<FunctionDefinition>) functionMap.get(id);
+ List<FunctionDefinition> functionDefinations = functionMap.get(id);
for (FunctionDefinition functionDef : functionDefinations) {
dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid());
}
@@ -244,7 +250,7 @@ public class PolicyController extends RestrictedBaseController {
for (int i = 0; i < functiondefinitions.size(); i ++) {
FunctionDefinition value = (FunctionDefinition) functiondefinitions.get(i);
mapID2Function.put(value.getXacmlid(), value);
- if (mapDatatype2Function.containsKey(value.getDatatypeBean()) == false) {
+ if (!mapDatatype2Function.containsKey(value.getDatatypeBean())) {
mapDatatype2Function.put(value.getDatatypeBean(), new ArrayList<FunctionDefinition>());
}
mapDatatype2Function.get(value.getDatatypeBean()).add(value);
@@ -262,21 +268,20 @@ public class PolicyController extends RestrictedBaseController {
response.getWriter().write(j.toString());
}
catch (Exception e){
- LOGGER.equals(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);
}
}
public PolicyEntity getPolicyEntityData(String scope, String policyName){
String key = scope + ":" + policyName;
List<Object> data = commonClassDao.getDataById(PolicyEntity.class, "scope:policyName", key);
- PolicyEntity entity = (PolicyEntity) data.get(0);
- return entity;
+ return (PolicyEntity) data.get(0);
}
public static Map<String, Roles> getUserRoles(String userId) {
Map<String, Roles> scopes = new HashMap<>();
List<Object> roles = commonClassDao.getDataById(Roles.class, "loginId", userId);
- if (roles != null && roles.size() > 0) {
+ if (roles != null && !roles.isEmpty()) {
for (Object role : roles) {
scopes.put(((Roles) role).getScope(), (Roles) role);
}
@@ -284,8 +289,8 @@ public class PolicyController extends RestrictedBaseController {
return scopes;
}
- public static List<String> getRolesOfUser(String userId) {
- List<String> rolesList = new ArrayList<String>();
+ public List<String> getRolesOfUser(String userId) {
+ List<String> rolesList = new ArrayList<>();
List<Object> roles = commonClassDao.getDataById(Roles.class, "loginId", userId);
for (Object role: roles) {
rolesList.add(((Roles) role).getRole());
@@ -293,7 +298,7 @@ public class PolicyController extends RestrictedBaseController {
return rolesList;
}
- public static List<Object> getRoles(String userId) {
+ public List<Object> getRoles(String userId) {
return commonClassDao.getDataById(Roles.class, "loginId", userId);
}
@@ -310,7 +315,7 @@ public class PolicyController extends RestrictedBaseController {
response.getWriter().write(j.toString());
}
catch (Exception e){
- LOGGER.error("Exception Occured"+e);
+ policyLogger.error("Exception Occured"+e);
}
}
@@ -325,13 +330,13 @@ public class PolicyController extends RestrictedBaseController {
setPapEngine((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL));
new PDPGroupContainer((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL));
} catch (Exception e) {
- LOGGER.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);
}
- public static PAPPolicyEngine getPapEngine() {
+ public PAPPolicyEngine getPapEngine() {
return papEngine;
}
@@ -374,8 +379,7 @@ public class PolicyController extends RestrictedBaseController {
}
public PolicyVersion getPolicyEntityFromPolicyVersion(String query){
- PolicyVersion policyVersionEntity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", query);
- return policyVersionEntity;
+ return (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", query);
}
public List<Object> getDataByQuery(String query){
@@ -394,7 +398,7 @@ public class PolicyController extends RestrictedBaseController {
try {
email.sendMail(entity, policyName, mode, commonClassDao);
} catch (MessagingException e) {
- LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Excepton Occured while Renaming/Deleting a Policy or Scope" + e);
+ policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Excepton Occured while Renaming/Deleting a Policy or Scope" + e);
}
}
@@ -428,5 +432,265 @@ public class PolicyController extends RestrictedBaseController {
el.put("highestVersion", entity.getHigherVersion());
return el;
}
+
+ public static String getLogTableLimit() {
+ return logTableLimit;
+ }
+
+ public static void setLogTableLimit(String logTableLimit) {
+ PolicyController.logTableLimit = logTableLimit;
+ }
+
+ public static String getSystemAlertTableLimit() {
+ return systemAlertTableLimit;
+ }
+
+ public static void setSystemAlertTableLimit(String systemAlertTableLimit) {
+ PolicyController.systemAlertTableLimit = systemAlertTableLimit;
+ }
+
+ public static CommonClassDao getCommonClassDao() {
+ return commonClassDao;
+ }
+
+ public static void setCommonClassDao(CommonClassDao commonClassDao) {
+ PolicyController.commonClassDao = commonClassDao;
+ }
+
+ public XacmlAdminAuthorization getAuthorizer() {
+ return authorizer;
+ }
+
+ public void setAuthorizer(XacmlAdminAuthorization authorizer) {
+ this.authorizer = authorizer;
+ }
+
+ public static Map<Datatype, List<FunctionDefinition>> getMapDatatype2Function() {
+ return mapDatatype2Function;
+ }
+
+ public static void setMapDatatype2Function(Map<Datatype, List<FunctionDefinition>> mapDatatype2Function) {
+ PolicyController.mapDatatype2Function = mapDatatype2Function;
+ }
+
+ public static Map<String, FunctionDefinition> getMapID2Function() {
+ return mapID2Function;
+ }
+
+ public static void setMapID2Function(Map<String, FunctionDefinition> mapID2Function) {
+ PolicyController.mapID2Function = mapID2Function;
+ }
+
+ public static String getSmtpHost() {
+ return smtpHost;
+ }
+
+ public static void setSmtpHost(String smtpHost) {
+ PolicyController.smtpHost = smtpHost;
+ }
+
+ public static String getSmtpPort() {
+ return smtpPort;
+ }
+
+ public static void setSmtpPort(String smtpPort) {
+ PolicyController.smtpPort = smtpPort;
+ }
+
+ public static String getSmtpUsername() {
+ return smtpUsername;
+ }
+
+ public static void setSmtpUsername(String smtpUsername) {
+ PolicyController.smtpUsername = smtpUsername;
+ }
+
+ public static String getSmtpPassword() {
+ return smtpPassword;
+ }
+
+ public static void setSmtpPassword(String smtpPassword) {
+ PolicyController.smtpPassword = smtpPassword;
+ }
+
+ public static String getSmtpApplicationName() {
+ return smtpApplicationName;
+ }
+
+ public static void setSmtpApplicationName(String smtpApplicationName) {
+ PolicyController.smtpApplicationName = smtpApplicationName;
+ }
+
+ public static String getSmtpEmailExtension() {
+ return smtpEmailExtension;
+ }
+
+ public static void setSmtpEmailExtension(String smtpEmailExtension) {
+ PolicyController.smtpEmailExtension = smtpEmailExtension;
+ }
+
+ public static String getLogdbDriver() {
+ return logdbDriver;
+ }
+
+ public static void setLogdbDriver(String logdbDriver) {
+ PolicyController.logdbDriver = logdbDriver;
+ }
+
+ public static String getLogdbUrl() {
+ return logdbUrl;
+ }
+
+ public static void setLogdbUrl(String logdbUrl) {
+ PolicyController.logdbUrl = logdbUrl;
+ }
+
+ public static String getLogdbUserName() {
+ return logdbUserName;
+ }
+
+ public static void setLogdbUserName(String logdbUserName) {
+ PolicyController.logdbUserName = logdbUserName;
+ }
+
+ public static String getLogdbPassword() {
+ return logdbPassword;
+ }
+
+ public static void setLogdbPassword(String logdbPassword) {
+ PolicyController.logdbPassword = logdbPassword;
+ }
+
+ public static String getLogdbDialect() {
+ return logdbDialect;
+ }
+
+ public static void setLogdbDialect(String logdbDialect) {
+ PolicyController.logdbDialect = logdbDialect;
+ }
+
+ public static String getXacmldbUrl() {
+ return xacmldbUrl;
+ }
+
+ public static void setXacmldbUrl(String xacmldbUrl) {
+ PolicyController.xacmldbUrl = xacmldbUrl;
+ }
+
+ public static String getXacmldbUserName() {
+ return xacmldbUserName;
+ }
+
+ public static void setXacmldbUserName(String xacmldbUserName) {
+ PolicyController.xacmldbUserName = xacmldbUserName;
+ }
+
+ public static String getXacmldbPassword() {
+ return xacmldbPassword;
+ }
+
+ public static void setXacmldbPassword(String xacmldbPassword) {
+ PolicyController.xacmldbPassword = xacmldbPassword;
+ }
+
+ public static String getAutoPushAvailable() {
+ return autoPushAvailable;
+ }
+
+ public static void setAutoPushAvailable(String autoPushAvailable) {
+ PolicyController.autoPushAvailable = autoPushAvailable;
+ }
+
+ public static String getAutoPushDSClosedLoop() {
+ return autoPushDSClosedLoop;
+ }
+
+ public static void setAutoPushDSClosedLoop(String autoPushDSClosedLoop) {
+ PolicyController.autoPushDSClosedLoop = autoPushDSClosedLoop;
+ }
+
+ public static String getAutoPushDSFirewall() {
+ return autoPushDSFirewall;
+ }
+
+ public static void setAutoPushDSFirewall(String autoPushDSFirewall) {
+ PolicyController.autoPushDSFirewall = autoPushDSFirewall;
+ }
+
+ public static String getAutoPushDSMicroservice() {
+ return autoPushDSMicroservice;
+ }
+
+ public static void setAutoPushDSMicroservice(String autoPushDSMicroservice) {
+ PolicyController.autoPushDSMicroservice = autoPushDSMicroservice;
+ }
+
+ public static String getAutoPushPDPGroup() {
+ return autoPushPDPGroup;
+ }
+
+ public static void setAutoPushPDPGroup(String autoPushPDPGroup) {
+ PolicyController.autoPushPDPGroup = autoPushPDPGroup;
+ }
+
+ public static String getPapUrl() {
+ return papUrl;
+ }
+
+ public static void setPapUrl(String papUrl) {
+ PolicyController.papUrl = papUrl;
+ }
+
+ public static String getMsEcompName() {
+ return msEcompName;
+ }
+
+ public static void setMsEcompName(String msEcompName) {
+ PolicyController.msEcompName = msEcompName;
+ }
+
+ public static String getMsPolicyName() {
+ return msPolicyName;
+ }
+
+ public static void setMsPolicyName(String msPolicyName) {
+ PolicyController.msPolicyName = msPolicyName;
+ }
+
+ public static String getConfigHome() {
+ return configHome;
+ }
+
+ public static void setConfigHome(String configHome) {
+ PolicyController.configHome = configHome;
+ }
+
+ public static String getActionHome() {
+ return actionHome;
+ }
+
+ public static void setActionHome(String actionHome) {
+ PolicyController.actionHome = actionHome;
+ }
+
+ public static Object getMapaccess() {
+ return mapAccess;
+ }
+
+ public static String getPolicydata() {
+ return policyData;
+ }
+
+ public static String getCharacterencoding() {
+ return characterEncoding;
+ }
+
+ public static String getContenttype() {
+ return contentType;
+ }
+
+ public static String getFile() {
+ return file;
+ }
}
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyExportAndImportController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyExportAndImportController.java
index 68a65fc5e..bf2a148e6 100644
--- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyExportAndImportController.java
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyExportAndImportController.java
@@ -89,6 +89,15 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
private Workbook workbook;
private HSSFWorkbook workBook2;
+
+ private PolicyController policyController;
+ public PolicyController getPolicyController() {
+ return policyController;
+ }
+
+ public void setPolicyController(PolicyController policyController) {
+ this.policyController = policyController;
+ }
@Autowired
private PolicyExportAndImportController(CommonClassDao commonClassDao){
@@ -190,12 +199,12 @@ public class PolicyExportAndImportController extends RestrictedBaseController {
String configName = null;
String scope = null;
boolean finalColumn = false;
- PolicyController controller = new PolicyController();
+ PolicyController controller = policyController != null ? getPolicyController() : new PolicyController();
String userId = UserUtils.getUserSession(request).getOrgUserId();
UserInfo userInfo = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", userId);
//Check if the Role and Scope Size are Null get the values from db.
- List<Object> userRoles = PolicyController.getRoles(userId);
+ List<Object> userRoles = controller.getRoles(userId);
roles = new ArrayList<>();
scopes = new HashSet<>();
for(Object role: userRoles){
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/SystemLogDbDaoImpl.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/SystemLogDbDaoImpl.java
index 927d20f2f..fbca821d4 100644
--- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/SystemLogDbDaoImpl.java
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/SystemLogDbDaoImpl.java
@@ -49,7 +49,7 @@ public class SystemLogDbDaoImpl implements SystemLogDbDao {
Transaction tx = session.beginTransaction();
List<SystemLogDB> system = null;
try {
- String sqlWhere = "date > DATE_SUB(curdate(), INTERVAL 5 DAY) ORDER BY date DESC limit "+PolicyController.logTableLimit+"";
+ String 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();
@@ -73,7 +73,7 @@ public class SystemLogDbDaoImpl implements SystemLogDbDao {
Transaction tx = session.beginTransaction();
List<SystemLogDB> system = null;
try {
- String sqlWhere = "date > DATE_SUB(curdate(), INTERVAL 5 DAY) and logtype = 'error' ORDER BY date DESC limit "+PolicyController.systemAlertTableLimit+"";
+ String 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();
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/PDPGroupContainer.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/PDPGroupContainer.java
index a0b47bb7d..d048ded99 100644
--- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/PDPGroupContainer.java
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/PDPGroupContainer.java
@@ -52,57 +52,51 @@ public class PDPGroupContainer extends PolicyItemSetChangeNotifier implements Po
/**
* String identifier of a file's "Id" property.
*/
- public static String PROPERTY_ID = "Id";
+ private static String PROPERTY_ID = "Id";
/**
* String identifier of a file's "name" property.
*/
- public static String PROPERTY_NAME = "Name";
+ private static String PROPERTY_NAME = "Name";
/**
* String identifier of a file's "Description" property.
*/
- public static String PROPERTY_DESCRIPTION = "Description";
+ private static String PROPERTY_DESCRIPTION = "Description";
/**
* String identifier of a file's "Default" property.
*/
- public static String PROPERTY_DEFAULT = "Default";
-
- /**
- * String identifier of a file's "icon" property.
- */
- public static String PROPERTY_ICON = "Icon";
-
+ private static String PROPERTY_DEFAULT = "Default";
/**
* String identifier of a file's "Status" property.
*/
- public static String PROPERTY_STATUS = "Status";
+ private static String PROPERTY_STATUS = "Status";
/**
* String identifier of a file's "PDPs" property.
*/
- public static String PROPERTY_PDPS = "PDPs";
+ private static String PROPERTY_PDPS = "PDPs";
/**
* String identifier of a file's "Policies" property.
*/
- public static String PROPERTY_POLICIES = "Policies";
+ private static String PROPERTY_POLICIES = "Policies";
/**
* String identifier of a file's "PIP Configurations" property.
*/
- public static String PROPERTY_PIPCONFIG = "PIP Configurations";
+ private static String PROPERTY_PIPCONFIG = "PIP Configurations";
/**
* String identifier of a file's "Selected" property.
*/
- public static String PROPERTY_SELECTED = "Selected";
+ private static String PROPERTY_SELECTED = "Selected";
/**
* List of the string identifiers for the available properties.
*/
- public static Collection<String> PDP_PROPERTIES;
+ private static Collection<String> PDP_PROPERTIES;
private PAPPolicyEngine papEngine = null;
protected List<EcompPDPGroup> groups = Collections.synchronizedList(new ArrayList<EcompPDPGroup>());
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/PDPPolicyContainer.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/PDPPolicyContainer.java
index 372a416c6..1cdf7d6a3 100644
--- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/PDPPolicyContainer.java
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/PDPPolicyContainer.java
@@ -46,32 +46,32 @@ public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements P
/**
* String identifier of a file's "Id" property.
*/
- public static String PROPERTY_ID = "Id";
+ private static String PROPERTY_ID = "Id";
/**
* String identifier of a file's "name" property.
*/
- public static String PROPERTY_NAME = "Name";
+ private static String PROPERTY_NAME = "Name";
/**
* String identifier of a file's "name" property.
*/
- public static String PROPERTY_VERSION = "Version";
+ private static String PROPERTY_VERSION = "Version";
/**
* String identifier of a file's "Description" property.
*/
- public static String PROPERTY_DESCRIPTION = "Description";
+ private static String PROPERTY_DESCRIPTION = "Description";
/**
* String identifier of a file's "IsRoot" property.
*/
- public static String PROPERTY_ISROOT = "Root";
+ private static String PROPERTY_ISROOT = "Root";
/**
* List of the string identifiers for the available properties.
*/
- public static Collection<String> PDPPOLICY_PROPERTIES;
+ private static Collection<String> PDPPOLICY_PROPERTIES;
private final Object data;
private List<PDPPolicy> policies;
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/ConfigurableRESTUtils.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/ConfigurableRESTUtils.java
index 4ebc01c0c..58d53a1f4 100644
--- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/ConfigurableRESTUtils.java
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/ConfigurableRESTUtils.java
@@ -46,10 +46,10 @@ public class ConfigurableRESTUtils {
GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE;
}
- public String ERROR_RECEIVED = "ERROR - Unexpected HTTP response: ";
+ private String ERROR_RECEIVED = "ERROR - Unexpected HTTP response: ";
public ConfigurableRESTUtils() {
-
+ //Default Constructor
}
@@ -144,7 +144,7 @@ public class ConfigurableRESTUtils {
try {
is = connection.getInputStream();
} catch (Exception e1) {
- // ignore this
+ LOGGER.error("Exception Occured"+e1);
}
if (is != null) {
is.close();
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 9eb90333b..338c4ca24 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
@@ -38,7 +38,7 @@ app.controller('policyPushController', function ($scope, PolicyAppService, modal
});
$scope.pdpdata;
- PolicyAppService.getData('get_PDPGroupContainerData').then(function (data) {
+ PolicyAppService.getData('get_PDPGroupData').then(function (data) {
var j = data;
$scope.pdpdata = JSON.parse(j.data);
console.log($scope.pdpdata);
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/templates/navbar.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/templates/navbar.html
index 80ca1c593..dfac651ae 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/templates/navbar.html
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/templates/navbar.html
@@ -8,7 +8,7 @@
</form>
</div>
<div class="form-group col-sm-5" style="margin-top: 2%"></div>
- <div class="form-group col-sm-4" style="margin-top: 2%" align="right">
+ <div class="form-group col-sm-4" style="margin-top: 2%" align="right" ng-hide="isDisabled">
<div class="btn-group">
<button type="button" class="btn btn-primary" ng-show="superAdminId" data-toggle="modal" data-target="#newfolder" ng-click="touch()"><i class="glyphicon glyphicon-plus"></i>Add Scope</button>
<button type="button" class="btn btn-primary" ng-show="importPolicyId" data-toggle="modal" data-target="#uploadfile" ng-show="config.allowedActions.upload" ng-click="touch()"> <i class="glyphicon glyphicon-upload"></i>Import</button>
diff --git a/POLICY-SDK-APP/src/test/java/org/openecomp/policy/admin/PolicyManagerServletTest.java b/POLICY-SDK-APP/src/test/java/org/openecomp/policy/admin/PolicyManagerServletTest.java
new file mode 100644
index 000000000..773955d85
--- /dev/null
+++ b/POLICY-SDK-APP/src/test/java/org/openecomp/policy/admin/PolicyManagerServletTest.java
@@ -0,0 +1,155 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.admin;
+
+import java.io.BufferedReader;
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.io.IOUtils;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.controller.PolicyController;
+import org.openecomp.policy.model.Roles;
+import org.openecomp.policy.rest.jpa.PolicyEditorScopes;
+import org.openecomp.policy.rest.jpa.PolicyEntity;
+import org.openecomp.policy.rest.jpa.PolicyVersion;
+import org.openecomp.policy.rest.jpa.UserInfo;
+
+public class PolicyManagerServletTest extends Mockito{
+
+ private static Logger logger = FlexLogger.getLogger(PolicyManagerServletTest.class);
+
+ private static List<Object> rolesdata;
+ private static List<Object> policyData;
+ private static List<Object> policyEditorScopes;
+ private static List<Object> policyVersion;
+
+ @Before
+ public void setUp() throws Exception{
+ logger.info("setUp: Entering");
+ UserInfo userinfo = new UserInfo();
+ userinfo.setUserLoginId("Test");
+ userinfo.setUserName("Test");
+ //Roles Data
+ rolesdata = new ArrayList<>();
+ Roles roles = new Roles();
+ roles.setLoginId("Test");
+ roles.setRole("super-admin");
+ Roles roles1 = new Roles();
+ roles1.setLoginId("Test");
+ roles1.setRole("admin");
+ roles1.setScope("['com','Test']");
+ rolesdata.add(roles);
+ rolesdata.add(roles1);
+
+ //PolicyEntity Data
+ policyData = new ArrayList<>();
+ String policyContent = "";
+ try {
+ ClassLoader classLoader = getClass().getClassLoader();
+ policyContent = IOUtils.toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml"));
+ } catch (Exception e1) {
+ logger.error("Exception Occured"+e1);
+ }
+ PolicyEntity entity = new PolicyEntity();
+ entity.setPolicyName("Config_SampleTest.1.xml");
+ entity.setPolicyData(policyContent);
+ entity.setScope("com");
+ policyData.add(entity);
+
+ //PolicyEditorScopes data
+ policyEditorScopes = new ArrayList<>();
+ PolicyEditorScopes scopes = new PolicyEditorScopes();
+ scopes.setScopeName("com");
+ scopes.setUserCreatedBy(userinfo);
+ scopes.setUserModifiedBy(userinfo);
+ PolicyEditorScopes scopes1 = new PolicyEditorScopes();
+ scopes1.setScopeName("com\\Test");
+ scopes1.setUserCreatedBy(userinfo);
+ scopes1.setUserModifiedBy(userinfo);
+ policyEditorScopes.add(scopes);
+ policyEditorScopes.add(scopes1);
+
+ //PolicyVersion data
+ policyVersion = new ArrayList<>();
+ PolicyVersion policy = new PolicyVersion();
+ policy.setPolicyName("com\\Config_SampleTest1206");
+ policy.setActiveVersion(1);
+ policy.setHigherVersion(1);
+ policy.setCreatedBy("Test");
+ policy.setModifiedBy("Test");
+ policyVersion.add(policy);
+ }
+
+ @Test
+ public void testDescribePolicy(){
+ PolicyManagerServlet servlet = new PolicyManagerServlet();
+ HttpServletRequest request = mock(HttpServletRequest.class);
+ HttpServletResponse response = mock(HttpServletResponse.class);
+ PolicyController controller = mock(PolicyController.class);
+
+ BufferedReader reader = new BufferedReader(new StringReader("{params: { mode: 'DESCRIBEPOLICYFILE', path: 'com.Config_SampleTest1206.1.xml'}}"));
+ try {
+ when(request.getReader()).thenReturn(reader);
+ when(controller.getDataByQuery("FROM PolicyEntity where policyName = 'Config_SampleTest1206.1.xml' and scope ='com'")).thenReturn(policyData);
+ servlet.setPolicyController(controller);
+ servlet.doPost(request, response);
+ } catch (Exception e1) {
+ logger.error("Exception Occured"+e1);
+ }
+ }
+
+
+ @Test
+ public void testPolicyScopeList(){
+ PolicyManagerServlet servlet = new PolicyManagerServlet();
+ HttpServletRequest request = mock(HttpServletRequest.class);
+ HttpServletResponse response = mock(HttpServletResponse.class);
+ PolicyController controller = mock(PolicyController.class);
+ List<String> list = new ArrayList<>();
+ list.add("{params: { mode: 'LIST', path: '/', onlyFolders: false}}");
+ list.add("{params: { mode: 'LIST', path: '/com', onlyFolders: false}}");
+ for(int i =0; i < list.size(); i++){
+ BufferedReader reader = new BufferedReader(new StringReader(list.get(i)));
+ try {
+ when(request.getReader()).thenReturn(reader);
+ when(controller.getRoles("Test")).thenReturn(rolesdata);
+ when(controller.getDataByQuery("from PolicyEditorScopes")).thenReturn(policyEditorScopes);
+ when(controller.getDataByQuery("from PolicyEditorScopes where SCOPENAME like 'com%'")).thenReturn(policyEditorScopes);
+ when(controller.getDataByQuery("from PolicyVersion where POLICY_NAME like 'com%'")).thenReturn(policyVersion);
+ servlet.setPolicyController(controller);
+ servlet.setTestUserId("Test");
+ servlet.doPost(request, response);
+ } catch (Exception e1) {
+ logger.error("Exception Occured"+e1);
+ }
+ }
+ }
+
+
+}
diff --git a/POLICY-SDK-APP/src/test/java/org/openecomp/policy/controller/AdminTabControllerTest.java b/POLICY-SDK-APP/src/test/java/org/openecomp/policy/controller/AdminTabControllerTest.java
new file mode 100644
index 000000000..43b8a6f25
--- /dev/null
+++ b/POLICY-SDK-APP/src/test/java/org/openecomp/policy/controller/AdminTabControllerTest.java
@@ -0,0 +1,74 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.controller;
+
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.UnsupportedEncodingException;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.rest.dao.CommonClassDao;
+import org.openecomp.policy.rest.jpa.GlobalRoleSettings;
+import org.springframework.mock.web.MockHttpServletResponse;
+
+public class AdminTabControllerTest {
+
+ private static Logger logger = FlexLogger.getLogger(AdminTabControllerTest.class);
+ private static CommonClassDao commonClassDao;
+
+ @Before
+ public void setUp() throws Exception {
+
+ logger.info("setUp: Entering");
+ commonClassDao = mock(CommonClassDao.class);
+ GlobalRoleSettings globalRole = new GlobalRoleSettings();
+ globalRole.setLockdown(true);
+ globalRole.setRole("super-admin");
+ List<Object> globalRoles = new ArrayList<>();
+ globalRoles.add(globalRole);
+ when(commonClassDao.getData(GlobalRoleSettings.class)).thenReturn(globalRoles);
+ }
+
+ @Test
+ public void testGetAdminRole(){
+ HttpServletRequest request = mock(HttpServletRequest.class);
+ MockHttpServletResponse response = new MockHttpServletResponse();
+
+ AdminTabController admin = new AdminTabController();
+ AdminTabController.setCommonClassDao(commonClassDao);
+ admin.getAdminTabEntityData(request, response);
+
+ try {
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("lockdowndata"));
+ } catch (UnsupportedEncodingException e) {
+ logger.error("Exception Occured"+e);
+ }
+ }
+
+}
diff --git a/POLICY-SDK-APP/src/test/java/org/openecomp/policy/controller/CreateDcaeMicroServiceControllerTest.java b/POLICY-SDK-APP/src/test/java/org/openecomp/policy/controller/CreateDcaeMicroServiceControllerTest.java
new file mode 100644
index 000000000..ca4f24949
--- /dev/null
+++ b/POLICY-SDK-APP/src/test/java/org/openecomp/policy/controller/CreateDcaeMicroServiceControllerTest.java
@@ -0,0 +1,647 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.policy.controller;
+
+
+import static org.easymock.EasyMock.createMock;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.replay;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.ReadListener;
+import javax.servlet.ServletInputStream;
+import javax.servlet.http.HttpServletRequest;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
+import org.openecomp.policy.rest.dao.CommonClassDao;
+import org.openecomp.policy.rest.jpa.ConfigurationDataEntity;
+import org.openecomp.policy.rest.jpa.MicroServiceModels;
+import org.openecomp.policy.rest.jpa.PolicyEntity;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.github.fge.jackson.JsonLoader;
+
+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;
+
+/**
+ * The class <code>CreateDcaeMicroServiceControllerTest</code> contains tests
+ * for the class {@link <code>CreateDcaeMicroServiceController</code>}*
+ *
+ * All JUnits are designed to run in the local development environment
+ * where they have write privileges and can execute time-sensitive
+ * tasks.
+ *
+ *
+ *
+ */
+
+public class CreateDcaeMicroServiceControllerTest {
+
+ private static Logger logger = FlexLogger.getLogger(CreateDcaeMicroServiceControllerTest.class);
+ private static CommonClassDao commonClassDao;
+ private String jsonString = null;
+ private String configBodyString = null;
+ private HttpServletRequest request = null;
+
+ @Before
+ public void setUp() throws Exception {
+
+ logger.info("setUp: Entering");
+ commonClassDao = mock(CommonClassDao.class);
+ List<Object> microServiceModelsData = new ArrayList<Object>();
+ MicroServiceModels testData = new MicroServiceModels();
+ testData.setVersion("OpenEcomp-Junit");
+ microServiceModelsData.add(testData);
+
+ // mock the getDataById() call
+ when(commonClassDao.getDataById(MicroServiceModels.class, "modelName", "test")).thenReturn(microServiceModelsData);
+
+ jsonString = "{\"policyData\": {\"error\": \"\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", "
+ + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", "
+ + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false},"
+ + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" },"
+ + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", "
+ + " \"policyDescription\": \"testing input\", \"ecompName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\","
+ + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, "
+ + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }";
+
+ configBodyString = "{\"service\":\"SniroPolicyEntityTest\",\"policyName\":\"someone\",\"description\":\"test\",\"templateVersion\":\"1607\",\"version\":\"HD\","
+ + "\"priority\":\"2\",\"content\":{\"lastPolled\":\"1\",\"boolen-test\":\"true\",\"created\":\"test\",\"retiredDate\":\"test\",\"scope\":\"SNIRO_PLACEMENT_VDHV\","
+ + "\"name\":\"test\",\"lastModified\":\"test\",\"state\":\"CREATED\",\"type\":\"CONFIG\",\"intent\":\"test\",\"target\":\"SNIRO\"}}";
+
+ request = mock(HttpServletRequest.class);
+ BufferedReader br = new BufferedReader(new StringReader(jsonString));
+ // mock the getReader() call
+ when(request.getReader()).thenReturn(br);
+
+ logger.info("setUp: exit");
+ }
+
+
+ /**
+ * Run the PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter,
+ * JsonNode) method test
+ */
+
+ @Test
+ public void testSetDataToPolicyRestAdapter() {
+
+ logger.debug("testSetDataToPolicyRestAdapter: enter");
+
+ CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
+ CreateDcaeMicroServiceController.setCommonClassDao(commonClassDao);
+
+ JsonNode root = null;
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ PolicyRestAdapter policyData = null;
+ try {
+ root = JsonLoader.fromString(jsonString);
+ policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class);
+ } catch (Exception e) {
+ logger.error("testSetDataToPolicyRestAdapter", e);
+ }
+
+ PolicyRestAdapter result = controller.setDataToPolicyRestAdapter(policyData, root);
+ assertTrue(result != null && result.getJsonBody() != null && !result.getJsonBody().isEmpty());
+
+ logger.debug("result.getJsonBody() : " + result.getJsonBody());
+ logger.debug("testSetDataToPolicyRestAdapter: exit");
+ }
+
+ /**
+ * Run the void stringBetweenDots(String, String) method test
+ */
+
+ @Test
+ public void testStringBetweenDots() {
+
+ logger.debug("testStringBetweenDots: enter");
+
+ //expect: uniqueKeys should contain a string value
+ CreateDcaeMicroServiceController controllerA = new CreateDcaeMicroServiceController();
+ String str = "testing\\.byCorrectWay\\.OfDATA";
+ String value = null;
+ assertEquals(1, controllerA.stringBetweenDots(str, value));
+
+ //expect: uniqueKeys should not contain a string value
+ str = "testing\byWrongtWay.\\OfDATA";
+ CreateDcaeMicroServiceController controllerB = new CreateDcaeMicroServiceController();
+ assertEquals(0, controllerB.stringBetweenDots(str, value));
+
+ logger.debug("testStringBetweenDots: exit");
+ }
+
+ /**
+ * Run the Map<String,String> load(String) method test
+ */
+
+ @Test
+ public void testLoad() {
+
+ logger.debug("testLoad: enter");
+
+ boolean isLocalTesting = true;
+ CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
+ String fileName = null;
+ Map<String,String> result = null;
+ try {
+ ClassLoader classLoader = getClass().getClassLoader();
+ fileName = new File(classLoader.getResource("policy_tosca_tca_v1707.yml").getFile()).getAbsolutePath();
+ } catch (Exception e1) {
+ logger.error("Exception Occured while loading file"+e1);
+ }
+ if(isLocalTesting){
+ try {
+ result = controller.load(fileName);
+ } catch (IOException e) {
+ logger.error("testLoad", e);
+ result = null;
+ }
+
+ assertTrue(result != null && !result.isEmpty());
+ logger.debug("result : " + result);
+ }
+
+ logger.debug("testLoad: exit");
+ }
+
+ /**
+ * Run the void parseTosca(String) method test
+ */
+
+ @Test
+ public void testParseTosca() {
+
+ logger.debug("testParseTosca: enter");
+ boolean isLocalTesting = true;
+ String fileName = null;
+ try {
+ ClassLoader classLoader = getClass().getClassLoader();
+ fileName = new File(classLoader.getResource("policy_tosca_tca_v1707.yml").getFile()).getAbsolutePath();
+ } catch (Exception e1) {
+ logger.error("Exception Occured while loading file"+e1);
+ }
+
+ CreateDcaeMicroServiceController contoller = new CreateDcaeMicroServiceController();
+ if(isLocalTesting){
+ try {
+ contoller.parseTosca(fileName);
+ }catch (Exception e) {
+ fail("parseTosca caused error: " + e);
+ }
+ }
+ logger.debug("testParseTosca: exit");
+ }
+
+ /**
+ * Run the ModelAndView getDCAEMSTemplateData(HttpServletRequest,
+ * HttpServletResponse) method test
+ */
+
+ @Test
+ public void testGetDCAEMSTemplateData() {
+
+ logger.debug("testGetDCAEMSTemplateData: enter");
+
+ CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ String msModelJson = "{\"policyData\":\"DkatPolicyBody\"}";
+ try {
+
+ CreateDcaeMicroServiceController.setCommonClassDao(commonClassDao);
+
+ BufferedReader br = new BufferedReader(new StringReader(msModelJson));
+ // mock the getReader() call
+ when(request.getReader()).thenReturn(br);
+
+ List<Object> microServiceModelsData = new ArrayList<Object>();
+ MicroServiceModels testData = new MicroServiceModels();
+ testData.setVersion("1707.4.1.2-Junit");
+ microServiceModelsData.add(testData);
+ // mock the getDataById() call with the same MS model name
+ when(commonClassDao.getDataById(MicroServiceModels.class, "modelName", "DkatPolicyBody")).thenReturn(microServiceModelsData);
+
+ controller.getDCAEMSTemplateData(request, response);
+
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("dcaeModelData"));
+
+ logger.debug("response: " + response.getContentAsString());
+
+ } catch (Exception e) {
+ logger.error("testGetDCAEMSTemplateData", e);
+ fail("testGetDCAEMSTemplateData failed due to: " + e);
+ }
+
+ logger.debug("testGetDCAEMSTemplateData: exit");
+ }
+
+ /**
+ * Run the ModelAndView getModelServiceVersionData(HttpServletRequest,
+ * HttpServletResponse) method test
+ */
+
+ @Test
+ public void testGetModelServiceVersionData() {
+
+ logger.debug("testGetModelServiceVersionData: enter");
+
+ CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ String msModelJson = "{\"policyData\":\"DkatPolicyBody\"}";
+ try {
+
+ CreateDcaeMicroServiceController.setCommonClassDao(commonClassDao);
+
+ BufferedReader br = new BufferedReader(new StringReader(msModelJson));
+ // mock the getReader() call
+ when(request.getReader()).thenReturn(br);
+
+ List<Object> microServiceModelsData = new ArrayList<Object>();
+ MicroServiceModels testData = new MicroServiceModels();
+ testData.setVersion("1707.4.1.2-Junit");
+ microServiceModelsData.add(testData);
+
+ // mock the getDataById() call with the same MS model name
+ when(commonClassDao.getDataById(MicroServiceModels.class, "modelName", "DkatPolicyBody")).thenReturn(microServiceModelsData);
+ controller.getModelServiceVersionData(request, response);
+
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("1707.4.1.2-Junit"));
+
+ logger.debug("response: " + response.getContentAsString());
+
+ } catch (Exception e) {
+ logger.error("testGetModelServiceVersionData", e);
+ fail("testGetModelServiceVersionData failed due to: " + e);
+ }
+
+ logger.debug("testGetModelServiceVersionData: exit");
+ }
+
+ /**
+ * Run the void getDCAEPriorityValuesData(HttpServletRequest,
+ * HttpServletResponse) method test
+ */
+
+ @Test
+ public void testGetDCAEPriorityValuesData() {
+
+ logger.debug("testGetDCAEPriorityValuesData: enter");
+
+ CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
+
+ MockHttpServletRequest request = new MockHttpServletRequest();
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ try{
+ controller.getDCAEPriorityValuesData(request, response);
+ assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("priorityDatas"));
+ logger.debug("response: " + response.getContentAsString());
+ } catch (Exception e) {
+ logger.error("testGetDCAEPriorityValuesData", e);
+ fail("testGetDCAEPriorityValuesData failed due to: " + e);
+ }
+
+ logger.debug("testGetDCAEPriorityValuesData: exit");
+ }
+
+ /**
+ * Run the void prePopulateDCAEMSPolicyData(PolicyRestAdapter,
+ * PolicyEntity) method test
+ */
+
+ @Test
+ public void testPrePopulateDCAEMSPolicyData() {
+
+ logger.debug("testPrePopulateDCAEMSPolicyData: enter");
+
+ CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
+
+ // populate an entity object for testing
+ PolicyEntity entity = new PolicyEntity();
+ ConfigurationDataEntity configData = new ConfigurationDataEntity();
+ configData.setConfigBody(configBodyString);
+ entity.setConfigurationData(configData);
+
+ JsonNode root = null;
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+ PolicyRestAdapter restAdapter = null;
+
+ try {
+ root = JsonLoader.fromString(jsonString);
+ restAdapter = (PolicyRestAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class);
+ PolicyType policyType = new PolicyType();
+ TargetType target = new TargetType();
+
+ // create guard attribute
+ AnyOfType anyOfType = new AnyOfType();
+ AllOfType alltype = new AllOfType();
+ MatchType matchType = new MatchType();
+ // set value
+ AttributeValueType attributeValue1 = new AttributeValueType();
+ attributeValue1.getContent().add("True");
+ matchType.setAttributeValue(attributeValue1);
+ // set Id
+ AttributeDesignatorType designator = new AttributeDesignatorType();
+ designator.setAttributeId("guard");
+ matchType.setAttributeDesignator(designator);
+ alltype.getMatch().add(matchType);
+
+ // add a dummy MatchType object since while (matchList.size()>1 ...)
+ MatchType matchDummy = new MatchType();
+ // set value
+ AttributeValueType dummyValue = new AttributeValueType();
+ dummyValue.getContent().add("dummy");
+ matchDummy.setAttributeValue(dummyValue);
+ // set Id
+ AttributeDesignatorType designatorDummy = new AttributeDesignatorType();
+ designatorDummy.setAttributeId("dummyId");
+ matchDummy.setAttributeDesignator(designatorDummy);
+
+ alltype.getMatch().add(matchDummy);
+ anyOfType.getAllOf().add(alltype);
+
+ target.getAnyOf().add(anyOfType);
+
+ // create RiskType attribute
+ AnyOfType anyRiskType = new AnyOfType();
+ AllOfType allRiskType = new AllOfType();
+ MatchType matchRiskType = new MatchType();
+ // set value
+ AttributeValueType riskTypeValue = new AttributeValueType();
+ riskTypeValue.getContent().add("test");
+ matchRiskType.setAttributeValue(riskTypeValue);
+ // set Id
+ AttributeDesignatorType designatorRiskType = new AttributeDesignatorType();
+ designatorRiskType.setAttributeId("RiskType");
+ matchRiskType.setAttributeDesignator(designatorRiskType);
+ allRiskType.getMatch().add(matchRiskType);
+
+ // add a dummy MatchType object since while (matchList.size()>1 ...)
+ MatchType matchDummy1 = new MatchType();
+ // set value
+ AttributeValueType dummy1Value = new AttributeValueType();
+ dummy1Value.getContent().add("dummy");
+ matchDummy1.setAttributeValue(dummy1Value);
+ // set Id
+ AttributeDesignatorType designatorDummy1 = new AttributeDesignatorType();
+ designatorDummy1.setAttributeId("dummyId");
+ matchDummy1.setAttributeDesignator(designatorDummy1);
+
+ allRiskType.getMatch().add(matchDummy1);
+
+ anyRiskType.getAllOf().add(allRiskType);
+
+ target.getAnyOf().add(anyRiskType);
+
+ // create RiskLevel attribute
+ AnyOfType anyRiskLevel = new AnyOfType();
+ AllOfType allRiskLevel = new AllOfType();
+ MatchType matchRiskLevel = new MatchType();
+ // set value
+ AttributeValueType riskLevel = new AttributeValueType();
+ riskLevel.getContent().add("3");
+ matchRiskLevel.setAttributeValue(riskLevel);
+ // set Id
+ AttributeDesignatorType designatorRiskLevel = new AttributeDesignatorType();
+ designatorRiskLevel.setAttributeId("RiskLevel");
+ matchRiskLevel.setAttributeDesignator(designatorRiskLevel);
+ allRiskLevel.getMatch().add(matchRiskLevel);
+
+ // add a dummy MatchType object since while (matchList.size()>1 ...)
+ MatchType matchDummy2 = new MatchType();
+ // set value
+ AttributeValueType dummy2Value = new AttributeValueType();
+ dummy2Value.getContent().add("dummy");
+ matchDummy2.setAttributeValue(dummy2Value);
+ // set Id
+ AttributeDesignatorType designatorDummy2 = new AttributeDesignatorType();
+ designatorDummy2.setAttributeId("dummyId");
+ matchDummy2.setAttributeDesignator(designatorDummy2);
+
+ allRiskLevel.getMatch().add(matchDummy2);
+
+ anyRiskLevel.getAllOf().add(allRiskLevel);
+ target.getAnyOf().add(anyRiskLevel);
+
+ policyType.setTarget(target);
+
+ restAdapter.setPolicyData(policyType);
+
+ controller.prePopulateDCAEMSPolicyData(restAdapter, entity);
+
+ logger.error("restAdapter.getRiskType() : " + restAdapter.getRiskType());
+ logger.error("restAdapter.getRiskLevel() : " + restAdapter.getRiskLevel());
+ logger.error("restAdapter.getGuard() : " + restAdapter.getGuard());
+
+ assertEquals("True", restAdapter.getGuard());
+ assertEquals("3", restAdapter.getRiskLevel());
+ assertEquals("test", restAdapter.getRiskType());
+
+ } catch (Exception e) {
+ logger.error("testPrePopulateDCAEMSPolicyData", e);
+ fail("testPrePopulateDCAEMSPolicyData failed due to: " + e);
+ }
+
+ logger.debug("testPrePopulateDCAEMSPolicyData: exit");
+
+ }
+
+ /**
+ * Run the Map<String,String> convert(String, String) method test
+ */
+
+ @Test
+ public void testConvert(){
+ logger.debug("testConvert: enter");
+
+ String str = "k1=v1,k2=v2,k3=v3";
+ String split = ",";
+ Map<String,String> result = CreateDcaeMicroServiceController.convert(str, split);
+ assertTrue(result != null && result.size() == 3);
+
+ logger.debug("testConvert: exit");
+ }
+
+ /**
+ * Run the Map<String,String> convertMap(Map<String,String>,
+ * Map<String,String>) method test
+ */
+
+ @Test
+ public void testConvertMap(){
+ logger.debug("testConvertMap: enter");
+
+ CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
+ Map<String,String> attributesMap = new HashMap<String, String>();
+ Map<String,String> attributesRefMap = new HashMap<String, String>();
+ Map<String,String> attributesListRefMap = controller.getAttributesListRefMap();
+ Map<String, LinkedList<String>> arrayTextList = controller.getArrayTextList();
+ LinkedList<String> list = new LinkedList<String>();
+
+ attributesMap.put("keyOne", "valueOne");
+ attributesMap.put("keyTwo", "valueTwo");
+ attributesMap.put("keyThree", "valueThree");
+
+ attributesRefMap.put("key4", "value4");
+ attributesRefMap.put("key5", "value5");
+ attributesRefMap.put("key6", "value6");
+
+ attributesListRefMap.put("key7", "value7");
+
+ list.add("l1");
+ list.add("l2");
+ arrayTextList.put("key8", list);
+
+ Map<String,String> result = controller.convertMap(attributesMap, attributesRefMap);
+
+ assertTrue(result != null && result.size() == 8);
+
+ assertTrue(arrayTextList.get("key8").toString().contains("[l1, l2]"));
+
+ logger.debug("testConvertMap: exit");
+ }
+
+ /**
+ * Run the void SetMSModelData(HttpServletRequest, HttpServletResponse)
+ * method test
+ */
+
+ //Ignore it for now due to Stream ended unexpectedly
+ //@Ignore
+ @Test
+ public void testSetMSModelData() {
+
+ logger.debug("testSetMSModelData: enter");
+
+ CreateDcaeMicroServiceController controller = new CreateDcaeMicroServiceController();
+
+ MockHttpServletResponse response = new MockHttpServletResponse();
+
+ HttpServletRequest request = createMock(HttpServletRequest.class);
+ expect(request.getContentType()).andReturn("multipart/form-data; boundary=----WebKitFormBoundaryWcRUaIbC8kXgjr3p");
+ expect(request.getMethod()).andReturn("post");
+ expect(request.getHeader("Content-length")).andReturn("7809");
+
+ expect(request.getContentLength()).andReturn(7809);
+
+ try {
+ // value of fileName needs to be matched to your local directory
+ String fileName = "";
+ try {
+ ClassLoader classLoader = getClass().getClassLoader();
+ fileName = new File(classLoader.getResource("schedulerPolicies1707.xmi").getFile()).getAbsolutePath();
+ } catch (Exception e1) {
+ logger.error("Exception Occured while loading file"+e1);
+ }
+ expect(request.getInputStream()).andReturn(new MockServletInputStream(fileName));
+ expect(request.getCharacterEncoding()).andReturn("UTF-8");
+ expect(request.getContentLength()).andReturn(1024);
+ replay(request);
+
+ controller.SetMSModelData(request, response);
+
+ } catch (Exception e) {
+ logger.error("testSetMSModelData" + e);
+ e.printStackTrace();
+ }
+
+ //assertTrue(false);
+
+ logger.debug("testSetMSModelData: exit");
+ }
+
+ /**
+ *
+ * @ Get File Stream
+ *
+ */
+ private class MockServletInputStream extends ServletInputStream {
+
+ InputStream fis = null;
+ public MockServletInputStream(String fileName) {
+ try {
+ fis = new FileInputStream(fileName);
+ } catch (Exception genExe) {
+ genExe.printStackTrace();
+ }
+ }
+ @Override
+ public int read() throws IOException {
+ if(fis.available() > 0) {
+ return fis.read();
+ }
+ return 0;
+ }
+
+ @Override
+ public int read(byte[] bytes, int len, int size) throws IOException {
+ if(fis.available() > 0) {
+ int length = fis.read(bytes, len, size);
+ return length;
+ }
+ return -1;
+ }
+ @Override
+ public boolean isFinished() {
+ return false;
+ }
+ @Override
+ public boolean isReady() {
+ return false;
+ }
+ @Override
+ public void setReadListener(ReadListener arg0) {
+
+ }
+ }
+
+} \ No newline at end of file
diff --git a/POLICY-SDK-APP/src/test/java/org/openecomp/policy/controller/PDPControllerTest.java b/POLICY-SDK-APP/src/test/java/org/openecomp/policy/controller/PDPControllerTest.java
new file mode 100644
index 000000000..a27ad4b57
--- /dev/null
+++ b/POLICY-SDK-APP/src/test/java/org/openecomp/policy/controller/PDPControllerTest.java
@@ -0,0 +1,98 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.controller;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.UnsupportedEncodingException;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.model.Roles;
+import org.openecomp.policy.xacml.api.pap.EcompPDPGroup;
+import org.openecomp.policy.xacml.std.pap.StdPDPGroup;
+import org.openecomp.policy.xacml.std.pap.StdPDPGroupStatus;
+import org.springframework.mock.web.MockHttpServletResponse;
+
+
+
+public class PDPControllerTest extends Mockito{
+
+ private static Logger logger = FlexLogger.getLogger(PDPControllerTest.class);
+ private Set<EcompPDPGroup> groupsData;
+ private Set<StdPDPGroup> groups;
+ private static List<Object> rolesdata;
+
+ @Before
+ public void setUp() throws Exception{
+ logger.info("setUp: Entering");
+ rolesdata = new ArrayList<>();
+ Roles roles = new Roles();
+ roles.setLoginId("Test");
+ roles.setRole("super-admin");
+ Roles roles1 = new Roles();
+ roles1.setLoginId("Test");
+ roles1.setRole("admin");
+ roles1.setScope("['com','Test']");
+ rolesdata.add(roles);
+ rolesdata.add(roles1);
+
+ groups = new HashSet<>();
+ StdPDPGroup group = new StdPDPGroup();
+ group.setId("default");
+ group.setDefault(true);
+ group.setName("default");
+ group.setDescription("The default group where new PDP's are put.");
+ group.setStatus(new StdPDPGroupStatus());
+ groups.add(group);
+ groupsData = new HashSet<>();
+ for (EcompPDPGroup g : this.groups) {
+ groupsData.add(g);
+ }
+ }
+
+ @Test
+ public void testPDPGroupData(){
+ HttpServletRequest request = mock(HttpServletRequest.class);
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ PolicyController controller = mock(PolicyController.class);
+ PDPController pdpController = new PDPController();
+ pdpController.setJunit(true);;
+ pdpController.setPolicyController(controller);
+ pdpController.setGroupsData(groupsData);
+ when(controller.getRoles("Test")).thenReturn(rolesdata);
+ pdpController.getPDPGroupEntityData(request, response);
+ try {
+ assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("data"));
+ } catch (UnsupportedEncodingException e) {
+ logger.error("Exception Occured"+e);
+ }
+ }
+
+}
diff --git a/POLICY-SDK-APP/src/test/java/org/openecomp/policy/controller/PolicyControllerTest.java b/POLICY-SDK-APP/src/test/java/org/openecomp/policy/controller/PolicyControllerTest.java
new file mode 100644
index 000000000..73f8d755a
--- /dev/null
+++ b/POLICY-SDK-APP/src/test/java/org/openecomp/policy/controller/PolicyControllerTest.java
@@ -0,0 +1,66 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ECOMP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2017 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.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+package org.openecomp.policy.controller;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.io.IOUtils;
+import org.junit.Before;
+import org.junit.Test;
+import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
+import org.openecomp.policy.common.logging.flexlogger.Logger;
+import org.openecomp.policy.rest.dao.CommonClassDao;
+import org.openecomp.policy.rest.jpa.PolicyEntity;
+
+public class PolicyControllerTest {
+
+ private static Logger logger = FlexLogger.getLogger(PolicyControllerTest.class);
+ private static CommonClassDao commonClassDao;
+
+ @Before
+ public void setUp() throws Exception{
+ logger.info("setUp: Entering");
+ commonClassDao = mock(CommonClassDao.class);
+ List<Object> data = new ArrayList<>();
+ String policyData = "";
+ try {
+ ClassLoader classLoader = getClass().getClassLoader();
+ policyData = IOUtils.toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml"));
+ } catch (Exception e1) {
+ e1.printStackTrace();
+ }
+ PolicyEntity entity = new PolicyEntity();
+ entity.setPolicyName("Config_SampleTest.1.xml");
+ entity.setPolicyData(policyData);
+ entity.setScope("com");
+ data.add(entity);
+
+ when(commonClassDao.getDataByQuery("FROM PolicyEntity where policyName = 'Config_SampleTest1206.1.xml' and scope ='com'")).thenReturn(data);
+ }
+
+ @Test
+ public void dummy(){
+ System.out.println("Dummy");
+ }
+}
diff --git a/POLICY-SDK-APP/src/test/resources/Config_SampleTest1206.1.xml b/POLICY-SDK-APP/src/test/resources/Config_SampleTest1206.1.xml
new file mode 100644
index 000000000..5c32cd4f1
--- /dev/null
+++ b/POLICY-SDK-APP/src/test/resources/Config_SampleTest1206.1.xml
@@ -0,0 +1,90 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<Policy xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" PolicyId="urn:com:xacml:policy:id:0b67998b-57e2-4e25-9ea9-f9154bf18df1" Version="1" RuleCombiningAlgId="urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides">
+ <Description>SampleTest1206@CreatedBy:test@CreatedBy:@ModifiedBy:test@ModifiedBy:</Description>
+ <Target>
+ <AnyOf>
+ <AllOf>
+ <Match MatchId="org.openecomp.function.regex-match">
+ <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">com.Config_SampleTest1206.1.xml</AttributeValue>
+ <AttributeDesignator Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject" AttributeId="PolicyName" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/>
+ </Match>
+ </AllOf>
+ <AllOf>
+ <Match MatchId="org.openecomp.function.regex-match">
+ <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">success</AttributeValue>
+ <AttributeDesignator Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject" AttributeId="ECOMPName" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/>
+ </Match>
+ <Match MatchId="org.openecomp.function.regex-match">
+ <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">PROD</AttributeValue>
+ <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="RiskType" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/>
+ </Match>
+ <Match MatchId="org.openecomp.function.regex-match">
+ <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">1</AttributeValue>
+ <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="RiskLevel" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/>
+ </Match>
+ <Match MatchId="org.openecomp.function.regex-match">
+ <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">True</AttributeValue>
+ <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="guard" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/>
+ </Match>
+ <Match MatchId="org.openecomp.function.regex-match">
+ <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">NA</AttributeValue>
+ <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="TTLDate" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/>
+ </Match>
+ <Match MatchId="org.openecomp.function.regex-match">
+ <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">SampleTest1206</AttributeValue>
+ <AttributeDesignator Category="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject" AttributeId="ConfigName" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/>
+ </Match>
+ </AllOf>
+ </AnyOf>
+ </Target>
+ <Rule RuleId="urn:com:xacml:rule:id:7e46d503-af54-4ea5-a86c-9eb6dd1f4f43" Effect="Permit">
+ <Target>
+ <AnyOf>
+ <AllOf>
+ <Match MatchId="urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case">
+ <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">ACCESS</AttributeValue>
+ <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:action" AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/>
+ </Match>
+ <Match MatchId="urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case">
+ <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">Config</AttributeValue>
+ <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/>
+ </Match>
+ </AllOf>
+ </AnyOf>
+ </Target>
+ <AdviceExpressions>
+ <AdviceExpression AdviceId="configID" AppliesTo="Permit">
+ <AttributeAssignmentExpression AttributeId="type" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" Issuer="">
+ <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">Configuration</AttributeValue>
+ </AttributeAssignmentExpression>
+ <AttributeAssignmentExpression AttributeId="URLID" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" Issuer="">
+ <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#anyURI">$URL/Config/com.Config_SampleTest1206.1.txt</AttributeValue>
+ </AttributeAssignmentExpression>
+ <AttributeAssignmentExpression AttributeId="PolicyName" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" Issuer="">
+ <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">com.Config_SampleTest1206.1.xml</AttributeValue>
+ </AttributeAssignmentExpression>
+ <AttributeAssignmentExpression AttributeId="VersionNumber" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" Issuer="">
+ <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">1</AttributeValue>
+ </AttributeAssignmentExpression>
+ <AttributeAssignmentExpression AttributeId="matching:ECOMPName" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" Issuer="">
+ <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">success</AttributeValue>
+ </AttributeAssignmentExpression>
+ <AttributeAssignmentExpression AttributeId="matching:ConfigName" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" Issuer="">
+ <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">SampleTest1206</AttributeValue>
+ </AttributeAssignmentExpression>
+ <AttributeAssignmentExpression AttributeId="RiskType" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" Issuer="">
+ <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">PROD</AttributeValue>
+ </AttributeAssignmentExpression>
+ <AttributeAssignmentExpression AttributeId="RiskLevel" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" Issuer="">
+ <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">1</AttributeValue>
+ </AttributeAssignmentExpression>
+ <AttributeAssignmentExpression AttributeId="guard" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" Issuer="">
+ <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">True</AttributeValue>
+ </AttributeAssignmentExpression>
+ <AttributeAssignmentExpression AttributeId="TTLDate" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" Issuer="">
+ <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">NA</AttributeValue>
+ </AttributeAssignmentExpression>
+ </AdviceExpression>
+ </AdviceExpressions>
+ </Rule>
+</Policy>
diff --git a/POLICY-SDK-APP/src/test/resources/logback.xml b/POLICY-SDK-APP/src/test/resources/logback.xml
new file mode 100644
index 000000000..b119a4e3b
--- /dev/null
+++ b/POLICY-SDK-APP/src/test/resources/logback.xml
@@ -0,0 +1,254 @@
+<!--
+ ============LICENSE_START=======================================================
+ ECOMP-PAP-REST
+ ================================================================================
+ Copyright (C) 2017 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.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ ============LICENSE_END=========================================================
+ -->
+
+<configuration scan="true" scanPeriod="3 seconds" debug="true">
+ <!--<jmxConfigurator /> -->
+ <!-- directory path for all other type logs -->
+ <property name="logDir" value="logs" />
+
+ <!-- directory path for debugging type logs -->
+ <property name="debugDir" value="logs" />
+
+ <!-- specify the component name
+ <ECOMP-component-name>::= "MSO" | "DCAE" | "ASDC " | "AAI" |"Policy" | "SDNC" | "AC" -->
+ <property name="componentName" value="Policy"></property>
+ <property name="subComponentName" value="XACML-PAP-REST"></property>
+
+ <!-- log file names -->
+ <property name="errorLogName" value="error" />
+ <property name="metricsLogName" value="metrics" />
+ <property name="auditLogName" value="audit" />
+ <property name="debugLogName" value="debug" />
+
+
+ <!-- modified time stamp format -->
+
+ <!-- A U D I T
+ <property name="defaultAuditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+ <property name="defaultAuditPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{ElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+ -->
+ <property name="defaultAuditPattern" value="%X{TransactionBeginTimestamp}|%X{TransactionEndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{partnerName}|%X{statusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{TransactionElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+
+
+
+ <!-- M E T R I C
+ <property name="defaultMetricPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+ -->
+ <property name="defaultMetricPattern" value="%X{MetricBeginTimestamp}|%X{MetricEndTimestamp}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{partnerName}|%X{targetEntity}|%X{targetServiceName}|%X{statusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%p|%X{severity}|%X{serverIpAddress}|%X{MetricElapsedTime}|%X{server}|%X{clientIpAddress}|%c||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+
+
+
+
+ <!-- E R R O R
+ <property name="defaultErrorPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{RequestId}|%thread|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{ErrorCategory}|%X{ErrorCode}|%X{ErrorDesciption}|%msg%n" />
+ -->
+ <property name="defaultErrorPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{requestId}|%t|%X{serviceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{ErrorCategory}|%X{ErrorCode}|%X{ErrorDesciption}|%msg%n" />
+
+
+
+ <!-- D E B U G
+ <property name="debugLoggerPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{Timer}|[%caller{3}]|%msg%n" />
+ <property name="debugLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" /> -->
+ -->
+ <property name="debugLoggerPattern" value="%d{yyyy-MM-dd'T'HH:mm:ss.SSS+00:00, UTC}|%X{RequestId}|%msg%n" />
+
+
+
+ <!-- D E F A U L T
+ <property name="defaultPatternOld" value="%d{MM/dd-HH:mm:ss.SSS}|%logger|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServiceName}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Timer}|%msg%n" />
+ <property name="defaultPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{ServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}||%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}|%msg%n" />
+ -->
+ <property name="defaultPattern" value="%d{&quot;yyyy-MM-dd'T'HH:mm:ss.SSSXXX&quot;, UTC}|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{server}|%X{clientIpAddress}|%c||%msg%n" />
+
+
+
+ <!-- P A T H
+ <property name="logDirectory" value="${logDir}/${componentName}/${subComponentName}" />
+ <property name="debugLogDirectory" value="${debugDir}/${componentName}/${subComponentName}" />
+
+ -->
+ <property name="logDirectory" value="${catalina.base}/${logDir}/${componentName}/${subComponentName}" />
+ <property name="debugLogDirectory" value="${catalina.base}/${debugDir}/${componentName}/${subComponentName}" />
+
+
+
+
+ <!-- Example evaluator filter applied against console appender -->
+ <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+ <encoder>
+ <pattern>${defaultPattern}</pattern>
+ </encoder>
+ </appender>
+
+ <!-- ============================================================================ -->
+ <!-- EELF Appenders -->
+ <!-- ============================================================================ -->
+
+ <!-- The EELFAppender is used to record events to the general application
+ log -->
+
+ <!-- EELF Audit Appender. This appender is used to record audit engine
+ related logging events. The audit logger and appender are specializations
+ of the EELF application root logger and appender. This can be used to segregate
+ Policy engine events from other components, or it can be eliminated to record
+ these events as part of the application root log. -->
+
+ <appender name="EELFAudit"
+ class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${auditLogName}.log</file>
+ <rollingPolicy
+ class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${logDirectory}/${auditLogName}.%i.log.zip
+ </fileNamePattern>
+ <minIndex>1</minIndex>
+ <maxIndex>9</maxIndex>
+ </rollingPolicy>
+ <triggeringPolicy
+ class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
+ <maxFileSize>5MB</maxFileSize>
+ </triggeringPolicy>
+ <encoder>
+ <pattern>${defaultAuditPattern}</pattern>
+ </encoder>
+ </appender>
+
+ <appender name="asyncEELFAudit" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize>
+ <appender-ref ref="EELFAudit" />
+ </appender>
+
+
+
+
+<appender name="EELFMetrics"
+ class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${metricsLogName}.log</file>
+ <rollingPolicy
+ class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${logDirectory}/${metricsLogName}.%i.log.zip
+ </fileNamePattern>
+ <minIndex>1</minIndex>
+ <maxIndex>9</maxIndex>
+ </rollingPolicy>
+ <triggeringPolicy
+ class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
+ <maxFileSize>5MB</maxFileSize>
+ </triggeringPolicy>
+ <encoder>
+ <!-- <pattern>"%d{HH:mm:ss.SSS} [%thread] %-5level %logger{1024} -
+ %msg%n"</pattern> -->
+ <pattern>${defaultMetricPattern}</pattern>
+ </encoder>
+ </appender>
+
+ <appender name="asyncEELFMetrics" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize>
+ <appender-ref ref="EELFMetrics"/>
+ </appender>
+
+
+
+
+ <appender name="EELFError"
+ class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${errorLogName}.log</file>
+ <rollingPolicy
+ class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${logDirectory}/${errorLogName}.%i.log.zip
+ </fileNamePattern>
+ <minIndex>1</minIndex>
+ <maxIndex>9</maxIndex>
+ </rollingPolicy>
+ <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
+ <level>ERROR</level>
+ </filter>
+ <triggeringPolicy
+ class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
+ <maxFileSize>5MB</maxFileSize>
+ </triggeringPolicy>
+ <encoder>
+ <pattern>${defaultErrorPattern}</pattern>
+ </encoder>
+ </appender>
+
+ <appender name="asyncEELFError" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize>
+ <appender-ref ref="EELFError"/>
+ </appender>
+
+
+
+ <appender name="EELFDebug"
+ class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${debugLogDirectory}/${debugLogName}.log</file>
+ <rollingPolicy
+ class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${debugLogDirectory}/${debugLogName}.%i.log.zip
+ </fileNamePattern>
+ <minIndex>1</minIndex>
+ <maxIndex>9</maxIndex>
+ </rollingPolicy>
+ <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
+ <level>INFO</level>
+ </filter>
+ <triggeringPolicy
+ class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
+ <maxFileSize>5MB</maxFileSize>
+ </triggeringPolicy>
+ <encoder>
+ <pattern>${debugLoggerPattern}</pattern>
+ </encoder>
+ </appender>
+
+ <appender name="asyncEELFDebug" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize>
+ <appender-ref ref="EELFDebug" />
+ <includeCallerData>true</includeCallerData>
+ </appender>
+
+
+ <!-- ============================================================================ -->
+ <!-- EELF loggers -->
+ <!-- ============================================================================ -->
+
+ <logger name="com.att.eelf.audit" level="info" additivity="false">
+ <appender-ref ref="asyncEELFAudit" />
+ </logger>
+
+ <logger name="com.att.eelf.metrics" level="info" additivity="false">
+ <appender-ref ref="asyncEELFMetrics" />
+ </logger>
+
+ <logger name="com.att.eelf.error" level="error" additivity="false">
+ <appender-ref ref="asyncEELFError" />
+ </logger>
+
+ <logger name="com.att.eelf.debug" level="info" additivity="false">
+ <appender-ref ref="asyncEELFDebug" />
+ </logger>
+
+
+
+ <root level="INFO">
+ <appender-ref ref="asyncEELFDebug" />
+ <appender-ref ref="asyncEELFError" />
+ </root>
+
+</configuration>
diff --git a/POLICY-SDK-APP/src/test/resources/policy_tosca_tca_v1707.yml b/POLICY-SDK-APP/src/test/resources/policy_tosca_tca_v1707.yml
new file mode 100644
index 000000000..0c30ceea0
--- /dev/null
+++ b/POLICY-SDK-APP/src/test/resources/policy_tosca_tca_v1707.yml
@@ -0,0 +1,65 @@
+tosca_definitions_version: tosca_simple_yaml_1_0_0
+
+node_types:
+ # policy root node
+ policy.nodes.Root:
+ derived_from: tosca.nodes.Root
+ properties:
+ policyName:
+ type: string
+ required: true
+ policyVersion:
+ type: string
+ required: true
+ policyScope:
+ type: string
+ required: true
+ policyDescription:
+ type: string
+ required: false
+
+ # virtual policy node for string matcher
+ policy.nodes.tca:
+ derived_from: policy.nodes.Root
+ properties:
+ functionalRole:
+ type: string
+ required: true
+ default: "ClosedLoop_F5-d925ed73-8231-4d02-9545-db4e101f88f8"
+ policyName:
+ type: string
+ required: true
+ default: "configuration.dcae.microservice.tca.xml"
+ policyVersion:
+ type: string
+ required: true
+ default: "v0.0.1"
+ threshholds:
+ type: list
+ entry_schema:
+ - type:policy.data.Threshold
+
+data_types:
+ policy.data.Threshold:
+ derived_from: tosca.nodes.Root
+ properties:
+ closedLoopControlName:
+ type: string
+ required: true
+ version:
+ type: string
+ required: true
+ default: "1.0.2"
+ fieldPath:
+ type: string
+ required: true
+ thresholdValue:
+ type: integer
+ required: true
+ direction:
+ type: string
+ required: true
+ severity:
+ type: string
+ required: true
+
diff --git a/POLICY-SDK-APP/src/test/resources/schedulerPolicies1707.xmi b/POLICY-SDK-APP/src/test/resources/schedulerPolicies1707.xmi
new file mode 100644
index 000000000..22afa23a2
--- /dev/null
+++ b/POLICY-SDK-APP/src/test/resources/schedulerPolicies1707.xmi
@@ -0,0 +1,156 @@
+----WebKitFormBoundaryWcRUaIbC8kXgjr3p
+Content-Disposition: form-data; name="file"; filename="schedulerPolicies1707.xmi"
+
+<?xml version="1.0" encoding="ASCII"?>
+<ecore:EPackage xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore" name="scheduler" nsURI="org.ecomp.test.scheduler" nsPrefix="scheduler">
+ <eAnnotations source="http://www.eclipse.org/emf/2011/Xcore">
+ <details key="ecomp" value="http://ecomp.org.com"/>
+ <details key="policy" value="http://ecomp.org.com/policy"/>
+ </eAnnotations>
+ <eClassifiers xsi:type="ecore:EClass" name="TimeLimitAndVerticalTopology" eSuperTypes="//SniroPolicyMetaInfo">
+ <eAnnotations source="http://ecomp.org.com/policy">
+ <details key="policyTemplate" value="SNIRO-SCHEDULER"/>
+ </eAnnotations>
+ <eStructuralFeatures xsi:type="ecore:EAttribute" name="type" unique="false" eType="//TimeLimitNVerticalTopologyType">
+ <eAnnotations source="http://ecomp.org.com/policy">
+ <details key="matching" value="true"/>
+ </eAnnotations>
+ <eAnnotations source="http://ecomp.org.com">
+ <details key="type" value="configuration"/>
+ </eAnnotations>
+ </eStructuralFeatures>
+ <eStructuralFeatures xsi:type="ecore:EAttribute" name="serviceType" unique="false">
+ <eAnnotations source="http://ecomp.org.com">
+ <details key="type" value="configuration"/>
+ </eAnnotations>
+ <eType xsi:type="ecore:EDataType" href="http://www.eclipse.org/emf/2002/Ecore#//EString"/>
+ </eStructuralFeatures>
+ <eStructuralFeatures xsi:type="ecore:EAttribute" name="nodeType" unique="false" upperBound="-1" eType="//EntityType">
+ <eAnnotations source="http://ecomp.org.com">
+ <details key="type" value="configuration"/>
+ </eAnnotations>
+ </eStructuralFeatures>
+ <eStructuralFeatures xsi:type="ecore:EAttribute" name="conflictScope" unique="false" eType="//ConflictScope">
+ <eAnnotations source="http://ecomp.org.com">
+ <details key="type" value="configuration"/>
+ </eAnnotations>
+ </eStructuralFeatures>
+ <eStructuralFeatures xsi:type="ecore:EReference" name="timeSchedule" eType="//TimeSchedule" containment="true" resolveProxies="false">
+ <eAnnotations source="http://ecomp.org.com">
+ <details key="type" value="configuration"/>
+ </eAnnotations>
+ </eStructuralFeatures>
+ </eClassifiers>
+ <eClassifiers xsi:type="ecore:EClass" name="TimeSchedule">
+ <eStructuralFeatures xsi:type="ecore:EReference" name="allowedPeriodicTime" upperBound="-1" eType="//AllowedPeriodicTime" containment="true" resolveProxies="false">
+ <eAnnotations source="http://ecomp.org.com">
+ <details key="type" value="configuration"/>
+ </eAnnotations>
+ </eStructuralFeatures>
+ </eClassifiers>
+ <eClassifiers xsi:type="ecore:EClass" name="TimeRange">
+ <eStructuralFeatures xsi:type="ecore:EAttribute" name="start_time" unique="false">
+ <eAnnotations source="http://ecomp.org.com">
+ <details key="type" value="configuration"/>
+ </eAnnotations>
+ <eType xsi:type="ecore:EDataType" href="http://www.eclipse.org/emf/2002/Ecore#//EString"/>
+ </eStructuralFeatures>
+ <eStructuralFeatures xsi:type="ecore:EAttribute" name="end_time" unique="false">
+ <eAnnotations source="http://ecomp.org.com">
+ <details key="type" value="configuration"/>
+ </eAnnotations>
+ <eType xsi:type="ecore:EDataType" href="http://www.eclipse.org/emf/2002/Ecore#//EString"/>
+ </eStructuralFeatures>
+ </eClassifiers>
+ <eClassifiers xsi:type="ecore:EClass" name="AllowedPeriodicTime">
+ <eStructuralFeatures xsi:type="ecore:EAttribute" name="day" unique="false" eType="//DayType">
+ <eAnnotations source="http://ecomp.org.com">
+ <details key="type" value="configuration"/>
+ </eAnnotations>
+ </eStructuralFeatures>
+ <eStructuralFeatures xsi:type="ecore:EReference" name="timeRange" upperBound="-1" eType="//TimeRange" containment="true" resolveProxies="false">
+ <eAnnotations source="http://ecomp.org.com">
+ <details key="type" value="configuration"/>
+ </eAnnotations>
+ </eStructuralFeatures>
+ </eClassifiers>
+ <eClassifiers xsi:type="ecore:EClass" name="SniroPolicyMetaInfo">
+ <eAnnotations source="http://ecomp.org.com/policy">
+ <details key="policyTemplate" value="SNIRO"/>
+ </eAnnotations>
+ <eStructuralFeatures xsi:type="ecore:EAttribute" name="identity" unique="false">
+ <eAnnotations source="http://ecomp.org.com">
+ <details key="type" value="configuration"/>
+ </eAnnotations>
+ <eType xsi:type="ecore:EDataType" href="http://www.eclipse.org/emf/2002/Ecore#//EString"/>
+ </eStructuralFeatures>
+ <eStructuralFeatures xsi:type="ecore:EReference" name="policyScope" eType="//Scope" containment="true" resolveProxies="false">
+ <eAnnotations source="http://ecomp.org.com/policy">
+ <details key="matching" value="true"/>
+ </eAnnotations>
+ <eAnnotations source="http://ecomp.org.com">
+ <details key="type" value="configuration"/>
+ </eAnnotations>
+ </eStructuralFeatures>
+ </eClassifiers>
+ <eClassifiers xsi:type="ecore:EClass" name="Scope">
+ <eStructuralFeatures xsi:type="ecore:EAttribute" name="serviceType" unique="false" upperBound="-1" eType="//ServiceType">
+ <eAnnotations source="http://ecomp.org.com">
+ <details key="type" value="configuration"/>
+ </eAnnotations>
+ </eStructuralFeatures>
+ <eStructuralFeatures xsi:type="ecore:EAttribute" name="entityType" unique="false" upperBound="-1" eType="//EntityType">
+ <eAnnotations source="http://ecomp.org.com">
+ <details key="type" value="configuration"/>
+ </eAnnotations>
+ </eStructuralFeatures>
+ <eStructuralFeatures xsi:type="ecore:EAttribute" name="aicZone" unique="false" upperBound="-1">
+ <eAnnotations source="http://ecomp.org.com">
+ <details key="type" value="configuration"/>
+ </eAnnotations>
+ <eType xsi:type="ecore:EDataType" href="http://www.eclipse.org/emf/2002/Ecore#//EString"/>
+ </eStructuralFeatures>
+ </eClassifiers>
+ <eClassifiers xsi:type="ecore:EEnum" name="WorkflowType">
+ <eLiterals name="softwareDownload" value="1"/>
+ <eLiterals name="softwareUpgrade" value="2"/>
+ <eLiterals name="configurationChange" value="3"/>
+ </eClassifiers>
+ <eClassifiers xsi:type="ecore:EEnum" name="ServiceType">
+ <eLiterals name="networkOnDemand" value="1"/>
+ <eLiterals name="changeManagement" value="2"/>
+ </eClassifiers>
+ <eClassifiers xsi:type="ecore:EEnum" name="ConflictScope">
+ <eLiterals name="vnf" value="1"/>
+ <eLiterals name="vnf_pserver" value="2"/>
+ <eLiterals name="vnf_zone" value="3"/>
+ </eClassifiers>
+ <eClassifiers xsi:type="ecore:EEnum" name="EntityType">
+ <eLiterals name="vnf" value="1"/>
+ <eLiterals name="pServer" value="2"/>
+ <eLiterals name="vServer" value="3"/>
+ </eClassifiers>
+ <eClassifiers xsi:type="ecore:EEnum" name="DayType">
+ <eLiterals name="weekday" value="1"/>
+ <eLiterals name="weekend" value="2"/>
+ <eLiterals name="holiday" value="3"/>
+ <eLiterals name="mon" value="4"/>
+ <eLiterals name="tue" value="5"/>
+ <eLiterals name="wed" value="6"/>
+ <eLiterals name="thu" value="7"/>
+ <eLiterals name="fri" value="8"/>
+ <eLiterals name="sat" value="9"/>
+ <eLiterals name="sun" value="10"/>
+ </eClassifiers>
+ <eClassifiers xsi:type="ecore:EEnum" name="TimeLimitNVerticalTopologyType">
+ <eLiterals name="timeLimitAndVerticalTopology"/>
+ </eClassifiers>
+ <eClassifiers xsi:type="ecore:EDataType" name="UUID" instanceClassName="java.util.UUID"/>
+</ecore:EPackage>
+
+------WebKitFormBoundaryWcRUaIbC8kXgjr3p
+Content-Disposition: form-data; name="file"; filename="schedulerPolicies1707.xmi"
+Content-Type: application/octet-stream
+
+
+------WebKitFormBoundaryWcRUaIbC8kXgjr3p-- \ No newline at end of file