Remove auto generated rule to the drl

Issue-ID: POLICY-488
Change-Id: Id6915407a6f030b77ae2d18ad3665af9d0feb34b
Signed-off-by: pa834y <pa834y@att.com>
diff --git a/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSHandler.java b/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSHandler.java
index c0a9cd2..b460fb8 100644
--- a/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSHandler.java
+++ b/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSHandler.java
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP Policy Engine
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018 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.
@@ -120,6 +120,8 @@
 	 */
 	@Override
 	public void runOnNotification(PDPNotification notification){
+		// reset the BRMSPush data structures
+		bRMSPush.resetDS();
 		if(notification.getNotificationType().equals(NotificationType.REMOVE)){
 			removedPolicies(notification.getRemovedPolicies());
 		}else if(notification.getNotificationType().equals(NotificationType.UPDATE)|| notification.getNotificationType().equals(NotificationType.BOTH)){
diff --git a/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSPush.java b/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSPush.java
index ac1d0ac..b76812b 100644
--- a/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSPush.java
+++ b/BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSPush.java
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP Policy Engine
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018 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.
@@ -374,6 +374,11 @@
         if (flag)
             syncGroupInfo();
     }
+    
+    public void resetDS(){
+    	resetModifiedGroups();
+        controllers = new ArrayList<>();
+    }
 
     private static void resetModifiedGroups() {
         modifiedGroups = new HashMap<>();
@@ -410,6 +415,7 @@
                         PEDependency dependency = PolicyUtils.jsonStringToObject(value,
                                 PEDependency.class);
                         userControllerName = key.replaceFirst("$controller:", "");
+                        LOGGER.info("addRule: userControllerName - " + userControllerName + ", dependency: - " + dependency);
                         addToGroup(userControllerName, dependency);
                     } catch (Exception e) {
                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while resolving Controller: " + e);
@@ -445,6 +451,7 @@
             // If the key is not got as parameters set by the user, setting the default value for kSessionName as
             // closedLoop
             if (kSessionName == null) {
+            	LOGGER.info("kSessionName is null, selectedName is  : " + selectedName );
                 if (selectedName == defaultName) {
                     kSessionName = "closedloop";
                 } else {
@@ -747,6 +754,7 @@
                 InvocationResult result = null;
 		String group = entry.getKey();
                 try {
+                	LOGGER.info("PushRules: ModifiedGroups, Key: " + group + ", Value: " + entry.getValue());
                     InvocationRequest request = new DefaultInvocationRequest();
                     setVersion(group);
                     createPom(group);
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java
index 3ed2ee3..4de65fd 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP-PAP-REST
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -86,7 +86,7 @@
 
 		Map<String,String> copyMap=new HashMap<>();
 		copyMap.putAll(brmsParamBody);
-		copyMap.put("policyName", policyName.substring(0, policyName.replace(".xml", "").lastIndexOf(".")));
+		copyMap.put("policyName", policyName.substring(0, policyName.replace(".xml", "").lastIndexOf('.')));
 		copyMap.put("policyScope", policyAdapter.getDomainDir());
 		copyMap.put("policyVersion",policyAdapter.getHighestVersion().toString());
 		copyMap.put("unique", ("p"+policyName+UUID.randomUUID().toString()).replaceAll("[^A-Za-z0-9]", ""));
@@ -123,12 +123,10 @@
 	
 	// Saving the Configurations file at server location for config policy.
 	protected void saveConfigurations(String policyName, String ruleBody) {
-		try {
-			if (policyName.endsWith(".xml")) {
-				policyName = policyName.substring(0,
-						policyName.lastIndexOf(".xml"));
-			}
-			PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".txt");
+	    if (policyName.endsWith(".xml")) {
+            policyName = policyName.substring(0, policyName.lastIndexOf(".xml"));
+        }
+		try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".txt")) {
 			String expandedBody=expandConfigBody(ruleBody,policyAdapter.getBrmsParamBody());
 			out.println(expandedBody);
 			policyAdapter.setJsonBody(expandedBody);
@@ -251,7 +249,7 @@
 					if (flag) {
 						params.append(line);
 					}
-					if (line.contains("declare PapParams")) {
+					if (line.contains("declare Params")) {
 						params.append(line);
 						flag = true;
 					}
@@ -259,7 +257,7 @@
 						break;
 					}
 				}
-				String param = params.toString().replace("declare PapParams", "").replace("end", "")
+				String param = params.toString().replace("declare Params", "").replace("end", "")
 						.replaceAll("\\s+", "");
 				String[] components = param.split(":");
 				String caption = "";
@@ -327,60 +325,26 @@
 		
 		if (policyAdapter.getData() != null) {	
 			Map<String,String> ruleAndUIValue= policyAdapter.getBrmsParamBody();
-			String tempateValue= ruleAndUIValue.get("templateName");
-			String valueFromDictionary= getValueFromDictionary(tempateValue);
+			String templateValue= ruleAndUIValue.get("templateName");
+			String valueFromDictionary= getValueFromDictionary(templateValue);
 			
-			//Get the type of the UI Fields. 
-			Map<String,String> typeOfUIField=findType(valueFromDictionary);
-			StringBuilder generatedRule = new StringBuilder();
 			StringBuilder body = new StringBuilder();
 			
 			try {
-				
-				try {
-					body.append("/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " +
-								"<$%BRMSParamTemplate=" + tempateValue + "%$> \n */ \n");
-					body.append(valueFromDictionary + "\n");
-					generatedRule.append("rule \"" +policyName.substring(0, policyName.replace(".xml", "").lastIndexOf(".")) +".PapParams\" \n\tsalience 1000 \n\twhen\n\tthen\n\t\tPapParams params = new PapParams();");
-					
-					//We first read the map data structure(ruleAndUIValue) received from the PAP-ADMIN
-					//We ignore if the key is "templateName as we are interested only in the UI fields and its value. 
-					//We have one more map data structure(typeOfUIField) created by parsing the Drools rule. 
-					//From the type of the UI field(String/int) we structure whether to put the "" or not. 
-					for (Map.Entry<String, String> entry : ruleAndUIValue.entrySet()) {
-						if(entry.getKey()!="templateName")
-						{
-							for(Map.Entry<String, String> fieldType:typeOfUIField.entrySet())
-							{
-								if(fieldType.getKey().equalsIgnoreCase(entry.getKey()))
-								{
-									String key = entry.getKey().substring(0, 1).toUpperCase() + entry.getKey().substring(1); 
-									if(fieldType.getValue()=="String")
-									{
-										//Type is String
-										generatedRule.append("\n\t\tparams.set"
-												+ key + "(\""
-												+ entry.getValue() + "\");");
-									}
-									else{
-									    generatedRule.append("\n\t\tparams.set"
-												+ key  + "("
-												+  entry.getValue() + ");");
-									}
-								}
-							}
-						}
-					}
-					
-					generatedRule.append("\n\t\tinsert(params);\nend");
-					LOGGER.info("New rule generated with :" + generatedRule);
-					body.append(generatedRule);
-				} catch (Exception e) {
-					PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", "Exception saving policy");
-				}
+			    body.append("/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " +
+			            "<$%BRMSParamTemplate=" + templateValue + "%$> \n");
+			    body.append("<%$Values=");
+			    for (Map.Entry<String, String> entry : ruleAndUIValue.entrySet()) {
+			        String uiKey = entry.getKey();
+			        if(!"templateName".equals(uiKey)) {
+			            body.append(uiKey+":-:"+entry.getValue()+":|:");
+			        }
+			    }
+			    body.append("$%> \n*/ \n");
+			    body.append(valueFromDictionary + "\n");
 			}
 			catch (Exception e) {
-				PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", "Exception saving policy");
+			    PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", "Exception saving policy");
 			}
 			
 			saveConfigurations(policyName,body.toString());
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/XACMLPAPTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/XACMLPAPTest.java
index 2b84cca..ca2b679 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/XACMLPAPTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/XACMLPAPTest.java
@@ -335,7 +335,7 @@
         template.setUserCreatedBy(userInfo);
         String rule = "package com.sample;\n"
                 + "import com.sample.DroolsTest.Message;\n"
-                + "declare PapParams\n"
+                + "declare Params\n"
                 + "samPoll : int\n"
                 + "value : String\n"
                 + "end\n"
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/BRMSPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/BRMSPolicyTest.java
index bb537db..c13d1f1 100644
--- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/BRMSPolicyTest.java
+++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/BRMSPolicyTest.java
@@ -46,8 +46,8 @@
 	
 	@Test
 	public void testReadFile() throws IOException {
-		String goodRule = "declare PapParams\nparam1 : int\nend\n";
-		String badRule = "declare PapParams\nparam1+ : int\nend\n";
+		String goodRule = "declare Params\nparam1 : int\nend\n";
+		String badRule = "declare Params\nparam1+ : int\nend\n";
 		assertEquals(CreateBRMSRuleTemplate.validateRuleParams(goodRule), true);
 		assertEquals(CreateBRMSRuleTemplate.validateRuleParams(badRule), false);
 	}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java
index df1ca6a..40cceea 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP Policy Engine
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -28,6 +28,7 @@
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Map.Entry;
 import java.util.Set;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
@@ -175,7 +176,7 @@
 					if (flag) {
 						params.append(line);
 					}
-					if (line.contains("declare PapParams")) {
+					if (line.contains("declare Params")) {
 						params.append(line);
 						flag = true;
 					}
@@ -183,7 +184,7 @@
 						break;
 					}
 				}
-				params = new StringBuilder(params.toString().replace("declare PapParams", "").replace("end", "").replaceAll("\\s+", ""));
+				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++) {
@@ -363,6 +364,17 @@
 						value = value.replace(brmsTemplateVlaue, "");
 						policyAdapter.setRuleName(value);
 					}
+					if(line.contains("<%$Values=")) {
+					    String value = line.substring(line.indexOf("<%$"), line.indexOf("$%>"));
+					    value = value.replaceAll("<%\\$Values=", "");
+					    for( String keyValue : value.split(":\\|:")) {
+					        String[] pair = keyValue.split(":-:");
+					        if (pair != null && pair.length > 0) {
+					        	dynamicLayoutMap.put(pair[0], (pair.length > 1) ? pair[1] : "");
+					        }
+					    }
+					    return;
+					}
 					if (line.startsWith("/*")) {
 						comment = true;
 						continue;
@@ -402,7 +414,7 @@
 					if (flag) {
 						params.append(line);
 					}
-					if (line.contains("rule") && line.contains(".PapParams\"")) {
+					if (line.contains("rule") && line.contains(".Params\"")) {
 						params.append(line);
 						flag = true;
 					}
@@ -410,8 +422,8 @@
 						break;
 					}
 				}
-				params = new StringBuilder(params.substring(params.indexOf(".PapParams\"")+ 11));
-				params = new StringBuilder(params.toString().replaceAll("\\s+", "").replace("salience1000whenthenPapParamsparams=newPapParams();","")
+				params = new StringBuilder(params.substring(params.indexOf(".Params\"")+ 11));
+				params = new StringBuilder(params.toString().replaceAll("\\s+", "").replace("salience1000whenthenParamsparams=newParams();","")
                         .replace("insert(params);end", "")
                         .replace("params.set", ""));
 				String[] components = params.toString().split("\\);");
@@ -459,30 +471,23 @@
 			}
 
 			String body;
+			body = findRule((String) policyData.getRuleName()) + "\n";
+			StringBuilder generatedMetadata = new StringBuilder();
+			generatedMetadata.append("/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " +
+					brmsTemplateVlaue + policyData.getRuleName() + "%$> \n */ \n");
 
-			body = "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " +
-					brmsTemplateVlaue + policyData.getRuleName() + "%$> \n */ \n";
-			body = body + findRule((String) policyData.getRuleName()) + "\n";
-			StringBuilder generatedRule = new StringBuilder();
-			generatedRule.append("rule \""+ policyData.getDomainDir().replace("\\", ".") +".Config_BRMS_Param_" + policyData.getPolicyName()+".PapParams\" \n\tsalience 1000 \n\twhen\n\tthen\n\t\tPapParams params = new PapParams();");
-
-			if(policyData.getRuleData().size() > 0){ 
-				for(Object keyValue: policyData.getRuleData().keySet()){ 
-					String key = keyValue.toString().substring(0, 1).toUpperCase() + keyValue.toString().substring(1); 
-					if (string.equals(keyValue)) { 
-						generatedRule.append("\n\t\tparams.set" 
-								+ key + "(\"" 
-								+ policyData.getRuleData().get(keyValue).toString() + "\");"); 
-					} else { 
-						generatedRule.append("\n\t\tparams.set" 
-								+ key + "(" 
-								+ policyData.getRuleData().get(keyValue).toString() + ");"); 
-					} 
-				} 
+			if(policyData.getDynamicLayoutMap().size() > 0){
+				generatedMetadata.append("/* <%$Values=");
+			    for (Entry<?, ?> entry : policyData.getRuleData().entrySet()) {
+			        String uiKey = (String) entry.getKey();
+			        if(!"templateName".equals(uiKey)) {
+			        	generatedMetadata.append(uiKey+":-:"+entry.getValue()+":|:");
+			        }
+			    }
+			    generatedMetadata.append("$%> \n*/ \n");			    
 			}
-			generatedRule.append("\n\t\tinsert(params);\nend");
-			policyLogger.info("New rule generated with :" + generatedRule.toString());
-			body = body + generatedRule.toString();
+			policyLogger.info("Metadata generated with :" + generatedMetadata.toString());
+			body = generatedMetadata.toString() + body;
 			// Expand the body. 
 			Map<String,String> copyMap=new HashMap<>();
 			copyMap.putAll((Map<? extends String, ? extends String>) policyData.getRuleData());
diff --git a/POLICY-SDK-APP/src/test/resources/com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt b/POLICY-SDK-APP/src/test/resources/com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt
index 63f93cb..6ff244e 100644
--- a/POLICY-SDK-APP/src/test/resources/com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt
+++ b/POLICY-SDK-APP/src/test/resources/com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt
@@ -88,7 +88,7 @@
 //
 // These parameters are required to build the runtime policy
 //
-declare PapParams
+declare Params
     closedLoopControlName : String
     actor : String
     aaiURL : String
diff --git a/POLICY-SDK-APP/src/test/resources/com.Config_BRMS_Raw_TestBRMSRawPolicy.1.txt b/POLICY-SDK-APP/src/test/resources/com.Config_BRMS_Raw_TestBRMSRawPolicy.1.txt
index a3cdb78..6924fc3 100644
--- a/POLICY-SDK-APP/src/test/resources/com.Config_BRMS_Raw_TestBRMSRawPolicy.1.txt
+++ b/POLICY-SDK-APP/src/test/resources/com.Config_BRMS_Raw_TestBRMSRawPolicy.1.txt
@@ -1,7 +1,7 @@
 package com.sample
 import com.sample.DroolsTest.Message;
 // Declare the Parameters here.
-declare PapParams
+declare Params
     samPoll : int
     value : String
 end
diff --git a/PolicyEngineAPI/src/main/java/org/onap/policy/std/AutoClientEnd.java b/PolicyEngineAPI/src/main/java/org/onap/policy/std/AutoClientEnd.java
index 5423149..e69f007 100644
--- a/PolicyEngineAPI/src/main/java/org/onap/policy/std/AutoClientEnd.java
+++ b/PolicyEngineAPI/src/main/java/org/onap/policy/std/AutoClientEnd.java
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * PolicyEngineAPI
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018 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.
@@ -82,7 +82,7 @@
 		AutoClientEnd.url = url;
 		
 		if (scheme == null || handler == null ||
-			! (scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS) &&
+			! (scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS) ||
 					scheme.equals(NotificationScheme.AUTO_NOTIFICATIONS) ) ||
 			AutoClientEnd.client != null) {
 			return;
diff --git a/PolicyEngineClient/testResources/test.drl b/PolicyEngineClient/testResources/test.drl
index 10cd5b7..5253cf8 100644
--- a/PolicyEngineClient/testResources/test.drl
+++ b/PolicyEngineClient/testResources/test.drl
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * archetype-closed-loop-demo-rules
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018 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.
@@ -83,7 +83,7 @@
 //
 // These parameters are required to build the runtime policy
 //
-declare PapParams
+declare Params
     closedLoopControlName : String
     actor : String
     aaiURL : String
diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/PolicyUtilsTest.java b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/PolicyUtilsTest.java
index 34ed6b8..8445ad7 100644
--- a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/PolicyUtilsTest.java
+++ b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/PolicyUtilsTest.java
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * PolicyEngineUtils
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018 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.
@@ -148,7 +148,7 @@
 	public void testBRMSValidate(){
 	    String rule = "package com.sample;\n"
 	            + "import com.sample.DroolsTest.Message;\n"
-	            + "declare PapParams\n"
+	            + "declare Params\n"
 	            + "samPoll : int\n"
 	            + "value : String\n"
 	            + "end\n"