aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorRavindra Bakkamanthala <rb7147@att.com>2017-06-05 22:42:02 -0400
committerRavindra Bakkamanthala <rb7147@att.com>2017-06-07 14:47:34 -0400
commitfc5c07705edc4dcb7083b39116a43844bb6a1490 (patch)
treeab5c7258197fc776fef8106413704a5f0a829160
parentd9007d680d19734d5dc106479784c420236cca4b (diff)
Fixed the Policy API issues and Bugfixes
Change-Id: I6e8b54442421b6ebd0ff88426fc6e5f3a36b0690 Signed-off-by: Ravindra Bakkamanthala <rb7147@att.com>
-rw-r--r--ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/Constraint.java22
-rw-r--r--ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuard.java7
-rw-r--r--ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/GuardPolicy.java8
-rw-r--r--ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java2
-rw-r--r--ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java4
-rw-r--r--ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuardTest.java6
-rw-r--r--ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/XACMLPapServlet.java64
-rw-r--r--ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/ActionPolicy.java23
-rw-r--r--ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/AutoPushPolicy.java4
-rw-r--r--ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java138
-rw-r--r--ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java10
-rw-r--r--ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java (renamed from ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateNewMicroSerivceModel.java)130
-rw-r--r--ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/DecisionPolicy.java156
-rw-r--r--ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/Policy.java12
-rw-r--r--ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/PolicyDBDao.java38
-rw-r--r--ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/SafePolicyBuilder.java26
-rw-r--r--ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java2
-rw-r--r--ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/PushPolicyController.java24
-rw-r--r--ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java2
-rw-r--r--ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DeleteHandler.java4
-rw-r--r--ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/policycontroller/PolicyCreation.java9
-rw-r--r--ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/service/ImportService.java8
-rw-r--r--ECOMP-PAP-REST/src/main/resources/Decision_GuardBLPolicyTemplate.xml (renamed from packages/base/src/files/install/servers/pap/bin/Decision_GuardPolicyTemplate.xml)62
-rw-r--r--ECOMP-PAP-REST/src/main/resources/Decision_GuardPolicyTemplate.xml (renamed from ECOMP-PAP-REST/Decision_GuardPolicyTemplate.xml)0
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/PapUrlResolver.java1
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpLoader.java2
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PAPServices.java7
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PolicyEngineImportService.java6
-rw-r--r--ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPApiAuth.java6
-rw-r--r--ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/YAMLParams.java9
-rw-r--r--ECOMP-SDK-APP/xacml.admin.properties2
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java140
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyRestController.java17
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java21
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java20
-rw-r--r--POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java314
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/PDPTabWindows/AddorEditPDPtoGroup.html2
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/PushtabWindow/removeGroupPoliciesWindow.html2
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/BRMSParamDictGridController.js2
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLPepOptionsDictGridController.js2
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLServiceDictGridController.js2
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLSiteDictGridController.js2
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVarbindDictGridController.js2
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVnfTypeDictGridController.js2
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVsclActionDictGridController.js2
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ActionPolicyController.js1
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DCAEMicroServicePolicyController.js7
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DecisionPolicyController.js26
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/ActionPolicyTemplate.html2
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/ClosedLoopFaultPolicyTemplate.html2
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/DecisionPolicyTemplate.html81
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/PolicyTypeTemplate.html2
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/policy_AutoPush.html13
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/policy_Dictionary.html25
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/policy_PDPManagement.html13
-rw-r--r--POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/policy_Roles.html21
-rw-r--r--PolicyEngineAPI/src/main/java/org/openecomp/policy/api/RuleProvider.java6
-rw-r--r--PolicyEngineAPI/src/main/java/org/openecomp/policy/std/StdPolicyEngine.java16
-rw-r--r--PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ClosedLoopPolicyClient.java26
-rw-r--r--PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ClosedLoopPolicyPerformanceMetricClient.java22
-rw-r--r--PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ConfigFirewallPolicyClient.java28
-rw-r--r--PolicyEngineClient/src/main/java/org/openecomp/policyEngine/MicroServicesPolicyClient.java22
-rw-r--r--PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/PolicyUtils.java84
-rw-r--r--PolicyEngineUtils/src/test/java/org/openecomp/policy/test/PolicyUtilsTest.java2
-rw-r--r--packages/base/src/files/install/elk/config/elasticsearch.yml460
-rw-r--r--packages/base/src/files/install/elk/init.d/elkd4
-rwxr-xr-xpackages/base/src/files/install/mysql/data/161000_upgrade_script.sql2
-rw-r--r--packages/base/src/files/install/mysql/data/170701_upgrade_script.sql4
-rw-r--r--packages/base/src/files/install/servers/console/bin/xacml.admin.properties4
-rw-r--r--packages/base/src/files/install/servers/pap/bin/xacml.pap.properties2
-rwxr-xr-xpackages/base/src/files/install/servers/pap/webapps/Config/com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt2
-rwxr-xr-xpackages/base/src/files/install/servers/pap/webapps/Config/com.Config_BRMS_Param_BRMSParamvLBDemoPolicy.1.txt2
-rw-r--r--packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties1
73 files changed, 1087 insertions, 1117 deletions
diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/Constraint.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/Constraint.java
index 85ddf066d..42a04e7b7 100644
--- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/Constraint.java
+++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/Constraint.java
@@ -77,6 +77,13 @@ public class Constraint {
this.blacklist = new LinkedList<>(blacklist);
}
+
+ public Constraint(Map<String, String> time_in_range, List<String> blacklist) {
+ if (time_in_range != null) {
+ this.time_in_range = Collections.unmodifiableMap(time_in_range);
+ }
+ this.blacklist = new LinkedList<>(blacklist);
+ }
public Constraint(Integer num, String duration, List<String> blacklist) {
this.num = num;
@@ -84,6 +91,13 @@ public class Constraint {
this.blacklist = new LinkedList<>(blacklist);
}
+ public Constraint(Integer num, String duration, Map<String, String> time_in_range) {
+ this(num, duration);
+ if (time_in_range != null) {
+ this.time_in_range = Collections.unmodifiableMap(time_in_range);
+ }
+ }
+
public Constraint(Integer num, String duration, Map<String, String> time_in_range, List<String> blacklist) {
this(num, duration);
if (time_in_range != null) {
@@ -102,13 +116,7 @@ public class Constraint {
}
public boolean isValid() {
- if (num == null && duration != null) {
- return false;
- }
- if (duration == null && num != null) {
- return false;
- }
- return true;
+ return ((num == null && duration != null)|| (duration == null && num != null))? false : true;
}
@Override
diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuard.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuard.java
index cfc904823..3df2a0885 100644
--- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuard.java
+++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuard.java
@@ -20,13 +20,12 @@
package org.openecomp.policy.controlloop.policy.guard;
import java.util.LinkedList;
-import java.util.List;
public class ControlLoopGuard {
private Guard guard;
- private List<GuardPolicy> guards;
+ private LinkedList<GuardPolicy> guards;
public ControlLoopGuard() {
//DO Nothing Empty Constructor
@@ -40,11 +39,11 @@ public class ControlLoopGuard {
this.guard = guard;
}
- public List<GuardPolicy> getGuards() {
+ public LinkedList<GuardPolicy> getGuards() {
return guards;
}
- public void setGuards(List<GuardPolicy> guards) {
+ public void setGuards(LinkedList<GuardPolicy> guards) {
this.guards = guards;
}
diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/GuardPolicy.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/GuardPolicy.java
index 7eb8af6d1..a4d56ff07 100644
--- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/GuardPolicy.java
+++ b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/GuardPolicy.java
@@ -31,7 +31,7 @@ public class GuardPolicy {
private String description;
private String actor;
private String recipe;
- private List<Constraint> limit_constraints;
+ private LinkedList<Constraint> limit_constraints;
public GuardPolicy() {
//Do Nothing Empty Constructor.
@@ -77,11 +77,11 @@ public class GuardPolicy {
this.recipe = recipe;
}
- public List<Constraint> getLimit_constraints() {
- return limit_constraints;
+ public LinkedList<Constraint> getLimit_constraints() {
+ return limit_constraints;
}
- public void setLimit_constraints(List<Constraint> limit_constraints) {
+ public void setLimit_constraints(LinkedList<Constraint> limit_constraints) {
this.limit_constraints = limit_constraints;
}
diff --git a/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java b/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java
index 1e035edf4..e2701eefb 100644
--- a/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java
+++ b/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java
@@ -31,7 +31,7 @@ import org.junit.Test;
import org.openecomp.policy.controlloop.guard.compiler.ControlLoopGuardCompiler;
public class ControlLoopGuardCompilerTest {
-
+
@Test
public void testTest1() {
try {
diff --git a/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java b/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java
index 5df0266ec..3137a1232 100644
--- a/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java
+++ b/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java
@@ -142,12 +142,12 @@ public class ControlLoopGuardBuilderTest {
fail(e.getMessage());
}
}
-
+
@Test
public void test1() {
this.test("src/test/resources/v2.0.0-guard/policy_guard_OpenECOMP_demo_vDNS.yaml");
}
-
+
@Test
public void test2() {
this.test("src/test/resources/v2.0.0-guard/policy_guard_1707_appc.yaml");
diff --git a/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuardTest.java b/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuardTest.java
index a09fd2112..4575e594f 100644
--- a/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuardTest.java
+++ b/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuardTest.java
@@ -19,7 +19,9 @@
*/
package org.openecomp.policy.controlloop.policy.guard;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileInputStream;
@@ -35,7 +37,7 @@ import org.yaml.snakeyaml.constructor.Constructor;
public class ControlLoopGuardTest {
-
+
@Test
public void testGuardvDNS() {
this.test("src/test/resources/v2.0.0-guard/policy_guard_OpenECOMP_demo_vDNS.yaml");
diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/XACMLPapServlet.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/XACMLPapServlet.java
index 685582e29..edbc2acb7 100644
--- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/XACMLPapServlet.java
+++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/XACMLPapServlet.java
@@ -1343,7 +1343,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
loggingContext.transactionEnded();
auditLogger.info("Success");
- if ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param"))) {
+ if (policy != null && (policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param"))) {
PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance();
if (pushPolicyHandler.preSafetyCheck(policy, CONFIG_HOME)) {
LOGGER.debug("Precheck Successful.");
@@ -1801,10 +1801,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
if (papEngine.getPDP(pdpId) == null) {
// this is a request to create a new PDP object
try{
- acPutTransaction.addPdpToGroup(pdp.getId(), group.getId(), pdp.getName(), pdp.getDescription(), pdp.getJmxPort(),"XACMLPapServlet.doACPut");
+ acPutTransaction.addPdpToGroup(pdp == null ? "PDP is null" : pdp.getId(), group.getId(), pdp == null ? "PDP is null" : pdp.getName(),
+ pdp == null ? "PDP is null" : pdp.getDescription(),
+ pdp == null ? 0 : pdp.getJmxPort(),"XACMLPapServlet.doACPut");
} catch(Exception e){
PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while adding pdp to group in the database: "
- +"pdp="+pdp.getId()+",to group="+group.getId());
+ +"pdp="+ (pdp == null ? "PDP is null" : pdp.getId()) +",to group="+group.getId());
throw new PAPException(e.getMessage());
}
papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription(), pdp.getJmxPort());
@@ -1813,7 +1815,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
acPutTransaction.updatePdp(pdp, "XACMLPapServlet.doACPut");
} catch(Exception e){
PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating pdp in the database: "
- +"pdp="+pdp.getId());
+ +"pdp="+(pdp == null ? "PDP is null" : pdp.getId()));
throw new PAPException(e.getMessage());
}
// this is a request to update the pdp
@@ -1867,7 +1869,9 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
// The Path on the PAP side is not carried on the RESTful interface with the AC
// (because it is local to the PAP)
// so we need to fill that in before submitting the group for update
- ((StdPDPGroup)objectFromJSON).setDirectory(((StdPDPGroup)group).getDirectory());
+ if(objectFromJSON != null){
+ ((StdPDPGroup)objectFromJSON).setDirectory(((StdPDPGroup)group).getDirectory());
+ }
try{
acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doACPut");
} catch(Exception e){
@@ -2138,26 +2142,28 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
HttpURLConnection connection = null;
try {
// Open up the connection
- connection = (HttpURLConnection)pdpURL.openConnection();
- // Setup our method and headers
- connection.setRequestMethod("GET");
- connection.setConnectTimeout(heartbeatTimeout);
- // Authentication
- String encoding = CheckPDP.getEncoding(pdp.getId());
- if(encoding !=null){
- connection.setRequestProperty("Authorization", "Basic " + encoding);
- }
- // Do the connect
- connection.connect();
- if (connection.getResponseCode() == 204) {
- newStatus = connection.getHeaderField(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB);
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("Heartbeat '" + pdp.getId() + "' status='" + newStatus + "'");
+ if(pdpURL != null){
+ connection = (HttpURLConnection)pdpURL.openConnection();
+ // Setup our method and headers
+ connection.setRequestMethod("GET");
+ connection.setConnectTimeout(heartbeatTimeout);
+ // Authentication
+ String encoding = CheckPDP.getEncoding(pdp.getId());
+ if(encoding !=null){
+ connection.setRequestProperty("Authorization", "Basic " + encoding);
}
- } else {
- // anything else is an unexpected result
- newStatus = PDPStatus.Status.UNKNOWN.toString();
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat connect response code " + connection.getResponseCode() + ": " + pdp.getId());
+ // Do the connect
+ connection.connect();
+ if (connection.getResponseCode() == 204) {
+ newStatus = connection.getHeaderField(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB);
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("Heartbeat '" + pdp.getId() + "' status='" + newStatus + "'");
+ }
+ } else {
+ // anything else is an unexpected result
+ newStatus = PDPStatus.Status.UNKNOWN.toString();
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat connect response code " + connection.getResponseCode() + ": " + pdp.getId());
+ }
}
} catch (UnknownHostException e) {
newStatus = PDPStatus.Status.NO_SUCH_HOST.toString();
@@ -2173,7 +2179,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat '" + pdp.getId() + "' connect exception");
} finally {
// cleanup the connection
- connection.disconnect();
+ if(connection != null)
+ connection.disconnect();
}
if ( ! pdp.getStatus().getStatus().toString().equals(newStatus)) {
if (LOGGER.isDebugEnabled()) {
@@ -2372,7 +2379,9 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
}
} finally {
// cleanup the connection
- connection.disconnect();
+ if(connection != null){
+ connection.disconnect();
+ }
// tell the AC to update it's status info
notifyAC();
}
@@ -2436,7 +2445,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
disconnectedACs.add(acURL);
} finally {
// cleanup the connection
- connection.disconnect();
+ if(connection != null)
+ connection.disconnect();
}
}
// remove any ACs that are no longer connected
diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/ActionPolicy.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/ActionPolicy.java
index 1884aab62..45ef01f6e 100644
--- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/ActionPolicy.java
+++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/ActionPolicy.java
@@ -328,8 +328,7 @@ public class ActionPolicy extends Policy {
// Add JSON_URL Assignment:
String actionBody = getActionPolicyDict(comboDictValue).getBody();
- if (!actionBody.equals(null)) {
- //if(!(actionBody==null || "".equals(actionBody))){
+ if (actionBody != null) {
AttributeAssignmentExpressionType assignmentJsonURL = new AttributeAssignmentExpressionType();
assignmentJsonURL.setAttributeId(BODY_ATTRIBUTEID);
assignmentJsonURL.setCategory(CATEGORY_RESOURCE);
@@ -342,7 +341,7 @@ public class ActionPolicy extends Policy {
obligation.getAttributeAssignmentExpression().add(assignmentJsonURL);
}
- if(!getActionPolicyDict(comboDictValue).getHeader().equals(null)){
+ if(getActionPolicyDict(comboDictValue).getHeader() != null){
String headerVal = getActionPolicyDict(comboDictValue).getHeader();
if(headerVal != null && !headerVal.equals("")){
// parse it on : to get number of headers
@@ -484,21 +483,23 @@ public class ActionPolicy extends Policy {
private Map<String,String> createDropDownMap(){
JPAUtils jpaUtils = null;
+ Map<String, String> dropDownMap = new HashMap<>();
try {
jpaUtils = JPAUtils.getJPAUtilsInstance(XACMLPapServlet.getEmf());
} catch (Exception e) {
LOGGER.error("Exception Occured"+e);
}
- Map<Datatype, List<FunctionDefinition>> functionMap = jpaUtils.getFunctionDatatypeMap();
- Map<String, String> dropDownMap = new HashMap<>();
- for (Datatype id : functionMap.keySet()) {
- List<FunctionDefinition> functionDefinitions = (List<FunctionDefinition>) functionMap
- .get(id);
- for (FunctionDefinition functionDef : functionDefinitions) {
- dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid());
+ if(jpaUtils != null){
+ Map<Datatype, List<FunctionDefinition>> functionMap = jpaUtils.getFunctionDatatypeMap();
+
+ for (Datatype id : functionMap.keySet()) {
+ List<FunctionDefinition> functionDefinitions = (List<FunctionDefinition>) functionMap
+ .get(id);
+ for (FunctionDefinition functionDef : functionDefinitions) {
+ dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid());
+ }
}
}
-
return dropDownMap;
}
diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/AutoPushPolicy.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/AutoPushPolicy.java
index b9ed78ef6..b658483d2 100644
--- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/AutoPushPolicy.java
+++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/AutoPushPolicy.java
@@ -136,9 +136,7 @@ public class AutoPushPolicy {
//Get the current policies from the Group and Add the new one
Set<PDPPolicy> currentPoliciesInGroup = pdpGroup.getPolicies();
Set<PDPPolicy> policies = new HashSet<>();
- if(policy!=null){
- policies.add(policy);
- }
+ policies.add(policy);
pdpGroup.copyPolicyToFile(policyId, new FileInputStream(Paths.get(policyToCreateUpdate).toFile()));
//If the selected policy is in the group we must remove it because the name is default
Iterator<PDPPolicy> policyIterator = policies.iterator();
diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java
index 535b2edd3..b9dc039fc 100644
--- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java
+++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java
@@ -29,17 +29,11 @@ import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
-import java.util.HashSet;
import java.util.Iterator;
+import java.util.List;
import java.util.Map;
-import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -50,11 +44,11 @@ import org.openecomp.policy.common.logging.eelf.PolicyLogger;
import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
import org.openecomp.policy.common.logging.flexlogger.Logger;
import org.openecomp.policy.pap.xacml.rest.controller.BRMSDictionaryController;
-import org.openecomp.policy.rest.XACMLRestProperties;
+import org.openecomp.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
+import org.openecomp.policy.rest.jpa.BRMSParamTemplate;
import com.att.research.xacml.std.IdentifierImpl;
-import com.att.research.xacml.util.XACMLProperties;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
@@ -74,14 +68,6 @@ public class CreateBrmsParamPolicy extends Policy {
private static final Logger LOGGER = FlexLogger.getLogger(CreateBrmsParamPolicy.class);
- /*
- * These are the parameters needed for DB access from the PAP
- */
- private static String papDbDriver = null;
- private static String papDbUrl = null;
- private static String papDbUser = null;
- private static String papDbPassword = null;
-
public CreateBrmsParamPolicy() {
super();
}
@@ -92,38 +78,35 @@ public class CreateBrmsParamPolicy extends Policy {
}
- public String expandConfigBody(String ruleContents, Map<String, String> brmsParamBody) {
-
- Set<String> keySet= new HashSet<>();
-
- Map<String,String> copyMap=new HashMap<>();
- copyMap.putAll(brmsParamBody);
- 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]", ""));
-
- //Finding all the keys in the Map data-structure.
- keySet= copyMap.keySet();
- Iterator<String> iterator = keySet.iterator();
- Pattern p;
- Matcher m;
- while(iterator.hasNext()) {
- //Converting the first character of the key into a lower case.
- String input= iterator.next();
- String output = Character.toLowerCase(input.charAt(0)) +
- (input.length() > 1 ? input.substring(1) : "");
- //Searching for a pattern in the String using the key.
- p=Pattern.compile("\\$\\{"+output+"\\}");
- m=p.matcher(ruleContents);
- //Replacing the value with the inputs provided by the user in the editor.
- String finalInput = copyMap.get(input);
- if(finalInput.contains("$")){
- finalInput = finalInput.replace("$", "\\$");
- }
- ruleContents=m.replaceAll(finalInput);
+ public String expandConfigBody(String ruleContents, Map<String, String> brmsParamBody) {
+
+ Map<String,String> copyMap=new HashMap<>();
+ copyMap.putAll(brmsParamBody);
+ 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]", ""));
+
+ //Finding all the keys in the Map data-structure.
+ Iterator<String> iterator = copyMap.keySet().iterator();
+ Pattern p;
+ Matcher m;
+ while(iterator.hasNext()) {
+ //Converting the first character of the key into a lower case.
+ String input= iterator.next();
+ String output = Character.toLowerCase(input.charAt(0)) +
+ (input.length() > 1 ? input.substring(1) : "");
+ //Searching for a pattern in the String using the key.
+ p=Pattern.compile("\\$\\{"+output+"\\}");
+ m=p.matcher(ruleContents);
+ //Replacing the value with the inputs provided by the user in the editor.
+ String finalInput = copyMap.get(input);
+ if(finalInput.contains("$")){
+ finalInput = finalInput.replace("$", "\\$");
}
- return ruleContents;
+ ruleContents=m.replaceAll(finalInput);
+ }
+ return ruleContents;
}
@@ -194,13 +177,9 @@ public class CreateBrmsParamPolicy extends Policy {
// xml.
Path newPolicyPath = null;
newPolicyPath = Paths.get(policyAdapter.getNewFileName());
-
- Boolean dbIsUpdated = true;
-
- successMap = new HashMap<>();
- if (dbIsUpdated) {
- successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
- } else {
+ successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
+ if(successMap == null){
+ successMap = new HashMap<>();
PolicyLogger.error("Failed to Update the Database Dictionary Tables.");
successMap.put("error", "DB UPDATE");
}
@@ -208,50 +187,15 @@ public class CreateBrmsParamPolicy extends Policy {
}
private String getValueFromDictionary(String templateName){
-
- Connection con = null;
- Statement st = null;
- ResultSet rs = null;
-
- /*
- * Retrieve the property values for db access from the xacml.pap.properties
- */
- papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
- papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
- papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
- papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD);
-
- String ruleTemplate=null;
-
- try {
- //Get DB Connection
- Class.forName(papDbDriver);
- con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword);
- st = con.createStatement();
-
- String queryString="select rule from BRMSParamTemplate where param_template_name=\"";
- queryString=queryString+templateName+"\"";
-
- rs = st.executeQuery(queryString);
- if(rs.next()){
- ruleTemplate=rs.getString("rule");
- }
- rs.close();
- }catch (ClassNotFoundException e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "CreateBrmsParamPolicy", "Exception querying BRMSParamTemplate");
- } catch (SQLException e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "CreateBrmsParamPolicy", "Exception querying BRMSParamTemplate");
- } finally {
- try{
- if (con!=null) con.close();
- if (rs!=null) rs.close();
- if (st!=null) st.close();
- } catch (Exception ex){
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, ex, "CreateBrmsParamPolicy", "Exception querying BRMSParamTemplate");
- }
+ String ruleTemplate = null;
+ CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
+ String queryString="from BRMSParamTemplate where param_template_name= '"+templateName+"'";
+ List<Object> result = dbConnection.getDataByQuery(queryString);
+ if(!result.isEmpty()){
+ BRMSParamTemplate template = (BRMSParamTemplate) result.get(0);
+ ruleTemplate = template.getRule();
}
return ruleTemplate;
-
}
protected Map<String, String> findType(String rule) {
diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java
index 350bbc4ff..a0f13ec02 100644
--- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java
+++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java
@@ -131,13 +131,9 @@ public class CreateBrmsRawPolicy extends Policy {
Path newPolicyPath = null;
newPolicyPath = Paths.get(policyAdapter.getNewFileName());
- Boolean dbIsUpdated = true;
-
- successMap = new HashMap<String, String>();
- if (dbIsUpdated) {
- successMap = createPolicy(newPolicyPath,
- getCorrectPolicyDataObject());
- } else {
+ successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject());
+ if (successMap == null) {
+ successMap = new HashMap<>();
PolicyLogger.error("Failed to Update the Database Dictionary Tables.");
successMap.put("error", "DB UPDATE");
}
diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateNewMicroSerivceModel.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java
index 0e4e409d3..e801a459d 100644
--- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateNewMicroSerivceModel.java
+++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java
@@ -25,11 +25,6 @@ import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
@@ -46,38 +41,28 @@ import org.openecomp.policy.common.logging.eelf.PolicyLogger;
import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
import org.openecomp.policy.common.logging.flexlogger.Logger;
import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet;
-import org.openecomp.policy.rest.XACMLRestProperties;
+import org.openecomp.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl;
import org.openecomp.policy.rest.jpa.MicroServiceModels;
import org.openecomp.policy.rest.jpa.UserInfo;
import org.openecomp.policy.rest.util.MSAttributeObject;
import org.openecomp.policy.rest.util.MSModelUtils;
import org.openecomp.policy.rest.util.MSModelUtils.MODEL_TYPE;
-import com.att.research.xacml.util.XACMLProperties;
-
-public class CreateNewMicroSerivceModel {
- private static final Logger logger = FlexLogger.getLogger(CreateNewMicroSerivceModel.class);
+public class CreateNewMicroServiceModel {
+ private static final Logger logger = FlexLogger.getLogger(CreateNewMicroServiceModel.class);
private MicroServiceModels newModel = null;
private HashMap<String,MSAttributeObject > classMap = new HashMap<>();
- /*
- * These are the parameters needed for DB access from the PAP
- */
- private static String papDbDriver = null;
- private static String papDbUrl = null;
- private static String papDbUser = null;
- private static String papDbPassword = null;
MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsEcompName(), XACMLPapServlet.getMsPolicyName());
- public CreateNewMicroSerivceModel(String fileName, String serviceName, String string, String version) {
+ public CreateNewMicroServiceModel(String fileName, String serviceName, String string, String version) {
super();
}
- public CreateNewMicroSerivceModel(String importFile, String modelName, String description, String version, String randomID) {
+ public CreateNewMicroServiceModel(String importFile, String modelName, String description, String version, String randomID) {
this.newModel = new MicroServiceModels();
- this.newModel.setDescription(description);
this.newModel.setVersion(version);
this.newModel.setModelName(modelName);
UserInfo userInfo = new UserInfo();
@@ -135,7 +120,7 @@ public class CreateNewMicroSerivceModel {
int BUFFER = 2048;
File file = new File(zipFile);
- ZipFile zip;
+ ZipFile zip = null;
try {
zip = new ZipFile("ExtractDir" + File.separator +file);
String newPath = zipFile.substring(0, zipFile.length() - 4);
@@ -143,8 +128,7 @@ public class CreateNewMicroSerivceModel {
Enumeration zipFileEntries = zip.entries();
// Process each entry
- while (zipFileEntries.hasMoreElements())
- {
+ while (zipFileEntries.hasMoreElements()){
// grab a zip file entry
ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
String currentEntry = entry.getName();
@@ -153,8 +137,7 @@ public class CreateNewMicroSerivceModel {
destinationParent.mkdirs();
- if (!entry.isDirectory())
- {
+ if (!entry.isDirectory()){
BufferedInputStream is = new BufferedInputStream(zip
.getInputStream(entry));
int currentByte;
@@ -173,13 +156,20 @@ public class CreateNewMicroSerivceModel {
is.close();
}
- if (currentEntry.endsWith(".zip"))
- {
+ if (currentEntry.endsWith(".zip")){
extractFolder(destFile.getAbsolutePath());
}
}
} catch (IOException e) {
- logger.error("Failed to unzip model file " + zipFile);
+ logger.error("Failed to unzip model file " + zipFile + e);
+ }finally{
+ if(zip != null){
+ try {
+ zip.close();
+ } catch (Exception e) {
+ logger.error("Exception Occured while closing the zip file"+e);
+ }
+ }
}
}
@@ -225,70 +215,34 @@ public class CreateNewMicroSerivceModel {
}
- @SuppressWarnings("resource")
public Map<String, String> saveImportService(){
- Map<String, String> successMap = new HashMap<>();
-
- Connection con = null;
- Statement st = null;
- ResultSet rs = null;
String modelName = this.newModel.getModelName();
String imported_by = "API";
String version = this.newModel.getVersion();
- String insertQuery = null;
- int ID = 0;
-
- /*
- * Retrieve the property values for db access from the xacml.pap.properties
- */
- papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
- papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
- papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
- papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD);
-
- try {
- //Get DB Connection
- Class.forName(papDbDriver);
- con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword);
- st = con.createStatement();
- String queryString ="SELECT * FROM MicroServiceModels WHERE modelName='" + modelName + "' AND version='" + version+ "';";
- rs = st.executeQuery(queryString);
-
- if(rs.next()){
- successMap.put("DBError", "EXISTS");
- logger.error("Import new service failed. Service already exists");
- }else{
- rs = st.executeQuery("SELECT MAX(ID) AS ID FROM MicroServiceModels;");
- if(rs.next()){
- ID = rs.getInt("ID");
- ID++;
- }
-
- String newDependency = "[" + this.newModel.getDependency() + "]";
- this.newModel.setDependency(newDependency);
- insertQuery = "INSERT INTO MicroServiceModels (ID, modelName, Dependency, DESCRIPTION, attributes, ref_attributes, sub_attributes, version, imported_by, enumValues, annotation) "
- + "VALUES("+ID+",'"+modelName+"','"+ this.newModel.getDependency()+"','"+this.newModel.getDescription()+"','"+this.newModel.getAttributes()+
- "','"+this.newModel.getRef_attributes()+"','"+this.newModel.getSub_attributes()+"','"+version+"','"+imported_by+"','"+this.newModel.getEnumValues()+"','"+this.newModel.getAnnotation()+"')";
- st.executeUpdate(insertQuery);
- successMap.put("success", "success");
- }
- rs.close();
- }catch (ClassNotFoundException e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "saveImportService", "Exception querying MicroServiceModels");
- successMap.put("DBError", "Error Query");
- } catch (SQLException e) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "saveImportService", "Exception querying MicroServiceModels");
- successMap.put("DBError", "Error Query");
- } finally {
- try{
- if (con!=null) con.close();
- if (rs!=null) rs.close();
- if (st!=null) st.close();
- } catch (Exception ex){
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, ex, "saveImportService", "Exception querying MicroServiceModels");
- }
- }
-
+ Map<String, String> successMap = new HashMap<>();
+ CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
+ List<Object> result = dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName+":"+version);
+ if(result.isEmpty()){
+ MicroServiceModels model = new MicroServiceModels();
+ model.setModelName(modelName);
+ model.setVersion(version);
+ model.setAttributes(this.newModel.getAttributes());
+ model.setAnnotation(this.newModel.getAnnotation());
+ model.setDependency(this.newModel.getDependency());
+ model.setDescription(this.newModel.getDescription());
+ model.setEnumValues(this.newModel.getEnumValues());
+ model.setRef_attributes(this.newModel.getRef_attributes());
+ model.setSub_attributes(this.newModel.getSub_attributes());
+ UserInfo userInfo = new UserInfo();
+ userInfo.setUserLoginId(imported_by);
+ userInfo.setUserName(imported_by);
+ model.setUserCreatedBy(userInfo);
+ dbConnection.save(model);
+ successMap.put("success", "success");
+ }else{
+ successMap.put("DBError", "EXISTS");
+ logger.error("Import new service failed. Service already exists");
+ }
return successMap;
}
}
diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/DecisionPolicy.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/DecisionPolicy.java
index 8d2617ce2..02ea630a6 100644
--- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/DecisionPolicy.java
+++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/DecisionPolicy.java
@@ -21,6 +21,7 @@
package org.openecomp.policy.pap.xacml.rest.components;
import java.io.ByteArrayInputStream;
+import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
@@ -28,6 +29,8 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
@@ -85,7 +88,13 @@ public class DecisionPolicy extends Policy {
public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not";
private static final String AAFProvider = "AAF";
public static final String GUARD_YAML = "GUARD_YAML";
- private static final String XACMLTEMPLATE = "Decision_GuardPolicyTemplate.xml";
+ public static final String GUARD_BL_YAML = "GUARD_BL_YAML";
+ private static final String XACML_GUARD_TEMPLATE = "Decision_GuardPolicyTemplate.xml";
+ private static final String XACML_BLGUARD_TEMPLATE = "Decision_GuardBLPolicyTemplate.xml";
+
+ private static final String ECOMPNAME = "ECOMPName";
+ private static final String POLICY_NAME = "PolicyName";
+ private static final String DESCRIPTION = "description";
List<String> dynamicLabelRuleAlgorithms = new LinkedList<>();
@@ -142,7 +151,7 @@ public class DecisionPolicy extends Policy {
version = policyAdapter.getHighestVersion();
// Create the Instance for pojo, PolicyType object is used in marshalling.
- if (policyAdapter.getPolicyType().equals("Decision")) {
+ if ("Decision".equals(policyAdapter.getPolicyType())) {
PolicyType policyConfig = new PolicyType();
policyConfig.setVersion(Integer.toString(version));
@@ -152,20 +161,20 @@ public class DecisionPolicy extends Policy {
}
policyName = policyAdapter.getNewFileName();
- if(policyAdapter.getRuleProvider().equals(GUARD_YAML)){
+ if(policyAdapter.getRuleProvider().equals(GUARD_YAML) || policyAdapter.getRuleProvider().equals(GUARD_BL_YAML)){
Map<String, String> yamlParams = new HashMap<>();
- yamlParams.put("description", (policyAdapter.getPolicyDescription()!=null)? policyAdapter.getPolicyDescription(): "YAML Guard Policy");
+ yamlParams.put(DESCRIPTION, (policyAdapter.getPolicyDescription()!=null)? policyAdapter.getPolicyDescription(): "YAML Guard Policy");
String fileName = policyAdapter.getNewFileName();
- String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
- if ((name == null) || (name.equals(""))) {
- name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
+ String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length());
+ if ((name == null) || ("".equals(name))) {
+ name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
}
- yamlParams.put("PolicyName", name);
- yamlParams.put("ECOMPName", policyAdapter.getEcompName());
+ yamlParams.put(POLICY_NAME, name);
+ yamlParams.put(ECOMPNAME, policyAdapter.getEcompName());
Map<String, String> params = policyAdapter.getDynamicFieldConfigAttributes();
yamlParams.putAll(params);
// Call YAML to XACML
- PolicyType decisionPolicy = getGuardPolicy(yamlParams);
+ PolicyType decisionPolicy = getGuardPolicy(yamlParams, policyAdapter.getRuleProvider());
decisionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
decisionPolicy.setVersion(Integer.toString(version));
policyAdapter.setPolicyData(decisionPolicy);
@@ -178,16 +187,16 @@ public class DecisionPolicy extends Policy {
decisionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
AllOfType allOfOne = new AllOfType();
String fileName = policyAdapter.getNewFileName();
- String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
- if ((name == null) || (name.equals(""))) {
- name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
+ String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length());
+ if ((name == null) || ("".equals(name))) {
+ name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
}
- allOfOne.getMatch().add(createMatch("PolicyName", name));
+ allOfOne.getMatch().add(createMatch(POLICY_NAME, name));
AllOfType allOf = new AllOfType();
// Match for Ecomp
- allOf.getMatch().add(createMatch("ECOMPName", (policyAdapter.getEcompName())));
+ allOf.getMatch().add(createMatch(ECOMPNAME, (policyAdapter.getEcompName())));
Map<String, String> dynamicFieldComponentAttributes = policyAdapter.getDynamicFieldConfigAttributes();
if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals(AAFProvider)){
@@ -235,44 +244,73 @@ public class DecisionPolicy extends Policy {
return true;
}
- public PolicyType getGuardPolicy(Map<String, String> yamlParams) {
+ public PolicyType getGuardPolicy(Map<String, String> yamlParams, String ruleProvider) {
try {
ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(new Guard());
- GuardPolicy policy1 = new GuardPolicy((policyAdapter.getUuid()!=null? policyAdapter.getUuid(): UUID.randomUUID().toString()) ,yamlParams.get("PolicyName"), yamlParams.get("description"), yamlParams.get("actor"), yamlParams.get("recipe"));
+ GuardPolicy policy1 = new GuardPolicy((policyAdapter.getUuid()!=null? policyAdapter.getUuid(): UUID.randomUUID().toString()) ,yamlParams.get(POLICY_NAME), yamlParams.get(DESCRIPTION), yamlParams.get("actor"), yamlParams.get("recipe"));
builder = builder.addGuardPolicy(policy1);
Map<String, String> time_in_range = new HashMap<>();
time_in_range.put("arg2", yamlParams.get("guardActiveStart"));
time_in_range.put("arg3", yamlParams.get("guardActiveEnd"));
- Constraint cons = new Constraint(Integer.parseInt(yamlParams.get("limit")), yamlParams.get("timeWindow"));
- cons.setTime_in_range(time_in_range);
+ String blackListString = yamlParams.get("blackList");
+ List<String> blackList = null;
+ if(blackListString!=null){
+ if (blackListString.contains(",")){
+ blackList = Arrays.asList(blackListString.split(","));
+ }
+ else{
+ blackList = new ArrayList<>();
+ blackList.add(blackListString);
+ }
+ }
+ File templateFile;
+ Path xacmlTemplatePath;
+ Constraint cons;
+ ClassLoader classLoader = getClass().getClassLoader();
+ switch (ruleProvider){
+ case GUARD_BL_YAML:
+ templateFile = new File(classLoader.getResource(XACML_BLGUARD_TEMPLATE).getFile());
+ xacmlTemplatePath = templateFile.toPath();
+ cons = new Constraint(time_in_range,blackList);
+ break;
+ default:
+ templateFile = new File(classLoader.getResource(XACML_GUARD_TEMPLATE).getFile());
+ xacmlTemplatePath = templateFile.toPath();
+ cons = new Constraint(Integer.parseInt(yamlParams.get("limit")), yamlParams.get("timeWindow"), time_in_range);
+ break;
+ }
builder = builder.addLimitConstraint(policy1.getId(), cons);
// Build the specification
Results results = builder.buildSpecification();
// YAML TO XACML
ControlLoopGuard yamlGuardObject = SafePolicyBuilder.loadYamlGuard(results.getSpecification());
- Path xacmlTemplatePath = Paths.get(XACMLTEMPLATE);
+
String xacmlTemplateContent;
try {
xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath));
- HashMap<String, String> yamlSpecs = new HashMap<String, String>();
- yamlSpecs.put("PolicyName", yamlParams.get("PolicyName"));
- yamlSpecs.put("description", yamlParams.get("description"));
- yamlSpecs.put("ECOMPName", yamlParams.get("ECOMPName"));
- yamlSpecs.put("actor", ((LinkedList<GuardPolicy>)yamlGuardObject.getGuards()).getFirst().getActor());
- yamlSpecs.put("recipe", ((LinkedList<GuardPolicy>)yamlGuardObject.getGuards()).getFirst().getRecipe());
- yamlSpecs.put("limit", ((LinkedList<Constraint>)((LinkedList<GuardPolicy>)yamlGuardObject.getGuards()).getFirst().getLimit_constraints()).getFirst().getNum().toString());
- yamlSpecs.put("timeWindow", ((LinkedList<Constraint>)((LinkedList<GuardPolicy>)yamlGuardObject.getGuards()).getFirst().getLimit_constraints()).getFirst().getDuration());
- yamlSpecs.put("guardActiveStart", ((LinkedList<Constraint>)((LinkedList<GuardPolicy>)yamlGuardObject.getGuards()).getFirst().getLimit_constraints()).getFirst().getTime_in_range().get("arg2"));
- yamlSpecs.put("guardActiveEnd", ((LinkedList<Constraint>)((LinkedList<GuardPolicy>)yamlGuardObject.getGuards()).getFirst().getLimit_constraints()).getFirst().getTime_in_range().get("arg3"));
- String xacmlPolicyContent = SafePolicyBuilder.generateXacmlGuard(xacmlTemplateContent,yamlSpecs);
- // Convert the Policy into Stream input to Policy Adapter.
+ HashMap<String, String> yamlSpecs = new HashMap<>();
+ yamlSpecs.put(POLICY_NAME, yamlParams.get(POLICY_NAME));
+ yamlSpecs.put(DESCRIPTION, yamlParams.get(DESCRIPTION));
+ yamlSpecs.put(ECOMPNAME, yamlParams.get(ECOMPNAME));
+ yamlSpecs.put("actor", yamlGuardObject.getGuards().getFirst().getActor());
+ yamlSpecs.put("recipe", yamlGuardObject.getGuards().getFirst().getRecipe());
+ if(yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getNum()!=null){
+ yamlSpecs.put("limit", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getNum().toString());
+ }
+ if(yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getDuration()!=null){
+ yamlSpecs.put("timeWindow", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getDuration());
+ }
+ yamlSpecs.put("guardActiveStart", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_in_range().get("arg2"));
+ yamlSpecs.put("guardActiveEnd", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_in_range().get("arg3"));
+ String xacmlPolicyContent = SafePolicyBuilder.generateXacmlGuard(xacmlTemplateContent,yamlSpecs, yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getBlacklist());
+ // Convert the Policy into Stream input to Policy Adapter.
Object policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(xacmlPolicyContent.getBytes(StandardCharsets.UTF_8)));
return (PolicyType) policy;
} catch (IOException e) {
- PolicyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage());
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage() + e);
}
} catch (BuilderException e) {
- PolicyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage());
+ LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage() +e);
}
return null;
}
@@ -394,19 +432,19 @@ public class DecisionPolicy extends Policy {
decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
policyAdapter.setPolicyData(decisionPolicy);
- }else if (dynamicLabelRuleAlgorithms != null && dynamicLabelRuleAlgorithms.size() > 0) {
+ }else if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) {
boolean isCompound = false;
ConditionType condition = new ConditionType();
int index = dynamicFieldOneRuleAlgorithms.size() - 1;
for (String labelAttr : dynamicLabelRuleAlgorithms) {
// if the rule algorithm as a label means it is a compound
- if (dynamicFieldOneRuleAlgorithms.get(index).toString().equals(labelAttr)) {
+ if (dynamicFieldOneRuleAlgorithms.get(index).equals(labelAttr)) {
ApplyType decisionApply = new ApplyType();
- String selectedFunction = (String) dynamicFieldComboRuleAlgorithms.get(index).toString();
- String value1 = (String) dynamicFieldOneRuleAlgorithms.get(index).toString();
- String value2 = dynamicFieldTwoRuleAlgorithms.get(index).toString();
+ String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index);
+ String value1 = dynamicFieldOneRuleAlgorithms.get(index);
+ String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
decisionApply.setFunctionId(dropDownMap.get(selectedFunction));
decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1)));
decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2)));
@@ -416,7 +454,7 @@ public class DecisionPolicy extends Policy {
// if rule algorithm not a compound
if (!isCompound) {
- condition.setExpression(new ObjectFactory().createApply(getInnerDecisionApply(dynamicLabelRuleAlgorithms.get(index).toString())));
+ condition.setExpression(new ObjectFactory().createApply(getInnerDecisionApply(dynamicLabelRuleAlgorithms.get(index))));
}
}
if (!permitRule) {
@@ -452,7 +490,7 @@ public class DecisionPolicy extends Policy {
// check the index for the label.
for (String labelAttr : dynamicLabelRuleAlgorithms) {
if (labelAttr.equals(value1Label)) {
- String value1 = (String) dynamicFieldOneRuleAlgorithms.get(index).toString();
+ String value1 = dynamicFieldOneRuleAlgorithms.get(index);
populateDataTypeList(value1);
// check if the row contains label again
@@ -463,8 +501,8 @@ public class DecisionPolicy extends Policy {
}
// Getting the values from the form.
- String functionKey = (String) dynamicFieldComboRuleAlgorithms.get(index).toString();
- String value2 = dynamicFieldTwoRuleAlgorithms.get(index).toString();
+ String functionKey = dynamicFieldComboRuleAlgorithms.get(index);
+ String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
decisionApply.setFunctionId(dropDownMap.get(functionKey));
// if two text field are rule attributes.
if ((value1.contains(RULE_VARIABLE)) && (value2.contains(RULE_VARIABLE))) {
@@ -550,9 +588,9 @@ public class DecisionPolicy extends Policy {
// if the rule algorithm is multiple compound one setting the apply
protected ApplyType getCompoundDecisionApply(int index) {
ApplyType decisionApply = new ApplyType();
- String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index).toString();
- String value1 = dynamicFieldOneRuleAlgorithms.get(index).toString();
- String value2 = dynamicFieldTwoRuleAlgorithms.get(index).toString();
+ String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index);
+ String value1 = dynamicFieldOneRuleAlgorithms.get(index);
+ String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
decisionApply.setFunctionId(dropDownMap.get(selectedFunction));
decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1)));
decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2)));
@@ -574,16 +612,14 @@ public class DecisionPolicy extends Policy {
}
private void populateDataTypeList(String value1) {
-
- ///String value1 = dynamicFieldDecisionOneRuleAlgorithms.get(index).getValue().toString();
String dataType = null;
if(value1.contains("S_")) {
value1 = value1.substring(2, value1.length());
- DecisionSettings decisionSettings = findDecisionSettingsBySettingId(value1);
- if (decisionSettings != null && decisionSettings.getDatatypeBean().getShortName().equals("string")) {
+ DecisionSettings decisionSettings = findDecisionSettingsBySettingId(value1.substring(2, value1.length()));
+ if (decisionSettings != null && "string".equals(decisionSettings.getDatatypeBean().getShortName())) {
dataType = STRING_DATATYPE;
- } else if (decisionSettings != null && decisionSettings.getDatatypeBean().getShortName().equals("boolean")) {
+ } else if (decisionSettings != null && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) {
dataType = BOOLEAN_DATATYPE;
} else {
dataType = INTEGER_DATATYPE;
@@ -602,13 +638,13 @@ public class DecisionPolicy extends Policy {
} catch (Exception e) {
LOGGER.error("Exception Occured"+e);
}
- Map<Datatype, List<FunctionDefinition>> functionMap = jpaUtils.getFunctionDatatypeMap();
- Map<String, String> dropDownMap = new HashMap<String, String>();
- for (Datatype id : functionMap.keySet()) {
- List<FunctionDefinition> functionDefinitions = (List<FunctionDefinition>) functionMap
- .get(id);
- for (FunctionDefinition functionDef : functionDefinitions) {
- dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid());
+ Map<String, String> dropDownMap = new HashMap<>();
+ if(jpaUtils!=null){
+ Map<Datatype, List<FunctionDefinition>> functionMap = jpaUtils.getFunctionDatatypeMap();
+ for (Map.Entry<Datatype,List<FunctionDefinition>> map: functionMap.entrySet()) {
+ for (FunctionDefinition functionDef : map.getValue()) {
+ dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid());
+ }
}
}
@@ -620,9 +656,9 @@ public class DecisionPolicy extends Policy {
DecisionSettings decisionSettings = findDecisionSettingsBySettingId(key);
String dataType = null;
- if (decisionSettings != null && decisionSettings.getDatatypeBean().getShortName().equals("string")) {
+ if (decisionSettings != null && "string".equals(decisionSettings.getDatatypeBean().getShortName())) {
dataType = STRING_DATATYPE;
- } else if (decisionSettings != null && decisionSettings.getDatatypeBean().getShortName().equals("boolean")) {
+ } else if (decisionSettings != null && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) {
dataType = BOOLEAN_DATATYPE;
} else {
dataType = INTEGER_DATATYPE;
diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/Policy.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/Policy.java
index 48431fe93..536f8e6b3 100644
--- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/Policy.java
+++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/Policy.java
@@ -210,13 +210,17 @@ public abstract class Policy {
// Validation for json.
protected static boolean isJSONValid(String data) {
+ JsonReader jsonReader = null;
try {
new JSONObject(data);
InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
- JsonReader jsonReader = Json.createReader(stream);
+ jsonReader = Json.createReader(stream);
System.out.println("Json Value is: " + jsonReader.read().toString() );
} catch (Exception e) {
+ LOGGER.error("Exception Occured while reading json"+e);
return false;
+ }finally{
+ jsonReader.close();
}
return true;
}
@@ -308,6 +312,12 @@ public abstract class Policy {
}
} catch (Exception e) {
success.put("error", "Validation Failed");
+ }finally{
+ try {
+ inputStream.close();
+ } catch (IOException e) {
+ LOGGER.error("Exception Occured while closing the input stream"+e);
+ }
}
} else {
PolicyLogger.error("Unknown data type sent back.");
diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/PolicyDBDao.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/PolicyDBDao.java
index 51fcb3d09..b65557e05 100644
--- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/PolicyDBDao.java
+++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/PolicyDBDao.java
@@ -35,7 +35,6 @@ import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
-import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
@@ -69,8 +68,6 @@ import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
-import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
-
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
@@ -105,6 +102,8 @@ import com.att.research.xacml.api.pap.PDP;
import com.att.research.xacml.api.pap.PDPPolicy;
import com.att.research.xacml.util.XACMLProperties;
+import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
+
public class PolicyDBDao {
private static final Logger logger = FlexLogger.getLogger(PolicyDBDao.class);
private List<?> otherServers;
@@ -871,6 +870,7 @@ public class PolicyDBDao {
try {
policyStream.close();
} catch (IOException e) {
+ didUpdate = false;
PolicyLogger.error(e.getMessage());
}
}
@@ -1031,7 +1031,7 @@ public class PolicyDBDao {
String action = "unknown action";
try {
- if(policy.isDeleted()){
+ if(policy != null && policy.isDeleted()){
logger.debug("Deleting Policy: " + policy.getPolicyName());
action = "delete";
Path newPath = Paths.get(policyPath.toString(), policy.getPolicyName());
@@ -1098,7 +1098,7 @@ public class PolicyDBDao {
}
} catch (IOException e1) {
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, "PolicyDBDao", "Error occurred while performing [" + action + "] of Policy File: " + policy.getPolicyName());
+ PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, "PolicyDBDao", "Error occurred while performing [" + action + "] of Policy File: " + policy != null ? policy.getPolicyName() : "null");
}
}
@@ -1315,11 +1315,12 @@ public class PolicyDBDao {
String repo = buildPolicyDirectory();
String policyScope = policy.getScope();
+
if(policyScope == null){
policyScope = "";
PolicyLogger.error("buildPolicyScopeDirectory("+policy+") computed null policyScope. Using blank.");
} else {
- policyScope = policyScope.replace(".", FileSystems.getDefault().getSeparator());
+ policyScope = policyScope.replace(".", File.separator);
}
if(policyScope == null){
policyScope = "";
@@ -1329,7 +1330,7 @@ public class PolicyDBDao {
PolicyLogger.error("buildPolicyScopeDirectory("+policy+") received null repo. Using blank.");
repo = "";
}
- Path returnPath = Paths.get(repo + FileSystems.getDefault().getSeparator() + policyScope);
+ Path returnPath = Paths.get(repo + File.separator + policyScope);
if(returnPath != null){
return returnPath.toString();
} else {
@@ -1341,9 +1342,7 @@ public class PolicyDBDao {
}
private String buildPolicyScopeDirectory(String policyScope){
String repo = buildPolicyDirectory();
- policyScope = policyScope.replace(".", FileSystems.getDefault().getSeparator());
- return repo + FileSystems.getDefault().getSeparator() + policyScope;
-
+ return repo + File.separator + policyScope.replace(".", File.separator);
}
private static String buildPolicyDirectory(){
@@ -1628,7 +1627,13 @@ public class PolicyDBDao {
} catch(Exception e){
PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "auditLocalDatabase() error");
logger.error("Exception Occured"+e);
- }
+ }finally{
+ try {
+ Files.walk(webappsPath).close();
+ } catch (IOException e) {
+ logger.error("Exception Occured while closing File Stream"+e);
+ }
+ }
}
/**
@@ -1980,7 +1985,7 @@ public class PolicyDBDao {
for(int j=i;j<gitPathParts.size();j++){
testGitPath = Paths.get(testGitPath.toString(),gitPathParts.get(j));
}
- if(path.contains(testGitPath.toString())){
+ if(path != null && path.contains(testGitPath.toString())){
gitPath = testGitPath.toString();
break;
}
@@ -1989,7 +1994,7 @@ public class PolicyDBDao {
logger.debug("gitPath is null. Returning");
return null;
}
- if(gitPath.length() >= path.length()){
+ if(path != null && (gitPath.length() >= path.length())){
logger.debug("gitPath length(): " + gitPath.length() + ">= path.length(): " + path.length() + ". Returning null");
return null;
}
@@ -2996,6 +3001,13 @@ public class PolicyDBDao {
}
}
}
+ if(policyXmlStream != null){
+ try {
+ policyXmlStream.close();
+ } catch (IOException e) {
+ logger.error("Exception Occured while closing input stream"+e);
+ }
+ }
createPolicy(policy.policyAdapter, username, policyScope,finalName,policyDataString);
}
diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/SafePolicyBuilder.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/SafePolicyBuilder.java
index 7637719b1..c4f53582b 100644
--- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/SafePolicyBuilder.java
+++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/SafePolicyBuilder.java
@@ -19,6 +19,7 @@
*/
package org.openecomp.policy.pap.xacml.rest.components;
+import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -30,6 +31,10 @@ import org.yaml.snakeyaml.constructor.Constructor;
public class SafePolicyBuilder {
+ private SafePolicyBuilder(){
+ //Private Constructor.
+ }
+
public static ControlLoopGuard loadYamlGuard(String specification) {
//
// Read the yaml into our Java Object
@@ -40,18 +45,29 @@ public class SafePolicyBuilder {
return (ControlLoopGuard) obj;
}
- public static String generateXacmlGuard(String xacmlFileContent,Map<String, String> generateMap) {
- for(String key: generateMap.keySet()){
- Pattern p = Pattern.compile("\\$\\{" +key +"\\}");
+ public static String generateXacmlGuard(String xacmlFileContent,Map<String, String> generateMap, List<String> blacklist) {
+ for(Map.Entry<String,String> map: generateMap.entrySet()){
+ Pattern p = Pattern.compile("\\$\\{" +map.getKey() +"\\}");
Matcher m = p.matcher(xacmlFileContent);
- String finalInput = generateMap.get(key);
+ String finalInput = map.getValue();
if(finalInput.contains("$")){
finalInput = finalInput.replace("$", "\\$");
}
xacmlFileContent=m.replaceAll(finalInput);
}
+ if(blacklist!=null && !blacklist.isEmpty()){
+ StringBuilder rule = new StringBuilder();
+ for(String blackListName : blacklist){
+ if(blackListName.contains("$")){
+ blackListName = blackListName.replace("$", "\\$");
+ }
+ rule.append("<AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">"+blackListName+"</AttributeValue>");
+ }
+ Pattern p = Pattern.compile("\\$\\{blackListElement\\}");
+ Matcher m = p.matcher(xacmlFileContent);
+ xacmlFileContent=m.replaceAll(rule.toString());
+ }
PolicyLogger.info("Generated XACML from the YAML Spec: \n" + xacmlFileContent);
-
return xacmlFileContent;
}
}
diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java
index 8d253d385..108d33c25 100644
--- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java
+++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java
@@ -1010,7 +1010,7 @@ public class MicroServiceDictionaryController {
this.newModel.setDependency("");
}
- if (mainClass.getDependency()==null){
+ if (mainClass != null && mainClass.getDependency()==null){
mainClass.setDependency("");
}
diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/PushPolicyController.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/PushPolicyController.java
index f468b374d..3f86378ab 100644
--- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/PushPolicyController.java
+++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/PushPolicyController.java
@@ -109,30 +109,6 @@ public class PushPolicyController {
}
}
- /*private void safetyChecker(String policyName) {
- if (XACMLProperties.getProperty("xacml.rest.pap.safetychecker").equals("on")) {
- if (policyName.contains("Config_MS_") || policyName.contains("BRMS_Param")) {
- SafetyCheckerService service = new SafetyCheckerService();
- PolicySafetyChecker safetyChecker = new PolicySafetyChecker();
- boolean isEntered = false;
- try {
- JSONObject policyDataObj = service.getConfigByPolicyName(policyName, XACMLPapServlet.getConfigHome());
- isEntered = safetyChecker.addItem(policyDataObj);
- } catch (Exception e) {
- PolicyLogger.warn(MessageCodes.ERROR_PROCESS_FLOW, "XACMLPapServlet", e, "Error while adding ClosedLoop in the database: "
- + "This is a PolicySafetyChecker warning, the push execution may proceed normally.");
- }
- if (isEntered) {
- LOGGER.info("SafetyChecker successfully added the closedLoop to the DB table.");
- } else {
- LOGGER.info("SafetyChecker failed to add the closedLoop to the DB table.");
- }
- }
- } else {
- LOGGER.info("PolicySafetyChecker is turned off.");
- }
- }*/
-
private void addPolicyToGroup(String policyScope, String policyID, String policyName, String pdpGroup, HttpServletResponse response) {
StdPDPGroup selectedPDPGroup = null;
StdPDPPolicy selectedPolicy = null;
diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java
index 75bd725f0..4dd48adfd 100644
--- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java
+++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java
@@ -194,7 +194,7 @@ public class ElkConnectorImpl implements ElkConnector{
LOGGER.trace("ENTER: " + text);
}
- if (filter_s == null || filter_s.size() <= 0) {
+ if (filter_s == null || filter_s.size() == 0) {
return search(type, text);
}
diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DeleteHandler.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DeleteHandler.java
index ff454ade9..88548ffa4 100644
--- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DeleteHandler.java
+++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DeleteHandler.java
@@ -308,7 +308,9 @@ public class DeleteHandler {
return true;
}
}finally{
- st.close();
+ if(st != null){
+ st.close();
+ }
}
}
return false;
diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/policycontroller/PolicyCreation.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/policycontroller/PolicyCreation.java
index dde2a0d3b..3437dab03 100644
--- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/policycontroller/PolicyCreation.java
+++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/policycontroller/PolicyCreation.java
@@ -29,6 +29,7 @@ import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+import org.apache.commons.lang.StringUtils;
import org.openecomp.policy.common.logging.eelf.PolicyLogger;
import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
import org.openecomp.policy.common.logging.flexlogger.Logger;
@@ -363,13 +364,17 @@ public class PolicyCreation extends AbstractPolicyCreation{
}
}
}
- if(policyData.getRuleProvider()!=null && policyData.getRuleProvider().equals(DecisionPolicy.GUARD_YAML) && policyData.getYamlparams()!=null){
- attributeMap.put("actor", policyData.getYamlparams().getActor());
+ if(policyData.getRuleProvider()!=null && (policyData.getRuleProvider().equals(DecisionPolicy.GUARD_YAML)|| policyData.getRuleProvider().equals(DecisionPolicy.GUARD_BL_YAML))
+ && policyData.getYamlparams()!=null){ attributeMap.put("actor", policyData.getYamlparams().getActor());
attributeMap.put("recipe", policyData.getYamlparams().getRecipe());
attributeMap.put("limit", policyData.getYamlparams().getLimit());
attributeMap.put("timeWindow", policyData.getYamlparams().getTimeWindow());
attributeMap.put("guardActiveStart", policyData.getYamlparams().getGuardActiveStart());
attributeMap.put("guardActiveEnd", policyData.getYamlparams().getGuardActiveEnd());
+ if(policyData.getYamlparams().getBlackList()!=null){
+ String blackList = StringUtils.join(policyData.getYamlparams().getBlackList(), ",");
+ attributeMap.put("blackList", blackList);
+ }
}
policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels);
policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo);
diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/service/ImportService.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/service/ImportService.java
index 3ff279d8d..d70332edf 100644
--- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/service/ImportService.java
+++ b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/service/ImportService.java
@@ -35,7 +35,7 @@ import javax.servlet.http.HttpServletResponse;
import org.openecomp.policy.common.logging.eelf.PolicyLogger;
import org.openecomp.policy.pap.xacml.rest.components.CreateBRMSRuleTemplate;
-import org.openecomp.policy.pap.xacml.rest.components.CreateNewMicroSerivceModel;
+import org.openecomp.policy.pap.xacml.rest.components.CreateNewMicroServiceModel;
public class ImportService {
@@ -65,7 +65,7 @@ public class ImportService {
successMap = brmsRuleTemplate.addRule(builder.toString(), serviceName, description, "API");
break;
case "MICROSERVICE":
- CreateNewMicroSerivceModel newMS = null;
+ CreateNewMicroServiceModel newMS = null;
String randomID = UUID.randomUUID().toString();
if ( fileName != null) {
File extracDir = new File("ExtractDir");
@@ -105,7 +105,7 @@ public class ImportService {
outputStream.write(buffer, 0, bytesRead) ;
}
} catch (IOException e) {
- PolicyLogger.error("Error in reading in Zip File from API call");
+ PolicyLogger.error("Error in reading in Zip File from API call"+e);
return;
}finally{
try {
@@ -120,7 +120,7 @@ public class ImportService {
}
}
}
- newMS = new CreateNewMicroSerivceModel(fileName, serviceName, "API", version, randomID);
+ newMS = new CreateNewMicroServiceModel(fileName, serviceName, "API", version, randomID);
successMap = newMS.addValuesToNewModel();
if (successMap.containsKey("success")) {
successMap.clear();
diff --git a/packages/base/src/files/install/servers/pap/bin/Decision_GuardPolicyTemplate.xml b/ECOMP-PAP-REST/src/main/resources/Decision_GuardBLPolicyTemplate.xml
index 6701a0848..1e428ff34 100644
--- a/packages/base/src/files/install/servers/pap/bin/Decision_GuardPolicyTemplate.xml
+++ b/ECOMP-PAP-REST/src/main/resources/Decision_GuardBLPolicyTemplate.xml
@@ -1,5 +1,5 @@
<?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:d56af069-6cf1-430c-ba07-e26602e06a52" Version="1" RuleCombiningAlgId="urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides">
+<Policy xmlns="urn:oasis:names:tc:xacml:3.0:core:schema:wd-17" PolicyId="urn:com:xacml:policy:id:d56af069-6cf1-430c-ba07-e26602e06a52" Version="1" RuleCombiningAlgId="urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-unless-deny">
<Description>${description}</Description>
<Target>
<AnyOf>
@@ -37,8 +37,8 @@
</AnyOf>
</Target>
<Condition>
- <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:or">
- <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:not">
+ <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:not">
+ <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:and">
<Apply FunctionId="urn:oasis:names:tc:xacml:2.0:function:time-in-range">
<Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:time-one-and-only">
<AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:environment:current-time" DataType="http://www.w3.org/2001/XMLSchema#time" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:environment" MustBePresent="false"/>
@@ -46,12 +46,16 @@
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">${guardActiveStart}</AttributeValue>
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">${guardActiveEnd}</AttributeValue>
</Apply>
- </Apply>
- <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-less-than-or-equal">
- <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-one-and-only">
- <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="count" DataType="http://www.w3.org/2001/XMLSchema#integer" Issuer="org:openecomp:xacml:sql:${timeWindow}" MustBePresent="false"/>
- </Apply>
- <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#integer">${limit}</AttributeValue>
+ <Apply FunctionId="urn:oasis:names:tc:xacml:3.0:function:any-of">
+ <Function FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-equal"/>
+ <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-one-and-only">
+ <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="target" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/>
+ </Apply>
+ <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-bag">
+ <!-- <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">vserver.vserver-name</AttributeValue>-->
+ ${blackListElement}
+ </Apply>
+ </Apply>
</Apply>
</Apply>
</Condition>
@@ -69,27 +73,31 @@
</Target>
<Condition>
<Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:not">
- <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:or">
- <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:not">
- <Apply FunctionId="urn:oasis:names:tc:xacml:2.0:function:time-in-range">
- <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:time-one-and-only">
- <AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:environment:current-time" DataType="http://www.w3.org/2001/XMLSchema#time" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:environment" MustBePresent="false"/>
- </Apply>
- <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">${guardActiveStart}</AttributeValue>
- <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">${guardActiveEnd}</AttributeValue>
- </Apply>
- </Apply>
- <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-less-than-or-equal">
- <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:integer-one-and-only">
- <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="count" DataType="http://www.w3.org/2001/XMLSchema#integer" Issuer="org:openecomp:xacml:sql:${timeWindow}" MustBePresent="false"/>
- </Apply>
- <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#integer">${limit}</AttributeValue>
- </Apply>
- </Apply>
+ <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:not">
+ <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:and">
+ <Apply FunctionId="urn:oasis:names:tc:xacml:2.0:function:time-in-range">
+ <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:time-one-and-only">
+ <AttributeDesignator AttributeId="urn:oasis:names:tc:xacml:1.0:environment:current-time" DataType="http://www.w3.org/2001/XMLSchema#time" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:environment" MustBePresent="false"/>
+ </Apply>
+ <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">${guardActiveStart}</AttributeValue>
+ <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#time">${guardActiveEnd}</AttributeValue>
+ </Apply>
+ <Apply FunctionId="urn:oasis:names:tc:xacml:3.0:function:any-of">
+ <Function FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-equal"/>
+ <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-one-and-only">
+ <AttributeDesignator Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource" AttributeId="target" DataType="http://www.w3.org/2001/XMLSchema#string" MustBePresent="false"/>
+ </Apply>
+ <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:string-bag">
+ <!-- <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">vserver.vserver-name</AttributeValue>-->
+ ${blackListElement}
+ </Apply>
+ </Apply>
+ </Apply>
+ </Apply>
</Apply>
</Condition>
<AdviceExpressions>
- <AdviceExpression AdviceId="GUARD_YAML" AppliesTo="Deny">
+ <AdviceExpression AdviceId="GUARD_BL_YAML" AppliesTo="Deny">
<AttributeAssignmentExpression AttributeId="guard.response" Category="urn:oasis:names:tc:xacml:3.0:attribute-category:resource">
<AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">Denied!</AttributeValue>
</AttributeAssignmentExpression>
diff --git a/ECOMP-PAP-REST/Decision_GuardPolicyTemplate.xml b/ECOMP-PAP-REST/src/main/resources/Decision_GuardPolicyTemplate.xml
index 6701a0848..6701a0848 100644
--- a/ECOMP-PAP-REST/Decision_GuardPolicyTemplate.xml
+++ b/ECOMP-PAP-REST/src/main/resources/Decision_GuardPolicyTemplate.xml
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/PapUrlResolver.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/PapUrlResolver.java
index 9d7ebbe6e..924c2b5ff 100644
--- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/PapUrlResolver.java
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/PapUrlResolver.java
@@ -24,7 +24,6 @@ import java.net.URI;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
-import java.util.Arrays;
import java.util.Date;
import java.util.NoSuchElementException;
import java.util.Properties;
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpLoader.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpLoader.java
index b4433036b..0766ac469 100644
--- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpLoader.java
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpLoader.java
@@ -559,7 +559,7 @@ public class XACMLPdpLoader {
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while retrieving policy "
+ policy
+ " from URL "
- + url.toString() + ", e=" + e);
+ + url + ", e=" + e);
}
}
papUrls.getNext();
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PAPServices.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PAPServices.java
index fe8c79409..4a705f5c4 100644
--- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PAPServices.java
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PAPServices.java
@@ -490,9 +490,16 @@ public class PAPServices {
+ connection.getHeaderField("message");
} else if ("addGroupError".equals(connection.getHeaderField("error"))) {
response = connection.getHeaderField("message");
+ } else if ("validation".equals(connection.getHeaderField("error"))){
+ response = XACMLErrorConstants.ERROR_DATA_ISSUE
+ + "Validation errors during policy engine " + connection.getHeaderField("operation") +
+ " for " + connection.getHeaderField("service");
} else if ("error".equals(connection.getHeaderField("error"))) {
response = XACMLErrorConstants.ERROR_UNKNOWN
+ "Could not create or update the policy for and unknown reason";
+ }else{
+ response = XACMLErrorConstants.ERROR_DATA_ISSUE
+ + "BAD REQUEST: Error occured while attempting perform this operation.. the request may be incorrect.";
}
LOGGER.error(response);
} else {
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PolicyEngineImportService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PolicyEngineImportService.java
index 38a0da32e..2a526f751 100644
--- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PolicyEngineImportService.java
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PolicyEngineImportService.java
@@ -80,10 +80,10 @@ public class PolicyEngineImportService {
}
private void specialCheck() {
- if(importResponse.contains("BAD REQUEST") || importResponse.contains("PE300")){
- status = HttpStatus.BAD_REQUEST;
- }else if(importResponse.contains("PE200")){
+ if(importResponse==null || importResponse.contains("PE200")){
status = HttpStatus.INTERNAL_SERVER_ERROR;
+ }else if(importResponse.contains("BAD REQUEST") || importResponse.contains("PE300")){
+ status = HttpStatus.BAD_REQUEST;
}
}
diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPApiAuth.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPApiAuth.java
index a5d3adb7a..c4573cc0d 100644
--- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPApiAuth.java
+++ b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPApiAuth.java
@@ -51,6 +51,10 @@ public class PDPApiAuth {
private static Long oldModified = null;
private static AAFPolicyClient aafClient = null;
+ private PDPApiAuth(){
+ // Private Constructor
+ }
+
/*
* Set Property by reading the properties File.
*/
@@ -84,7 +88,7 @@ public class PDPApiAuth {
String resource) {
try{
String[] userNamePass = PolicyUtils.decodeBasicEncoding(clientEncoding);
- if(userNamePass==null){
+ if(userNamePass==null || userNamePass.length==0){
String usernameAndPassword = null;
byte[] decodedBytes = Base64.getDecoder().decode(clientEncoding);
usernameAndPassword = new String(decodedBytes, "UTF-8");
diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/YAMLParams.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/YAMLParams.java
index adcce2633..71a99d2fb 100644
--- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/YAMLParams.java
+++ b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/YAMLParams.java
@@ -20,6 +20,8 @@
package org.openecomp.policy.rest.adapter;
+import java.util.List;
+
public class YAMLParams {
private String actor;
private String recipe;
@@ -27,6 +29,7 @@ public class YAMLParams {
private String timeWindow;
private String guardActiveStart;
private String guardActiveEnd;
+ private List<String> blackList;
public String getActor() {
return actor;
@@ -64,4 +67,10 @@ public class YAMLParams {
public void setGuardActiveEnd(String guardActiveEnd) {
this.guardActiveEnd = guardActiveEnd;
}
+ public List<String> getBlackList() {
+ return blackList;
+ }
+ public void setBlackList(List<String> blackList) {
+ this.blackList = blackList;
+ }
}
diff --git a/ECOMP-SDK-APP/xacml.admin.properties b/ECOMP-SDK-APP/xacml.admin.properties
index ded60a5b9..b3550dfc1 100644
--- a/ECOMP-SDK-APP/xacml.admin.properties
+++ b/ECOMP-SDK-APP/xacml.admin.properties
@@ -149,7 +149,7 @@ xacml.rest.pap.password=alpha123
# new Property Please mention your PAP-REST webapps Location here.
-xacml.rest.config.webapps=C:\\Second Tomcat\\apache-tomcat-8.0.23\\webapps\\ConfigPAP\\
+xacml.rest.config.webapps=/home/users/PolicyEngine/webapps/ConfigPAP/
# pdps file - Needs to have the location of the PDPs File of the PAP-REST
xacml.rest.pdp.idfile=test.properties
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 fdf43264f..639e29e3d 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
@@ -353,6 +353,16 @@ public class PolicyManagerServlet extends HttpServlet {
if(scopes.isEmpty()){
return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
}
+ Set<String> tempScopes = scopes;
+ for(String scope : tempScopes){
+ List<Object> scopesList = queryPolicyEditorScopes(scope);
+ if(!scopesList.isEmpty()){
+ for(int i = 0; i < scopesList.size(); i++){
+ PolicyEditorScopes tempScope = (PolicyEditorScopes) scopesList.get(i);
+ scopes.add(tempScope.getScopeName());
+ }
+ }
+ }
}
if(policyList!= null){
for(int i = 0; i < policyList.length(); i++){
@@ -384,9 +394,13 @@ public class PolicyManagerServlet extends HttpServlet {
List<Object> filterdatas = controller.getData(PolicyVersion.class);
for(Object filter : filterdatas){
PolicyVersion filterdata = (PolicyVersion) filter;
- String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator));
- if(scopes.contains(scopeName)){
- policyData.add(filterdata);
+ try{
+ String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator));
+ if(scopes.contains(scopeName)){
+ policyData.add(filterdata);
+ }
+ }catch(Exception e){
+ LOGGER.error("Exception occured while filtering policyversion data"+e);
}
}
}
@@ -567,11 +581,6 @@ public class PolicyManagerServlet extends HttpServlet {
}
}
}
- if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
- if(scopes.isEmpty()){
- return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
- }
- }
List<JSONObject> resultList = new ArrayList<>();
boolean onlyFolders = params.getBoolean("onlyFolders");
@@ -580,7 +589,18 @@ public class PolicyManagerServlet extends HttpServlet {
path = path.replaceAll("..xml", "").trim();
}
-
+ if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) {
+ if(scopes.isEmpty()){
+ return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin");
+ }else{
+ if(!"/".equals(path)){
+ String tempScope = path.substring(1, path.length());
+ tempScope = tempScope.replace("/", File.separator);
+ scopes.add(tempScope);
+ }
+ }
+ }
+
if("/".equals(path)){
if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){
List<Object> scopesList = queryPolicyEditorScopes(null);
@@ -601,14 +621,16 @@ public class PolicyManagerServlet extends HttpServlet {
for(Object scope : scopes){
JSONObject el = new JSONObject();
List<Object> scopesList = queryPolicyEditorScopes(scope.toString());
- PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
- el.put("name", scopeById.getScopeName());
- el.put("date", scopeById.getCreatedDate());
- el.put("size", "");
- el.put("type", "dir");
- el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
- el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
- resultList.add(el);
+ if(!scopesList.isEmpty()){
+ PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0);
+ el.put("name", scopeById.getScopeName());
+ el.put("date", scopeById.getCreatedDate());
+ el.put("size", "");
+ el.put("type", "dir");
+ el.put("createdBy", scopeById.getUserCreatedBy().getUserName());
+ el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName());
+ resultList.add(el);
+ }
}
}
}else{
@@ -632,7 +654,7 @@ public class PolicyManagerServlet extends HttpServlet {
if(scopeName == null){
scopeNamequery = "from PolicyEditorScopes";
}else{
- scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"'";
+ scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"%'";
}
PolicyController controller = getPolicyControllerInstance();
List<Object> scopesList = controller.getDataByQuery(scopeNamequery);
@@ -945,6 +967,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{
+ FileWriter fw = null;
String queryEntityName = null;
PolicyController controller = getPolicyControllerInstance();
PolicyEntity cloneEntity = new PolicyEntity();
@@ -967,6 +990,15 @@ public class PolicyManagerServlet extends HttpServlet {
controller.saveData(configurationDataEntity);
ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName);
cloneEntity.setConfigurationData(configEntiy);
+ String newConfigurationName = configEntiy.getConfigurationName();
+ try {
+ fw = new FileWriter(PolicyController.getConfigHome() + File.separator + newConfigurationName);
+ BufferedWriter bw = new BufferedWriter(fw);
+ bw.write(configEntiy.getConfigBody());
+ bw.close();
+ } catch (IOException e) {
+ LOGGER.error("Exception Occured While cloning the configuration file"+e);
+ }
}else if(newpolicyName.contains("Action_")){
ActionBodyEntity actionBodyEntity = new ActionBodyEntity();
actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension));
@@ -978,6 +1010,22 @@ public class PolicyManagerServlet extends HttpServlet {
controller.saveData(actionBodyEntity);
ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class, "actionBodyName", queryEntityName);
cloneEntity.setActionBodyEntity(actionEntiy);
+ String newConfigurationName = actionEntiy.getActionBodyName();
+ try {
+ fw = new FileWriter(PolicyController.getActionHome() + File.separator + newConfigurationName);
+ BufferedWriter bw = new BufferedWriter(fw);
+ bw.write(actionEntiy.getActionBody());
+ bw.close();
+ } catch (IOException e) {
+ LOGGER.error("Exception Occured While cloning the configuration file"+e);
+ }
+ }
+ if(fw != null){
+ try {
+ fw.close();
+ } catch (IOException e) {
+ LOGGER.error("Exception Occured While closing the File input stream"+e);
+ }
}
cloneEntity.setDeleted(entity.isDeleted());
cloneEntity.setCreatedBy(userId);
@@ -1033,45 +1081,20 @@ public class PolicyManagerServlet extends HttpServlet {
String policyEntityquery = "FROM PolicyEntity where policyName = '"+newPolicySplit[1]+"' and scope ='"+newPolicySplit[0]+"'";
List<Object> queryData = controller.getDataByQuery(policyEntityquery);
if(!queryData.isEmpty()){
+ return error("Policy already exists with same name");
+ }
+
+ //Query the Policy Entity with oldPolicy Name
+ policyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'";
+ queryData = controller.getDataByQuery(policyEntityquery);
+ if(!queryData.isEmpty()){
entity = (PolicyEntity) queryData.get(0);
}
if(entity != null){
- //if a policy exists with new name check if it is deleted or not
- if(entity.isDeleted()){
- //Check Policy Group Entity table if policy has been pushed or not
- String query = "from PolicyGroupEntity where policyid = '"+entity.getPolicyId()+"'";
- List<Object> object = controller.getDataByQuery(query);
- if(object == null){
- //if PolicyGroupEntity data is empty delete the entry from database
- controller.deleteData(entity);
- //Query the Policy Entity with oldPolicy Name
- policyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'";
- queryData = controller.getDataByQuery(policyEntityquery);
- if(!queryData.isEmpty()){
- entity = (PolicyEntity) queryData.get(0);
- }
- if(entity != null){
- cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId);
- success = true;
- }
- }else{
- return error("Policy Clone failed due to policy with new name existing in PDP Group.");
- }
- }else{
- return error("Policy Clone failed due to same name existing.");
- }
- }else{
- //Query the Policy Entity with oldPolicy Name
- policyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'";
- queryData = controller.getDataByQuery(policyEntityquery);
- if(!queryData.isEmpty()){
- entity = (PolicyEntity) queryData.get(0);
- }
- if(entity != null){
- cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId);
- success = true;
- }
+ cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId);
+ success = true;
}
+
if(success){
PolicyVersion entityItem = new PolicyVersion();
entityItem.setActiveVersion(Integer.parseInt(version));
@@ -1394,18 +1417,15 @@ public class PolicyManagerServlet extends HttpServlet {
}
LOGGER.debug("addFolder path: {} name: {}" + path +name);
if(!name.equals("")){
+ if(name.startsWith(File.separator)){
+ name = name.substring(1);
+ }
PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, "scopeName", name);
if(entity == null){
UserInfo userInfo = new UserInfo();
userInfo.setUserLoginId(userId);
PolicyEditorScopes newScope = new PolicyEditorScopes();
- String scopeName = null;
- if(name.startsWith(File.separator)){
- scopeName = name.substring(1);
- }else{
- scopeName = name;
- }
- newScope.setScopeName(scopeName);
+ newScope.setScopeName(name);
newScope.setUserCreatedBy(userInfo);
newScope.setUserModifiedBy(userInfo);
controller.saveData(newScope);
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 582dd6c68..2c04bc66d 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
@@ -380,14 +380,21 @@ 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, "POST", uri.replaceFirst("/", "").trim());
- if(body.contains("CouldNotConnectException")){
+ try{
+ String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
+ if(body.contains("CouldNotConnectException")){
+ List<String> data = new ArrayList<>();
+ data.add("Elastic Search Server is down");
+ resultList = data;
+ }else{
+ JSONObject json = new JSONObject(body);
+ resultList = json.get("policyresult");
+ }
+ }catch(Exception e){
+ policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception Occured while querying Elastic Search: " + e);
List<String> data = new ArrayList<>();
data.add("Elastic Search Server is down");
resultList = data;
- }else{
- JSONObject json = new JSONObject(body);
- resultList = json.get("policyresult");
}
response.setCharacterEncoding(PolicyController.getCharacterencoding());
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 68dff19bd..8258b8bed 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
@@ -20,7 +20,12 @@
package org.openecomp.policy.controller;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
import java.io.PrintWriter;
+import java.nio.file.Files;
+import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
@@ -355,11 +360,25 @@ public class CreateBRMSParamController extends RestrictedBaseController {
private void paramUIGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
String data = entity.getConfigurationData().getConfigBody();
if(data != null){
+ File file = new File(PolicyController.getConfigHome() +File.separator+ entity.getConfigurationData().getConfigurationName());
+ if(file.exists()){
+ try (BufferedReader br = new BufferedReader(new FileReader(file))) {
+ StringBuilder sb = new StringBuilder();
+ String line = br.readLine();
+ while (line != null) {
+ sb.append(line);
+ sb.append("\n");
+ line = br.readLine();
+ }
+ }catch(Exception e){
+ policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ e.getMessage() + e);
+ }
+ }
try {
StringBuilder params = new StringBuilder("");
Boolean flag = false;
Boolean comment = false;
- for (String line : data.split("\n")) {
+ for (String line : Files.readAllLines(Paths.get(file.toString()))) {
if (line.isEmpty() || line.startsWith("//")) {
continue;
}
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java
index 2fecd7eea..28278062d 100644
--- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java
@@ -157,6 +157,8 @@ public class DecisionPolicyController extends RestrictedBaseController {
break;
}else if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().toString().equalsIgnoreCase("GUARD_YAML")){
policyAdapter.setRuleProvider("GUARD_YAML");
+ }else if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().toString().equalsIgnoreCase("GUARD_BL_YAML")){
+ policyAdapter.setRuleProvider("GUARD_BL_YAML");
}
}else{
policyAdapter.setRuleProvider("Custom");
@@ -166,7 +168,7 @@ public class DecisionPolicyController extends RestrictedBaseController {
ApplyType decisionApply = (ApplyType) condition.getExpression().getValue();
decisionApply = (ApplyType) decisionApply.getExpression().get(0).getValue();
ruleAlgoirthmTracker = new LinkedList<>();
- if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals("GUARD_YAML")){
+ if(policyAdapter.getRuleProvider()!=null && (policyAdapter.getRuleProvider().equals("GUARD_YAML")||(policyAdapter.getRuleProvider().equals("GUARD_BL_YAML")))){
YAMLParams yamlParams = new YAMLParams();
for(int i=0; i<attributeList.size() ; i++){
Map<String, String> map = (Map<String,String>)attributeList.get(i);
@@ -179,9 +181,19 @@ public class DecisionPolicyController extends RestrictedBaseController {
ApplyType apply = ((ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(0).getValue());
yamlParams.setGuardActiveStart(((AttributeValueType)apply.getExpression().get(1).getValue()).getContent().get(0).toString());
yamlParams.setGuardActiveEnd(((AttributeValueType)apply.getExpression().get(2).getValue()).getContent().get(0).toString());
- yamlParams.setLimit(((AttributeValueType)((ApplyType)decisionApply.getExpression().get(1).getValue()).getExpression().get(1).getValue()).getContent().get(0).toString());
- String timeWindow = ((AttributeDesignatorType)((ApplyType)((ApplyType)decisionApply.getExpression().get(1).getValue()).getExpression().get(0).getValue()).getExpression().get(0).getValue()).getIssuer();
- yamlParams.setTimeWindow(timeWindow.substring(timeWindow.lastIndexOf(":")+1));
+ if(policyAdapter.getRuleProvider().equals("GUARD_BL_YAML")){
+ apply = (ApplyType)((ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(1).getValue()).getExpression().get(2).getValue();
+ Iterator<JAXBElement<?>> attributes = apply.getExpression().iterator();
+ List<String> blackList = new ArrayList<>();
+ while(attributes.hasNext()){
+ blackList.add(((AttributeValueType)attributes.next().getValue()).getContent().get(0).toString());
+ }
+ yamlParams.setBlackList(blackList);
+ }else{
+ yamlParams.setLimit(((AttributeValueType)((ApplyType)decisionApply.getExpression().get(1).getValue()).getExpression().get(1).getValue()).getContent().get(0).toString());
+ String timeWindow = ((AttributeDesignatorType)((ApplyType)((ApplyType)decisionApply.getExpression().get(1).getValue()).getExpression().get(0).getValue()).getExpression().get(0).getValue()).getIssuer();
+ yamlParams.setTimeWindow(timeWindow.substring(timeWindow.lastIndexOf(":")+1));
+ }
policyAdapter.setYamlparams(yamlParams);
policyAdapter.setAttributes(new ArrayList<Object>());
policyAdapter.setRuleAlgorithmschoices(new ArrayList<Object>());
diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java
index ff91e9381..bb138d415 100644
--- a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java
+++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java
@@ -30,6 +30,7 @@ import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
@@ -89,8 +90,6 @@ public class PolicyValidationController extends RestrictedBaseController {
public static final String MICROSERVICES="Micro Service";
private Pattern pattern;
private Matcher matcher;
-
- private static Map<String, String> rangeMap = new HashMap<>();
private static Map<String, String> mapAttribute = new HashMap<>();
private static final String EMAIL_PATTERN =
@@ -104,7 +103,7 @@ public class PolicyValidationController extends RestrictedBaseController {
public ModelAndView validatePolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{
try{
boolean valid = true;
- String responseString = "";
+ StringBuilder responseString = new StringBuilder();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JsonNode root = mapper.readTree(request.getReader());
@@ -112,17 +111,17 @@ public class PolicyValidationController extends RestrictedBaseController {
if(policyData.getPolicyName() != null){
String policyNameValidate = emptyValidator(policyData.getPolicyName());
if(!policyNameValidate.contains("success")){
- responseString = responseString + "PolicyName:" + policyNameValidate + "<br>";
+ responseString.append("PolicyName:" + policyNameValidate + "<br>");
valid = false;
};
}else{
- responseString = responseString + "PolicyName: PolicyName Should not be empty" + "<br>";
+ responseString.append( "PolicyName: PolicyName Should not be empty" + "<br>");
valid = false;
}
if(policyData.getPolicyDescription() != null){
String descriptionValidate = descriptionValidator(policyData.getPolicyDescription());
if(!descriptionValidate.contains("success")){
- responseString = responseString + "Description:" + descriptionValidate + "<br>";
+ responseString.append("Description:" + descriptionValidate + "<br>");
valid = false;
}
}
@@ -133,11 +132,11 @@ public class PolicyValidationController extends RestrictedBaseController {
if(policyData.getEcompName() != null){
String ecompNameValidate = emptyValidator(policyData.getEcompName());
if(!ecompNameValidate.contains("success")){
- responseString = responseString + "EcompName:" + ecompNameValidate + "<br>";
+ responseString.append("EcompName:" + ecompNameValidate + "<br>");
valid = false;
}
}else{
- responseString = responseString + "Ecomp Name: Ecomp Name Should not be empty" + "<br>";
+ responseString.append("Ecomp Name: Ecomp Name Should not be empty" + "<br>");
valid = false;
}
}
@@ -145,33 +144,33 @@ public class PolicyValidationController extends RestrictedBaseController {
if(policyData.getRiskType() != null){
String riskTypeValidate = emptyValidator(policyData.getRiskType());
if(!riskTypeValidate.contains("success")){
- responseString = responseString + "RiskType:" + riskTypeValidate + "<br>";
+ responseString.append("RiskType:" + riskTypeValidate + "<br>");
valid = false;
}
}else {
- responseString = responseString + "Risk Type: Risk Type Should not be Empty" + "<br>";
+ responseString.append("Risk Type: Risk Type Should not be Empty" + "<br>");
valid = false;
}
if(policyData.getRiskLevel() != null){
String validateRiskLevel = emptyValidator(policyData.getRiskLevel());
if(!validateRiskLevel.contains("success")){
- responseString = responseString + "RiskLevel:" + validateRiskLevel + "<br>";
+ responseString.append("RiskLevel:" + validateRiskLevel + "<br>");
valid = false;
}
}else {
- responseString = responseString + "Risk Level: Risk Level Should not be Empty" + "<br>";
+ responseString.append("Risk Level: Risk Level Should not be Empty" + "<br>");
valid = false;
}
if(policyData.getGuard() != null){
String validateGuard = emptyValidator(policyData.getGuard());
if(!validateGuard.contains("success")){
- responseString = responseString + "Guard:" + validateGuard + "<br>";
+ responseString.append("Guard:" + validateGuard + "<br>");
valid = false;
}
}else {
- responseString = responseString + "Guard: Guard Value Should not be Empty" + "<br>";
+ responseString.append("Guard: Guard Value Should not be Empty" + "<br>");
valid = false;
}
@@ -179,21 +178,21 @@ public class PolicyValidationController extends RestrictedBaseController {
if(policyData.getConfigName() != null){
String configNameValidate = emptyValidator(policyData.getConfigName());
if(!configNameValidate.contains("success")){
- responseString = responseString + "ConfigName:" + configNameValidate + "<br>";
+ responseString.append("ConfigName:" + configNameValidate + "<br>");
valid = false;
}
}else{
- responseString = responseString + "Config Name: Config Name Should not be Empty" + "<br>";
+ responseString.append("Config Name: Config Name Should not be Empty" + "<br>");
valid = false;
}
if(policyData.getConfigType() != null){
String configTypeValidate = emptyValidator(policyData.getConfigType());
if(!configTypeValidate.contains("success")){
- responseString = responseString + "ConfigType:" + configTypeValidate + "<br>";
+ responseString.append("ConfigType:" + configTypeValidate + "<br>");
valid = false;
}
}else{
- responseString = responseString + "Config Type: Config Type Should not be Empty" + "<br>";
+ responseString.append("Config Type: Config Type Should not be Empty" + "<br>");
valid = false;
}
if(policyData.getConfigBodyData() != null){
@@ -202,28 +201,28 @@ public class PolicyValidationController extends RestrictedBaseController {
if (policyType != null) {
if (policyType.equals("JSON")) {
if (!isJSONValid(configBodyData)) {
- responseString = responseString + "Config Body: JSON Content is not valid" + "<br>";
+ responseString.append("Config Body: JSON Content is not valid" + "<br>");
valid = false;
}
} else if (policyType.equals("XML")) {
if (!isXMLValid(configBodyData)) {
- responseString = responseString + "Config Body: XML Content data is not valid" + "<br>";
+ responseString.append("Config Body: XML Content data is not valid" + "<br>");
valid = false;
}
} else if (policyType.equals("PROPERTIES")) {
if (!isPropValid(configBodyData)||configBodyData.equals("")) {
- responseString = responseString + "Config Body: Property data is not valid" + "<br>";
+ responseString.append("Config Body: Property data is not valid" + "<br>");
valid = false;
}
} else if (policyType.equals("OTHER")) {
if (configBodyData.equals("")) {
- responseString = responseString + "Config Body: Config Body Should not be Empty" + "<br>";
+ responseString.append("Config Body: Config Body Should not be Empty" + "<br>");
valid = false;
}
}
}
}else{
- responseString = responseString + "Config Body: Config Body Should not be Empty" + "<br>";
+ responseString.append("Config Body: Config Body Should not be Empty" + "<br>");
valid = false;
}
}
@@ -232,21 +231,21 @@ public class PolicyValidationController extends RestrictedBaseController {
if(policyData.getConfigName() != null){
String configNameValidate = PolicyUtils.emptyPolicyValidator(policyData.getConfigName());
if(!configNameValidate.contains("success")){
- responseString = responseString + "<b>ConfigName</b>:<i>" + configNameValidate + "</i><br>";
+ responseString.append("<b>ConfigName</b>:<i>" + configNameValidate + "</i><br>");
valid = false;
}
}else{
- responseString = responseString + "<b>Config Name</b>:<i> Config Name is required" + "</i><br>";
+ responseString.append("<b>Config Name</b>:<i> Config Name is required" + "</i><br>");
valid = false;
}
if(policyData.getSecurityZone() == null){
- responseString = responseString + "<b>Security Zone</b>:<i> Security Zone is required" + "</i><br>";
+ responseString.append("<b>Security Zone</b>:<i> Security Zone is required" + "</i><br>");
valid = false;
}
}
if(policyData.getConfigPolicyType().equals("BRMS_Param")){
if(policyData.getRuleName() == null){
- responseString = responseString + "<b>BRMS Template</b>:<i>BRMS Template is required</i><br>";
+ responseString.append("<b>BRMS Template</b>:<i>BRMS Template is required</i><br>");
valid = false;
}
}
@@ -255,38 +254,38 @@ public class PolicyValidationController extends RestrictedBaseController {
String message = PolicyUtils.brmsRawValidate(policyData.getConfigBodyData());
// If there are any error other than Annotations then this is not Valid
if(message.contains("[ERR")){
- responseString = responseString + "<b>Raw Rule Validate</b>:<i>Raw Rule has error"+ message +"</i><br>";
+ responseString.append("<b>Raw Rule Validate</b>:<i>Raw Rule has error"+ message +"</i><br>");
valid = false;
}
}else{
- responseString = responseString + "<b>Raw Rule</b>:<i>Raw Rule is required</i><br>";
+ responseString.append("<b>Raw Rule</b>:<i>Raw Rule is required</i><br>");
valid = false;
}
}
if(policyData.getConfigPolicyType().equals("ClosedLoop_PM")){
try{
if(root.get("policyData").get("verticaMetrics").get("serviceTypePolicyName") == null && policyData.getServiceTypePolicyName().isEmpty()){
- responseString = responseString + "<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required</i><br>";
+ responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required</i><br>");
valid = false;
}
}catch(Exception e){
- responseString = responseString + "<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required</i><br>";
+ responseString.append("<b>ServiceType PolicyName</b>:<i>ServiceType PolicyName is required</i><br>");
valid = false;
}
if(root.get("policyData").get("jsonBodyData") != null){
ClosedLoopPMBody pmBody = (ClosedLoopPMBody)mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopPMBody.class);
if(pmBody.getEmailAddress() != null){
- String result = emailValidation(pmBody.getEmailAddress(), responseString);
+ String result = emailValidation(pmBody.getEmailAddress(), responseString.toString());
if(result != "success"){
- responseString = result + "<br>";
+ responseString.append(result + "<br>");
valid = false;
}
}
if(pmBody.getGeoLink() != null){
String result = PolicyUtils.emptyPolicyValidator(pmBody.getGeoLink());
if(!result.contains("success")){
- responseString = responseString + "<b>GeoLink</b>:<i>" + result + "</i><br>";
+ responseString.append("<b>GeoLink</b>:<i>" + result + "</i><br>");
valid = false;
};
}
@@ -297,14 +296,14 @@ public class PolicyValidationController extends RestrictedBaseController {
if(!key.contains("Message")){
String attributeValidate = PolicyUtils.emptyPolicyValidator(value);
if(!attributeValidate.contains("success")){
- responseString = responseString + "<b>Attributes</b>:<i>" + key + " : value has spaces</i><br>";
+ responseString.append("<b>Attributes</b>:<i>" + key + " : value has spaces</i><br>");
valid = false;
};
}
}
}
}else{
- responseString = responseString + "<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services</i><br>";
+ responseString.append("<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services</i><br>");
valid = false;
}
}
@@ -312,73 +311,69 @@ public class PolicyValidationController extends RestrictedBaseController {
if(root.get("policyData").get("jsonBodyData") != null){
ClosedLoopFaultBody faultBody = (ClosedLoopFaultBody)mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopFaultBody.class);
if(faultBody.getEmailAddress() != null){
- String result = emailValidation(faultBody.getEmailAddress(), responseString);
+ String result = emailValidation(faultBody.getEmailAddress(), responseString.toString());
if(result != "success"){
- responseString = result+ "<br>";
+ responseString.append(result+ "<br>");
valid = false;
}
}
if((faultBody.isGama() || faultBody.isMcr() || faultBody.isTrinity() || faultBody.isvDNS() || faultBody.isvUSP()) != true){
- responseString = responseString + "<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services</i><br>";
+ responseString.append("<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services</i><br>");
valid = false;
}
if(faultBody.getActions() == null){
- responseString = responseString + "<b>vPRO Actions</b>:<i>vPRO Actions is required</i><br>";
- valid = false;
- }
- if(faultBody.getAgingWindow() == 0){
- responseString = responseString + "<b>Aging Window</b>:<i>Aging Window is required</i><br>";
+ responseString.append("<b>vPRO Actions</b>:<i>vPRO Actions is required</i><br>");
valid = false;
}
if(faultBody.getClosedLoopPolicyStatus() == null){
- responseString = responseString + "<b>Policy Status</b>:<i>Policy Status is required</i><br>";
+ responseString.append("<b>Policy Status</b>:<i>Policy Status is required</i><br>");
valid = false;
}
if(faultBody.getConditions() == null){
- responseString = responseString + "<b>Conditions</b>:<i>Select Atleast one Condition</i><br>";
+ responseString.append("<b>Conditions</b>:<i>Select Atleast one Condition</i><br>");
valid = false;
}
if(faultBody.getGeoLink() != null){
- String result = PolicyUtils.emptyPolicyValidator(faultBody.getGeoLink());
+ String result = PolicyUtils.emptyPolicyValidatorWithSpaceAllowed(faultBody.getGeoLink());
if(!result.contains("success")){
- responseString = responseString + "<b>GeoLink</b>:<i>" + result + "</i><br>";
+ responseString.append("<b>GeoLink</b>:<i>" + result + "</i><br>");
valid = false;
};
}
if(faultBody.getTimeInterval() == 0){
- responseString = responseString + "<b>Time Interval</b>:<i>Time Interval is required</i><br>";
+ responseString.append("<b>Time Interval</b>:<i>Time Interval is required</i><br>");
valid = false;
}
if(faultBody.getRetrys() == 0){
- responseString = responseString + "<b>Number of Retries</b>:<i>Number of Retries is required</i><br>";
+ responseString.append("<b>Number of Retries</b>:<i>Number of Retries is required</i><br>");
valid = false;
}
if(faultBody.getTimeOutvPRO() == 0){
- responseString = responseString + "<b>APP-C Timeout</b>:<i>APP-C Timeout is required</i><br>";
+ responseString.append("<b>APP-C Timeout</b>:<i>APP-C Timeout is required</i><br>");
valid = false;
}
if(faultBody.getTimeOutRuby() == 0){
- responseString = responseString + "<b>TimeOutRuby</b>:<i>TimeOutRuby is required</i><br>";
+ responseString.append("<b>TimeOutRuby</b>:<i>TimeOutRuby is required</i><br>");
valid = false;
}
if(faultBody.getVnfType() == null){
- responseString = responseString + "<b>Vnf Type</b>:<i>Vnf Type is required</i><br>";
+ responseString.append("<b>Vnf Type</b>:<i>Vnf Type is required</i><br>");
valid = false;
}
}else{
- responseString = responseString + "<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services</i><br>";
- responseString = responseString + "<b>vPRO Actions</b>:<i>vPRO Actions is required</i><br>";
- responseString = responseString + "<b>Aging Window</b>:<i>Aging Window is required</i><br>";
- responseString = responseString + "<b>Policy Status</b>:<i>Policy Status is required</i><br>";
- responseString = responseString + "<b>Conditions</b>:<i>Select Atleast one Condition</i><br>";
- responseString = responseString + "<b>PEP Name</b>:<i>PEP Name is required</i><br>";
- responseString = responseString + "<b>PEP Action</b>:<i>PEP Action is required</i><br>";
- responseString = responseString + "<b>Time Interval</b>:<i>Time Interval is required</i><br>";
- responseString = responseString + "<b>Number of Retries</b>:<i>Number of Retries is required</i><br>";
- responseString = responseString + "<b>APP-C Timeout</b>:<i>APP-C Timeout is required</i><br>";
- responseString = responseString + "<b>TimeOutRuby</b>:<i>TimeOutRuby is required</i><br>";
- responseString = responseString + "<b>Vnf Type</b>:<i>Vnf Type is required</i><br>";
+ responseString.append("<b>D2/Virtualized Services</b>:<i>Select atleast one D2/Virtualized Services</i><br>");
+ responseString.append("<b>vPRO Actions</b>:<i>vPRO Actions is required</i><br>");
+ responseString.append("<b>Aging Window</b>:<i>Aging Window is required</i><br>");
+ responseString.append("<b>Policy Status</b>:<i>Policy Status is required</i><br>");
+ responseString.append("<b>Conditions</b>:<i>Select Atleast one Condition</i><br>");
+ responseString.append("<b>PEP Name</b>:<i>PEP Name is required</i><br>");
+ responseString.append("<b>PEP Action</b>:<i>PEP Action is required</i><br>");
+ responseString.append("<b>Time Interval</b>:<i>Time Interval is required</i><br>");
+ responseString.append("<b>Number of Retries</b>:<i>Number of Retries is required</i><br>");
+ responseString.append("<b>APP-C Timeout</b>:<i>APP-C Timeout is required</i><br>");
+ responseString.append("<b>TimeOutRuby</b>:<i>TimeOutRuby is required</i><br>");
+ responseString.append("<b>Vnf Type</b>:<i>Vnf Type is required</i><br>");
valid = false;
}
}
@@ -399,7 +394,7 @@ public class PolicyValidationController extends RestrictedBaseController {
returnModel = getAttributeObject(service, version);
String annoation = returnModel.getAnnotation();
if (!Strings.isNullOrEmpty(annoation)){
- rangeMap = new HashMap<String,String>();
+ Map<String, String> rangeMap = new HashMap<>();
rangeMap = Splitter.on(",").withKeyValueSeparator("=").split(annoation);
for (Entry<String, String> rMap : rangeMap.entrySet()){
if (rMap.getValue().contains("range::")){
@@ -409,16 +404,16 @@ public class PolicyValidationController extends RestrictedBaseController {
int endNum = Integer.parseInt(tempString[1]);
String returnString = "Invalid Range:" + rMap.getKey() + " must be between "
+ startNum + " - " + endNum + ",";
- if (isType(value.replace("\"", ""))){
+ if (isInteger(value.replace("\"", ""))){
int result = Integer.parseInt(value.replace("\"", ""));
if (result < startNum || result > endNum){
- responseString = responseString + returnString;
+ responseString.append(returnString);
valid = false;
}
}else {
- responseString = responseString + returnString;
+ responseString.append(returnString);
valid = false;
}
}
@@ -426,17 +421,17 @@ public class PolicyValidationController extends RestrictedBaseController {
}
//for continue testing for Dkat, just blocked this validation until fixing it. gw1218 on 3/30/17
//if (!checkAttributeValues()){
- //responseString = responseString + "<b>Micro Service</b>:<i> Attribute Values Missing" + "</i><br>";
+ //responseString.append("<b>Micro Service</b>:<i> Attribute Values Missing" + "</i><br>");
//valid = false;
//}
}else{
- responseString = responseString + "<b>Micro Service</b>:<i> Micro Service is required" + "</i><br>";
+ responseString.append("<b>Micro Service</b>:<i> Micro Service is required" + "</i><br>");
valid = false;
}
if(policyData.getPriority() == null){
- responseString = responseString + "<b>Priority</b>:<i> Priority is required" + "</i><br>";
+ responseString.append("<b>Priority</b>:<i> Priority is required" + "</i><br>");
valid = false;
}
}
@@ -445,49 +440,60 @@ public class PolicyValidationController extends RestrictedBaseController {
if(policyData.getEcompName() != null){
String ecompNameValidate = emptyValidator(policyData.getEcompName());
if(!ecompNameValidate.contains("success")){
- responseString = responseString + "EcompName:" + ecompNameValidate + "<br>";
+ responseString.append("EcompName:" + ecompNameValidate + "<br>");
valid = false;
}
}else{
- responseString = responseString + "Ecomp Name: Ecomp Name Should not be empty" + "<br>";
+ responseString.append("Ecomp Name: Ecomp Name Should not be empty" + "<br>");
valid = false;
}
- if(policyData.getRuleProvider().equals("GUARD_YAML")){
+ if("GUARD_YAML".equals(policyData.getRuleProvider()) || "GUARD_BL_YAML".equals(policyData.getRuleProvider())){
if(policyData.getYamlparams()==null){
- responseString = responseString + "<b> Guard Params are Required </b>" + "<br>";
+ responseString.append("<b> Guard Params are Required </b>" + "<br>");
valid = false;
}else{
if(policyData.getYamlparams().getActor()==null){
- responseString = responseString + "Guard Params <b>Actor</b> is Required " + "<br>";
+ responseString.append("Guard Params <b>Actor</b> is Required " + "<br>");
valid = false;
}
if(policyData.getYamlparams().getRecipe()==null){
- responseString = responseString + "Guard Params <b>Recipe</b> is Required " + "<br>";
- valid = false;
- }
- if(policyData.getYamlparams().getLimit()==null){
- responseString = responseString + " Guard Params <b>Limit</b> is Required " + "<br>";
- valid = false;
- }else{
- try{
- Integer.parseInt(policyData.getYamlparams().getLimit());
- }catch(NumberFormatException e){
- responseString = responseString + " Guard Params <b>Limit</b> Should be Integer " + "<br>";
- valid = false;
- }
- }
- if(policyData.getYamlparams().getTimeWindow()==null){
- responseString = responseString + "Guard Params <b>Time Window</b> is Required" + "<br>";
+ responseString.append("Guard Params <b>Recipe</b> is Required " + "<br>");
valid = false;
}
if(policyData.getYamlparams().getGuardActiveStart()==null){
- responseString = responseString + "Guard Params <b>Guard Active Start/b>is Required " + "<br>";
+ responseString.append("Guard Params <b>Guard Active Start/b>is Required " + "<br>");
valid = false;
}
if(policyData.getYamlparams().getGuardActiveEnd()==null){
- responseString = responseString + "Guard Params <b>Guard Active End</b>is Required " + "<br>";
+ responseString.append("Guard Params <b>Guard Active End</b>is Required " + "<br>");
valid = false;
}
+ if("GUARD_YAML".equals(policyData.getRuleProvider())){
+ if(policyData.getYamlparams().getLimit()==null){
+ responseString.append(" Guard Params <b>Limit</b> is Required " + "<br>");
+ valid = false;
+ }else if(!isInteger(policyData.getYamlparams().getLimit())){
+ responseString.append(" Guard Params <b>Limit</b> Should be Integer " + "<br>");
+ valid = false;
+ }
+ if(policyData.getYamlparams().getTimeWindow()==null){
+ responseString.append("Guard Params <b>Time Window</b> is Required" + "<br>");
+ valid = false;
+ }
+ }else if("GUARD_BL_YAML".equals(policyData.getRuleProvider())){
+ if(policyData.getYamlparams().getBlackList()==null || policyData.getYamlparams().getBlackList().isEmpty()){
+ responseString.append(" Guard Params <b>BlackList</b> is Required " + "<br>");
+ valid = false;
+ }else{
+ for(String blackList: policyData.getYamlparams().getBlackList()){
+ if(blackList==null || !("success".equals(emptyValidator(blackList)))){
+ responseString.append(" Guard Params <b>BlackList</b> Should be valid String" + "<br>");
+ valid = false;
+ break;
+ }
+ }
+ }
+ }
}
}
}
@@ -496,49 +502,99 @@ public class PolicyValidationController extends RestrictedBaseController {
if(policyData.getActionPerformer() != null){
String actionPerformer = emptyValidator(policyData.getActionPerformer());
if(!actionPerformer.contains("success")){
- responseString = responseString + "ActionPerformer:" + actionPerformer + "<br>";
+ responseString.append("ActionPerformer:" + actionPerformer + "<br>");
valid = false;
};
}else{
- responseString = responseString + "ActionPerformer: ActionPerformer Should not be empty" + "<br>";
+ responseString.append("ActionPerformer: ActionPerformer Should not be empty" + "<br>");
+ valid = false;
+ }
+ if(policyData.getAttributes() != null){
+ for(Object attribute : policyData.getAttributes()){
+ if(attribute instanceof LinkedHashMap<?, ?>){
+ try{
+ //This is for validation check if the value exists or not
+ String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
+ String value = ((LinkedHashMap<?, ?>) attribute).get("value").toString();
+ if("".equals(key) || "".equals(value)){
+ responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "<br>");
+ valid = false;
+ break;
+ }
+ }catch(Exception e){
+ LOGGER.error("This is a Policy Validation check" +e);
+ responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "<br>");
+ valid = false;
+ break;
+ }
+ }
+ }
+ }else{
+ responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "<br>");
valid = false;
}
if(policyData.getActionAttributeValue() != null){
String actionAttribute = emptyValidator(policyData.getActionAttributeValue());
if(!actionAttribute.contains("success")){
- responseString = responseString + "ActionAttribute:" + actionAttribute + "<br>";
+ responseString.append("ActionAttribute:" + actionAttribute + "<br>");
valid = false;
};
}else{
- responseString = responseString + "ActionAttribute: ActionAttribute Should not be empty" + "<br>";
+ responseString.append("ActionAttribute: ActionAttribute Should not be empty" + "<br>");
valid = false;
}
}
+
+ if(policyData.getPolicyType().equals(ACTION_POLICY) || policyData.getPolicyType().equals(DECISION_POLICY)){
+ if(!policyData.getRuleAlgorithmschoices().isEmpty()){
+ for(Object attribute : policyData.getRuleAlgorithmschoices()){
+ if(attribute instanceof LinkedHashMap<?, ?>){
+ try{
+ String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString();
+ String key = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString();
+ String rule = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString();
+ String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString();
+ if("".equals(label) || "".equals(key) || "".equals(rule) || "".equals(value)){
+ responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "<br>");
+ valid = false;
+ }
+ }catch(Exception e){
+ LOGGER.error("This is a Policy Validation check" +e);
+ responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "<br>");
+ valid = false;
+ break;
+ }
+ }
+ }
+ }
+ }
if(policyData.getPolicyType().equals(CONFIG_POLICY)){
+ String value = "";
if(valid){
List<Object> spData = commonClassDao.getDataById(SafePolicyWarning.class, "riskType", policyData.getRiskType());
if (!spData.isEmpty()){
SafePolicyWarning safePolicyWarningData = (SafePolicyWarning) spData.get(0);
safePolicyWarningData.getMessage();
- responseString = responseString + "Messaage:" + safePolicyWarningData.getMessage();
+ value = "Messaage:" + safePolicyWarningData.getMessage();
}
- responseString = "success" + "@#"+ responseString;
+ responseString.append("success" + "@#"+ value);
}
}else{
if(valid){
- responseString = "success";
+ responseString.append("success");
}
}
PrintWriter out = response.getWriter();
- JsonMessage msg = new JsonMessage(mapper.writeValueAsString(responseString));
+ JsonMessage msg = new JsonMessage(mapper.writeValueAsString(responseString.toString()));
JSONObject j = new JSONObject(msg);
out.write(j.toString());
return null;
}
catch (Exception e){
+ LOGGER.error("Exception Occured while Policy Validation" +e);
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
@@ -547,9 +603,18 @@ public class PolicyValidationController extends RestrictedBaseController {
return null;
}
+ protected boolean isInteger(String number) {
+ try{
+ Integer.parseInt(number);
+ }catch(NumberFormatException e){
+ return false;
+ }
+ return true;
+ }
+
protected String emptyValidator(String field){
- String error = "success";
- if (field.equals("") || field.contains(" ") || !field.matches("^[a-zA-Z0-9_]*$")) {
+ String error;
+ if ("".equals(field) || field.contains(" ") || !field.matches("^[a-zA-Z0-9_]*$")) {
error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
return error;
} else {
@@ -564,7 +629,7 @@ public class PolicyValidationController extends RestrictedBaseController {
}
protected String descriptionValidator(String field) {
- String error = "success";
+ String error;
if (field.contains("@CreatedBy:") || field.contains("@ModifiedBy:")) {
error = "The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:";
return error;
@@ -590,16 +655,16 @@ public class PolicyValidationController extends RestrictedBaseController {
return error;
}
- protected String emailValidation(String email, String responseString){
+ protected String emailValidation(String email, String response){
if(email != null){
String validateEmail = PolicyUtils.validateEmailAddress(email.replace("\"", ""));
if(!validateEmail.contains("success")){
- responseString = responseString + "<b>Email</b>:<i>" + validateEmail+ "</i><br>";
+ response += "<b>Email</b>:<i>" + validateEmail+ "</i><br>";
}else{
return "success";
}
}
- return responseString;
+ return response;
}
private MicroServiceModels getAttributeObject(String name, String version) {
@@ -631,35 +696,16 @@ public class PolicyValidationController extends RestrictedBaseController {
}
}
- private Boolean isType(String testStr) {
- try {
- Integer.parseInt(testStr);
- return true;
- } catch(Exception e) {
- return false;
- }
- }
-
// Validation for json.
protected static boolean isJSONValid(String data) {
- InputStream stream = null;
- JsonReader jsonReader = null;
try {
new JSONObject(data);
- stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
- jsonReader = Json.createReader(stream);
+ InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
+ JsonReader jsonReader = Json.createReader(stream);
+ System.out.println("Json Value is: " + jsonReader.read().toString() );
} catch (Exception e) {
- LOGGER.error("Exception Occured"+e);
+ e.printStackTrace();
return false;
- }finally{
- try {
- if(stream != null && jsonReader != null){
- jsonReader.close();
- stream.close();
- }
- } catch (IOException e) {
- LOGGER.error("Exception Occured while closing the input stream"+e);
- }
}
return true;
}
@@ -689,7 +735,7 @@ public class PolicyValidationController extends RestrictedBaseController {
Scanner scanner = new Scanner(prop);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
- line.replaceAll("\\s+", "");
+ line = line.replaceAll("\\s+", "");
if (line.startsWith("#")) {
continue;
} else {
@@ -709,4 +755,4 @@ public class PolicyValidationController extends RestrictedBaseController {
return true;
}
-}
+} \ No newline at end of file
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/PDPTabWindows/AddorEditPDPtoGroup.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/PDPTabWindows/AddorEditPDPtoGroup.html
index 19e11bfeb..3bfb50fd7 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/PDPTabWindows/AddorEditPDPtoGroup.html
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/PDPTabWindows/AddorEditPDPtoGroup.html
@@ -19,7 +19,7 @@
*/-->
<script type="text/ng-template" id="create_newPDP_InGroup.html">
<div class="modal">
- <div class="modal-dialog-lg">
+ <div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h2 class="font-showcase-font-name" style="color : #157bb2">{{label}}</h2>
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/PushtabWindow/removeGroupPoliciesWindow.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/PushtabWindow/removeGroupPoliciesWindow.html
index 9a880bd52..6ebda43a7 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/PushtabWindow/removeGroupPoliciesWindow.html
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/Windows/PushtabWindow/removeGroupPoliciesWindow.html
@@ -18,7 +18,7 @@
* ============LICENSE_END=========================================================
*/-->
<script type="text/ng-template" id="remove_PDPGroupPolicies_popup.html">
-<div class="modal" style="margin-bottom: 20px; width: 100%" data-backdrop="static"
+<div class="modal" style="margin-bottom: 20px; width: 100%; height:80%" data-backdrop="static"
data-keyboard="false">
<div class="modal-dialog-lg">
<div class="modal-content">
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/BRMSParamDictGridController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/BRMSParamDictGridController.js
index fd49a3a9e..fc0cbc1a6 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/BRMSParamDictGridController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/BRMSParamDictGridController.js
@@ -125,7 +125,7 @@ app.controller('brmsParamDictGridController', function ($scope, PolicyAppService
var i;
if($scope.searchDatas.length > 0){
for(i = 0 ; i < $scope.searchDatas.length; i++){
- searchString += $scope.searchDatas[i].name + "\n";
+ searchString += $scope.searchDatas[i] + "\n";
}
}else{
searchString += "No Policies is Using this Value"
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLPepOptionsDictGridController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLPepOptionsDictGridController.js
index 9ec2a2091..db6d2a7b1 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLPepOptionsDictGridController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLPepOptionsDictGridController.js
@@ -151,7 +151,7 @@ app.controller('pepOptionsDictGridController', function ($scope, PolicyAppServic
var i;
if($scope.searchDatas.length > 0){
for(i = 0 ; i < $scope.searchDatas.length; i++){
- searchString += $scope.searchDatas[i].name + "\n";
+ searchString += $scope.searchDatas[i] + "\n";
}
}else{
searchString += "No Policies is Using this Value"
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLServiceDictGridController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLServiceDictGridController.js
index 099c1e648..b63cec043 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLServiceDictGridController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLServiceDictGridController.js
@@ -126,7 +126,7 @@ app.controller('serviceDictGridController', function ($scope, PolicyAppService,
var i;
if($scope.searchDatas.length > 0){
for(i = 0 ; i < $scope.searchDatas.length; i++){
- searchString += $scope.searchDatas[i].name + "\n";
+ searchString += $scope.searchDatas[i] + "\n";
}
}else{
searchString += "No Policies is Using this Value"
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLSiteDictGridController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLSiteDictGridController.js
index d42674a33..638fd84ad 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLSiteDictGridController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLSiteDictGridController.js
@@ -126,7 +126,7 @@ app.controller('siteDictGridController', function ($scope, PolicyAppService, mod
var i;
if($scope.searchDatas.length > 0){
for(i = 0 ; i < $scope.searchDatas.length; i++){
- searchString += $scope.searchDatas[i].name + "\n";
+ searchString += $scope.searchDatas[i] + "\n";
}
}else{
searchString += "No Policies is Using this Value"
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVarbindDictGridController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVarbindDictGridController.js
index f191da9c7..b2bb51b64 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVarbindDictGridController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVarbindDictGridController.js
@@ -150,7 +150,7 @@ app.controller('varbindDictGridController', function ($scope, PolicyAppService,
var i;
if($scope.searchDatas.length > 0){
for(i = 0 ; i < $scope.searchDatas.length; i++){
- searchString += $scope.searchDatas[i].name + "\n";
+ searchString += $scope.searchDatas[i] + "\n";
}
}else{
searchString += "No Policies is Using this Value"
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVnfTypeDictGridController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVnfTypeDictGridController.js
index 545568f68..bea675588 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVnfTypeDictGridController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVnfTypeDictGridController.js
@@ -149,7 +149,7 @@ app.controller('vnfTypeDictGridController', function ($scope, PolicyAppService,
var i;
if($scope.searchDatas.length > 0){
for(i = 0 ; i < $scope.searchDatas.length; i++){
- searchString += $scope.searchDatas[i].name + "\n";
+ searchString += $scope.searchDatas[i] + "\n";
}
}else{
searchString += "No Policies is Using this Value"
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVsclActionDictGridController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVsclActionDictGridController.js
index 61091523f..512e11464 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVsclActionDictGridController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/controller/dictionaryGridController/CLVsclActionDictGridController.js
@@ -150,7 +150,7 @@ app.controller('vsclActionDictGridController', function ($scope, PolicyAppServic
var i;
if($scope.searchDatas.length > 0){
for(i = 0 ; i < $scope.searchDatas.length; i++){
- searchString += $scope.searchDatas[i].name + "\n";
+ searchString += $scope.searchDatas[i] + "\n";
}
}else{
searchString += "No Policies is Using this Value"
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ActionPolicyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ActionPolicyController.js
index 0bfcd3c01..398b285e6 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ActionPolicyController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/ActionPolicyController.js
@@ -143,6 +143,7 @@ app.controller('actionPolicyController', ['$scope', 'PolicyAppService', 'policyN
if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
$scope.temp.policy.attributes = [];
+ $scope.temp.policy.attributes.push({'id':'choice'+1});
$scope.temp.policy.ruleAlgorithmschoices = [];
}else{
if($scope.temp.policy.attributes.length == 0){
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DCAEMicroServicePolicyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DCAEMicroServicePolicyController.js
index 5e602ae12..fb966430c 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DCAEMicroServicePolicyController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DCAEMicroServicePolicyController.js
@@ -403,9 +403,12 @@ angular.module('abs').controller('dcaeMicroServiceController', ['$scope', '$wind
if(attribute.includes(":")){
enumName = attribute.split(":")[0];
}
- }
+ }
var baseEnum = $scope.dcaeModelData.enumValues;
- var enumList = baseEnum.split(splitEnum);
+ var enumList = [];
+ if(baseEnum != null){
+ enumList = baseEnum.split(splitEnum);
+ }
var enumAttributes;
var patternTest = new RegExp(enumName);
for (k=0; k < enumList.length; k += 1){
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DecisionPolicyController.js b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DecisionPolicyController.js
index ce27e04e0..e7858d7b5 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DecisionPolicyController.js
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplateController/DecisionPolicyController.js
@@ -163,8 +163,14 @@ angular.module('abs').controller('decisionPolicyController', ['$scope', 'PolicyA
if(!$scope.temp.policy.editPolicy && !$scope.temp.policy.readOnly){
$scope.temp.policy.attributes = [];
- $scope.temp.policy.settings = [];
- $scope.temp.policy.ruleAlgorithmschoices = [];
+ $scope.temp.policy.settings = [];
+ $scope.temp.policy.ruleAlgorithmschoices = [];
+ if(!$scope.temp.policy.yamlparams){
+ $scope.temp.policy.yamlparams = {};
+ }
+ if(!$scope.temp.policy.yamlparams.blackList){
+ $scope.temp.policy.yamlparams.blackList = [];
+ }
}else if($scope.temp.policy.ruleProvider=="Custom"){
if($scope.temp.policy.attributes.length == 0){
$scope.temp.policy.attributes = [];
@@ -172,10 +178,14 @@ angular.module('abs').controller('decisionPolicyController', ['$scope', 'PolicyA
if($scope.temp.policy.settings.length == 0){
$scope.temp.policy.settings = [];
}
- if($scope.temp.policy.ruleAlgorithmschoices.length == 0){
+ if($scope.temp.policy.ruleAlgorithmschoices == null || $scope.temp.policy.ruleAlgorithmschoices.length == 0){
$scope.temp.policy.ruleAlgorithmschoices = [];
}
- }
+ }else if($scope.temp.policy.ruleProvider=="GUARD_BL_YAML"){
+ if($scope.temp.policy.yamlparams.blackList.length==0){
+ $scope.temp.policy.yamlparams.blackList = [];
+ }
+ }
$scope.attributeDatas = [{"attributes" : $scope.temp.policy.attributes}];
$scope.addNewChoice = function() {
var newItemNo = $scope.temp.policy.attributes.length+1;
@@ -197,6 +207,14 @@ angular.module('abs').controller('decisionPolicyController', ['$scope', 'PolicyA
$scope.temp.policy.settings.splice(lastItem);
};
+ $scope.addNewBL = function() {
+ $scope.temp.policy.yamlparams.blackList.push('');
+ };
+ $scope.removeBL = function() {
+ var lastItem = $scope.temp.policy.yamlparams.blackList.length-1;
+ $scope.temp.policy.yamlparams.blackList.splice(lastItem);
+ };
+
$scope.ItemNo = 0;
$scope.ruleAlgorithmDatas = [{"ruleAlgorithms" : $scope.temp.policy.ruleAlgorithmschoices }];
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/ActionPolicyTemplate.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/ActionPolicyTemplate.html
index ffb0e972f..e58e7bb62 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/ActionPolicyTemplate.html
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/ActionPolicyTemplate.html
@@ -51,7 +51,7 @@
</div>
</div>
<div class="well">
- <label>Rule Algorithms:<sup><b>*</b></sup></label><br>
+ <label>Rule Algorithms:<sup><b></b></sup></label><br>
<div class="form-group row">
<div class="form-group col-sm-1">
<button type="button" class="btn btn-default"
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/ClosedLoopFaultPolicyTemplate.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/ClosedLoopFaultPolicyTemplate.html
index e831bb40e..fad038ddc 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/ClosedLoopFaultPolicyTemplate.html
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/ClosedLoopFaultPolicyTemplate.html
@@ -301,7 +301,7 @@
</div>
<div class="well">
<div class="form-group row">
- <label>PEP:<sup><b>*</b></sup></label><br>
+ <label>PEP:<sup><b></b></sup></label><br>
<div class="form-group col-sm-3">
<label>PEP Options:<sup><b></b></sup></label><br> <select
class="form-control" ng-disabled="temp.policy.readOnly"
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/DecisionPolicyTemplate.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/DecisionPolicyTemplate.html
index a98dbff1d..637ecff03 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/DecisionPolicyTemplate.html
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/DecisionPolicyTemplate.html
@@ -32,11 +32,90 @@
<option>Custom</option>
<option>AAF</option>
<option>GUARD_YAML</option>
+ <option>GUARD_BL_YAML<option>
</select>
</div>
</div>
</div>
+ <div ng-if="temp.policy.ruleProvider == 'GUARD_BL_YAML'">
+ <div class="well">
+ <div class="form-group row">
+ <div class="form-group col-sm-1">
+ <label>Guard YAML Attributes:</label><br>
+ </div>
+ </div>
+ <div class="form-group row">
+ <div class="form-group row" style="margin-left: 2%">
+ <div class="form-group col-sm-3">
+ <label> actor: </label>
+ </div>
+ <div class="form-group col-sm-3">
+ <input type="text" class="form-control"
+ ng-disabled="temp.policy.readOnly" ng-model="temp.policy.yamlparams.actor"
+ placeholder="Actor" />
+ </div>
+ </div>
+ <div class="form-group row" style="margin-left: 2%">
+ <div class="form-group col-sm-3">
+ <label> recipe: </label>
+ </div>
+ <div class="form-group col-sm-3">
+ <input type="text" class="form-control"
+ ng-disabled="temp.policy.readOnly" ng-model="temp.policy.yamlparams.recipe"
+ placeholder="Recipe" />
+ </div>
+ </div>
+ <div class="form-group row" style="margin-left: 2%">
+ <div class="form-group col-sm-3">
+ <label> guardActiveStart: </label>
+ </div>
+ <div class="form-group col-sm-3">
+ <input type="text" class="form-control"
+ ng-disabled="temp.policy.readOnly" ng-model="temp.policy.yamlparams.guardActiveStart"
+ placeholder="00:00:00-05:00" />
+ </div>
+ </div>
+ <div class="form-group row" style="margin-left: 2%">
+ <div class="form-group col-sm-3">
+ <label> guardActiveEnd: </label>
+ </div>
+ <div class="form-group col-sm-3">
+ <input type="text" class="form-control"
+ ng-disabled="temp.policy.readOnly" ng-model="temp.policy.yamlparams.guardActiveEnd"
+ placeholder="00:00:00-05:00" />
+ </div>
+ </div>
+ <div class="form-group row" style="margin-left: 2%">
+ <div class="form-group col-sm-3">
+ <label> BlackList: </label>
+ <button type="button" class="btn btn-default"
+ ng-disabled="temp.policy.readOnly" ng-click="addNewBL()">
+ <i class="fa fa-plus"></i>
+ </button>
+ </div>
+ <div class="form-group col-sm-4">
+ <div data-ng-repeat="choice in temp.policy.yamlparams.blackList track by $index">
+ <div class="form-group row">
+ <div class="form-group col-sm-9">
+ <input type="text" class="form-control"
+ ng-disabled="temp.policy.readOnly"
+ ng-model="temp.policy.yamlparams.blackList[$index]" placeholder="BlackList" />
+ </div>
+ <div class="form-group col-sm-1">
+ <button type="button" class="btn btn-default" ng-show="$last"
+ ng-disabled="temp.policy.readOnly" ng-click="removeBL()">
+ <i class="fa fa-minus"></i>
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
<div ng-if="temp.policy.ruleProvider == 'GUARD_YAML'">
<div class="well">
<div class="form-group row">
@@ -199,7 +278,7 @@
<div ng-if="temp.policy.ruleProvider == 'Custom'">
<div class="well">
- <label>Decision Rule Algorithms:<sup><b>*</b></sup></label><br>
+ <label>Decision Rule Algorithms:<sup><b></b></sup></label><br>
<div class="form-group row">
<div class="form-group col-sm-1">
<button type="button" class="btn btn-default"
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/PolicyTypeTemplate.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/PolicyTypeTemplate.html
index ada2428ed..acbc4eec5 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/PolicyTypeTemplate.html
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/Editor/PolicyTemplates/PolicyTypeTemplate.html
@@ -25,7 +25,7 @@
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
- <button type="button" class="close" data-dismiss="modal">
+ <button type="button" class="close" data-dismiss="modal" ng-click="refresh();">
<span class="sr-only">{{"close"
| translate}}</span>
</button>
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/policy_AutoPush.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/policy_AutoPush.html
index b53dab32a..776663595 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/policy_AutoPush.html
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/policy_AutoPush.html
@@ -25,9 +25,18 @@
padding: 10px;
}
+/* The Modal (background) */
.modal {
- display: block;
- overflow-y: auto;
+ display: block;
+ position: fixed;
+ z-index: 1;
+ left: 0;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ overflow: auto;
+ background-color: rgb(0,0,0);
+ background-color: rgba(0,0,0,0.4);
}
</style>
<div ng-app id="page-content" style="margin-bottom: 20px; width: 100%">
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/policy_Dictionary.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/policy_Dictionary.html
index db490c400..4e3a9746f 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/policy_Dictionary.html
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/policy_Dictionary.html
@@ -18,21 +18,18 @@
============LICENSE_END=========================================================
-->
<style>
+/* The Modal (background) */
.modal {
- display: block;
-}
-
-.modal {
- overflow-y: auto;
- max-height: 90%;
- margin-top: 5%;
- margin-bottom: 5%;
- margin-left: 10%;
- margin-right: 10%;
-}
-
-.modal-backdrop {
- background-color: red;
+ display: block;
+ position: fixed;
+ z-index: 1;
+ left: 0;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ overflow: auto;
+ background-color: rgb(0,0,0);
+ background-color: rgba(0,0,0,0.4);
}
</style>
<div ng-app id="page-content" style="margin-bottom: 20px; width: 100%">
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/policy_PDPManagement.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/policy_PDPManagement.html
index 1e88e7acb..4c77cf528 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/policy_PDPManagement.html
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/policy_PDPManagement.html
@@ -18,9 +18,18 @@
* ============LICENSE_END=========================================================
*/-->
<style>
+/* The Modal (background) */
.modal {
- display: block;
- overflow-y: auto;
+ display: block;
+ position: fixed;
+ z-index: 1;
+ left: 0;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ overflow: auto;
+ background-color: rgb(0,0,0);
+ background-color: rgba(0,0,0,0.4);
}
</style>
<div id="page-content" style="margin-bottom: 20px; width: 99%">
diff --git a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/policy_Roles.html b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/policy_Roles.html
index 6ca03c963..6df44bc24 100644
--- a/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/policy_Roles.html
+++ b/POLICY-SDK-APP/src/main/webapp/app/policyApp/policy-models/policy_Roles.html
@@ -18,17 +18,18 @@
* ============LICENSE_END=========================================================
*/-->
<style>
+/* The Modal (background) */
.modal {
- display: block;
-}
-
-.modal {
- overflow-y: auto;
- max-height: 90%;
- margin-top: 5%;
- margin-bottom: 5%;
- margin-left: 10%;
- margin-right: 10%;
+ display: block;
+ position: fixed;
+ z-index: 1;
+ left: 0;
+ top: 0;
+ width: 100%;
+ height: 100%;
+ overflow: auto;
+ background-color: rgb(0,0,0);
+ background-color: rgba(0,0,0,0.4);
}
</style>
<div id="page-content" style="margin-bottom: 20px; width: 100%">
diff --git a/PolicyEngineAPI/src/main/java/org/openecomp/policy/api/RuleProvider.java b/PolicyEngineAPI/src/main/java/org/openecomp/policy/api/RuleProvider.java
index 0bd8bd9e8..99f075a30 100644
--- a/PolicyEngineAPI/src/main/java/org/openecomp/policy/api/RuleProvider.java
+++ b/PolicyEngineAPI/src/main/java/org/openecomp/policy/api/RuleProvider.java
@@ -40,7 +40,11 @@ public enum RuleProvider {
/**
* Indicates Guard YAML will be providing the Rule information.
*/
- GUARD_YAML("GUARD_YAML")
+ GUARD_YAML("GUARD_YAML"),
+ /**
+ * Indicates Guard BLACKLIST YAML
+ */
+ GUARD_BL_YAML("GUARD_BL_YAML")
;
private String name;
diff --git a/PolicyEngineAPI/src/main/java/org/openecomp/policy/std/StdPolicyEngine.java b/PolicyEngineAPI/src/main/java/org/openecomp/policy/std/StdPolicyEngine.java
index 2e14676c8..0732c3cf5 100644
--- a/PolicyEngineAPI/src/main/java/org/openecomp/policy/std/StdPolicyEngine.java
+++ b/PolicyEngineAPI/src/main/java/org/openecomp/policy/std/StdPolicyEngine.java
@@ -689,15 +689,13 @@ public class StdPolicyEngine {
LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + pdps.get(0), e);
exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
}
- finally{
- if(result == null){
- Collections.rotate(pdps, -1);
- Collections.rotate(encoding, -1);
- pdpsCount++;
- }else{
- break;
- }
- }
+ if(result == null){
+ Collections.rotate(pdps, -1);
+ Collections.rotate(encoding, -1);
+ pdpsCount++;
+ }else{
+ break;
+ }
}
if(exception != null && exception.getStatusCode()!=null){
if(exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){
diff --git a/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ClosedLoopPolicyClient.java b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ClosedLoopPolicyClient.java
index 4f0926cca..a54030b94 100644
--- a/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ClosedLoopPolicyClient.java
+++ b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ClosedLoopPolicyClient.java
@@ -23,6 +23,7 @@ package org.openecomp.policyEngine;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
+import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.nio.file.Path;
@@ -49,20 +50,26 @@ public class ClosedLoopPolicyClient {
//Builds JSONObject from File
private static JsonObject buildJSON(File jsonInput, String jsonString) throws FileNotFoundException {
JsonObject json = null;;
-
+ JsonReader jsonReader = null;
if (jsonString != null && jsonInput == null) {
StringReader in = null;
in = new StringReader(jsonString);
- JsonReader jsonReader = Json.createReader(in);
+ jsonReader = Json.createReader(in);
json = jsonReader.readObject();
- }
- else {
+ in.close();
+ }else {
InputStream in = null;
in = new FileInputStream(jsonInput);
- JsonReader jsonReader = Json.createReader(in);
+ jsonReader = Json.createReader(in);
json = jsonReader.readObject();
+ try {
+ in.close();
+ } catch (IOException e) {
+ System.err.println("Exception Occured while closing input stream"+e);
+ }
}
-
+ jsonReader.close();
+
return json;
}
public static void main(String[] args) {
@@ -78,10 +85,9 @@ public class ClosedLoopPolicyClient {
// Set up Micro Services Attributes
File jsonFile = null;
String MSjsonString= null;
- if (MSjsonString == null) {
- Path file = Paths.get("C:\\policyAPI\\ClosedLoopJSON\\faultTestJson.json");
- jsonFile = file.toFile();
- }
+ Path file = Paths.get("C:\\policyAPI\\ClosedLoopJSON\\faultTestJson.json");
+ jsonFile = file.toFile();
+
policyParameters.setConfigBody(buildJSON(jsonFile, MSjsonString).toString());
policyParameters.setConfigBodyType(PolicyType.JSON);
diff --git a/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ClosedLoopPolicyPerformanceMetricClient.java b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ClosedLoopPolicyPerformanceMetricClient.java
index 6357cea5a..9564cdefe 100644
--- a/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ClosedLoopPolicyPerformanceMetricClient.java
+++ b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ClosedLoopPolicyPerformanceMetricClient.java
@@ -23,6 +23,7 @@ package org.openecomp.policyEngine;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
+import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.nio.file.Path;
@@ -50,20 +51,26 @@ public class ClosedLoopPolicyPerformanceMetricClient {
//Builds JSONObject from File
private static JsonObject buildJSON(File jsonInput, String jsonString) throws FileNotFoundException {
JsonObject json = null;;
-
+ JsonReader jsonReader = null;
if (jsonString != null && jsonInput == null) {
StringReader in = null;
in = new StringReader(jsonString);
- JsonReader jsonReader = Json.createReader(in);
+ jsonReader = Json.createReader(in);
json = jsonReader.readObject();
+ in.close();
}
else {
InputStream in = null;
in = new FileInputStream(jsonInput);
- JsonReader jsonReader = Json.createReader(in);
+ jsonReader = Json.createReader(in);
json = jsonReader.readObject();
+ try {
+ in.close();
+ } catch (IOException e) {
+ System.err.println("Exception Occured while closing input stream"+e);
+ }
}
-
+ jsonReader.close();
return json;
}
@@ -80,10 +87,9 @@ public class ClosedLoopPolicyPerformanceMetricClient {
// Set up Micro Services Attributes
File jsonFile = null;
String MSjsonString= null;
- if (MSjsonString == null) {
- Path file = Paths.get("C:\\policyAPI\\ClosedLoopJSON\\pmTestJson.json");
- jsonFile = file.toFile();
- }
+ Path file = Paths.get("C:\\policyAPI\\ClosedLoopJSON\\pmTestJson.json");
+ jsonFile = file.toFile();
+
policyParameters.setConfigBody(buildJSON(jsonFile, MSjsonString).toString());
policyParameters.setConfigBodyType(PolicyType.JSON);
diff --git a/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ConfigFirewallPolicyClient.java b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ConfigFirewallPolicyClient.java
index 5c6752bd5..a6b3119f9 100644
--- a/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ConfigFirewallPolicyClient.java
+++ b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ConfigFirewallPolicyClient.java
@@ -23,6 +23,7 @@ package org.openecomp.policyEngine;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
+import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.nio.file.Path;
@@ -65,10 +66,9 @@ public class ConfigFirewallPolicyClient {
policyParameters.setRiskType("PROD");
File jsonFile = null;
String jsonRuleList = null;
- if (jsonRuleList == null) {
- Path file = Paths.get("C:\\policyAPI\\firewallRulesJSON\\Config_FW_1607Rule.json");
- jsonFile = file.toFile();
- }
+ Path file = Paths.get("C:\\policyAPI\\firewallRulesJSON\\Config_FW_1607Rule.json");
+ jsonFile = file.toFile();
+
//buildJSON(jsonFile, jsonRuleList);
policyParameters.setConfigBody(buildJSON(jsonFile, jsonRuleList).toString());
policyParameters.setConfigBodyType(PolicyType.JSON);
@@ -93,24 +93,26 @@ public class ConfigFirewallPolicyClient {
}
private static JsonObject buildJSON(File jsonInput, String jsonString) throws FileNotFoundException {
- JsonObject json = null;;
+ JsonObject json = null;
+ JsonReader jsonReader = null;
if (jsonString != null && jsonInput == null) {
StringReader in = null;
-
in = new StringReader(jsonString);
-
- JsonReader jsonReader = Json.createReader(in);
+ jsonReader = Json.createReader(in);
json = jsonReader.readObject();
-
-
+ in.close();
} else {
InputStream in = null;
in = new FileInputStream(jsonInput);
-
- JsonReader jsonReader = Json.createReader(in);
+ jsonReader = Json.createReader(in);
json = jsonReader.readObject();
+ try {
+ in.close();
+ } catch (IOException e) {
+ System.err.println("Exception Occured while closing input stream"+e);
+ }
}
-
+ jsonReader.close();
return json;
}
diff --git a/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/MicroServicesPolicyClient.java b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/MicroServicesPolicyClient.java
index 4021c9432..4c6756a5b 100644
--- a/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/MicroServicesPolicyClient.java
+++ b/PolicyEngineClient/src/main/java/org/openecomp/policyEngine/MicroServicesPolicyClient.java
@@ -23,6 +23,7 @@ package org.openecomp.policyEngine;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
+import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.nio.file.Path;
@@ -48,20 +49,26 @@ static Boolean isEdit = false;
//Builds JSONObject from File
private static JsonObject buildJSON(File jsonInput, String jsonString) throws FileNotFoundException {
JsonObject json = null;;
-
+ JsonReader jsonReader = null;
if (jsonString != null && jsonInput == null) {
StringReader in = null;
in = new StringReader(jsonString);
- JsonReader jsonReader = Json.createReader(in);
+ jsonReader = Json.createReader(in);
json = jsonReader.readObject();
+ in.close();
}
else {
InputStream in = null;
in = new FileInputStream(jsonInput);
- JsonReader jsonReader = Json.createReader(in);
+ jsonReader = Json.createReader(in);
json = jsonReader.readObject();
+ try {
+ in.close();
+ } catch (IOException e) {
+ System.err.println("Exception Occured while closing input stream"+e);
+ }
}
-
+ jsonReader.close();
return json;
}
public static void main(String[] args) {
@@ -80,10 +87,9 @@ public static void main(String[] args) {
// Set up Micro Services Attributes
File jsonFile = null;
String MSjsonString= null;
- if (MSjsonString == null) {
- Path file = Paths.get("C:\\policyAPI\\MicroServicesJSON\\testStringMatching.json");
- jsonFile = file.toFile();
- }
+ Path file = Paths.get("C:\\policyAPI\\MicroServicesJSON\\testStringMatching.json");
+ jsonFile = file.toFile();
+
policyParameters.setConfigBody(buildJSON(jsonFile, MSjsonString).toString());
policyParameters.setConfigBodyType(PolicyType.JSON);
diff --git a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/PolicyUtils.java b/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/PolicyUtils.java
index 75197932a..dfbefcd73 100644
--- a/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/PolicyUtils.java
+++ b/PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/PolicyUtils.java
@@ -37,9 +37,7 @@ import org.drools.verifier.builder.VerifierBuilder;
import org.drools.verifier.builder.VerifierBuilderFactory;
import org.kie.api.io.ResourceType;
-import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.CharMatcher;
@@ -48,16 +46,21 @@ public class PolicyUtils {
public static final String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
+ private static final String PACKAGE_ERROR = "mismatched input '{' expecting one of the following tokens: '[package";
+ private static final String SUCCESS = "success";
+
+ private PolicyUtils(){
+ // Private Constructor
+ }
public static String objectToJsonString(Object o) throws JsonProcessingException{
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(o);
}
- public static <T> T jsonStringToObject(String jsonString, Class<T> className) throws JsonParseException, JsonMappingException, IOException{
+ public static <T> T jsonStringToObject(String jsonString, Class<T> className) throws IOException{
ObjectMapper mapper = new ObjectMapper();
- T t = mapper.readValue(jsonString, className);
- return t;
+ return mapper.readValue(jsonString, className);
}
public static String decode(String encodedString) throws UnsupportedEncodingException {
@@ -79,18 +82,34 @@ public class PolicyUtils {
String password = tokenizer.nextToken();
return new String[]{username, password};
}else{
- return null;
+ return new String[]{};
}
}
public static String emptyPolicyValidator(String field){
- String error = "success";
- if (field.equals("") || field.contains(" ") || !field.matches("^[a-zA-Z0-9_]*$")) {
+ String error;
+ if ("".equals(field) || field.contains(" ") || !field.matches("^[a-zA-Z0-9_]*$")) {
+ error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
+ return error;
+ } else {
+ if(CharMatcher.ASCII.matchesAllOf((CharSequence) field)){
+ error = SUCCESS;
+ }else{
+ error = "The Value Contains Non ASCII Characters";
+ return error;
+ }
+ }
+ return error;
+ }
+
+ public static String emptyPolicyValidatorWithSpaceAllowed(String field){
+ String error;
+ if ("".equals(field) || !field.matches("^[a-zA-Z0-9_ ]*$")) {
error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations";
return error;
} else {
if(CharMatcher.ASCII.matchesAllOf((CharSequence) field)){
- error = "success";
+ error = SUCCESS;
}else{
error = "The Value Contains Non ASCII Characters";
return error;
@@ -100,19 +119,19 @@ public class PolicyUtils {
}
public static String descriptionValidator(String field) {
- String error = "success";
+ String error;
if (field.contains("@CreatedBy:") || field.contains("@ModifiedBy:")) {
error = "The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:";
return error;
} else {
- error = "success";
+ error = SUCCESS;
}
return error;
}
public static String validateEmailAddress(String emailAddressValue) {
- String error = "success";
- List<String> emailList = Arrays.asList(emailAddressValue.toString().split(","));
+ String error = SUCCESS;
+ List<String> emailList = Arrays.asList(emailAddressValue.split(","));
for(int i =0 ; i < emailList.size() ; i++){
Pattern pattern = Pattern.compile(EMAIL_PATTERN);
Matcher matcher = pattern.matcher(emailList.get(i).trim());
@@ -120,7 +139,7 @@ public class PolicyUtils {
error = "Please check the Following Email Address is not Valid .... " +emailList.get(i).toString();
return error;
}else{
- error = "success";
+ error = SUCCESS;
}
}
return error;
@@ -130,21 +149,28 @@ public class PolicyUtils {
* Check for "[ERR" to see if there are any errors.
*/
public static String brmsRawValidate(String rule){
- VerifierBuilder vBuilder = VerifierBuilderFactory.newVerifierBuilder();
- Verifier verifier = vBuilder.newVerifier();
- verifier.addResourcesToVerify(new ReaderResource(new StringReader(rule)), ResourceType.DRL);
- // Check if there are any Errors in Verification.
- if(verifier.getErrors().size()!=0){
- String message = "Not a Valid DRL rule";
- for(VerifierError error: verifier.getErrors()){
- // Ignore annotations Error Messages
- if(!error.getMessage().contains("'@'")){
- message = message + "\n" + error.getMessage();
- }
- }
- return message;
- }
- return "";
+ VerifierBuilder vBuilder = VerifierBuilderFactory.newVerifierBuilder();
+ Verifier verifier = vBuilder.newVerifier();
+ verifier.addResourcesToVerify(new ReaderResource(new StringReader(rule)), ResourceType.DRL);
+ // Check if there are any Errors in Verification.
+ if(!verifier.getErrors().isEmpty()){
+ boolean ignore = false;
+ StringBuilder message = new StringBuilder("Not a Valid DRL rule");
+ for(VerifierError error: verifier.getErrors()){
+ // Ignore annotations Error Messages
+ if(!error.getMessage().contains("'@'") && !error.getMessage().contains(PACKAGE_ERROR)){
+ ignore= true;
+ message.append("\n" + error.getMessage());
+ }
+ }
+ // Ignore new package names with {
+ // More checks for message to check if its a package error.
+ if(ignore && !message.toString().contains("Parser returned a null Package")){
+ message.append("[ERR 107]");
+ }
+ return message.toString();
+ }
+ return "";
}
/**
diff --git a/PolicyEngineUtils/src/test/java/org/openecomp/policy/test/PolicyUtilsTest.java b/PolicyEngineUtils/src/test/java/org/openecomp/policy/test/PolicyUtilsTest.java
index 7dac55596..42481036f 100644
--- a/PolicyEngineUtils/src/test/java/org/openecomp/policy/test/PolicyUtilsTest.java
+++ b/PolicyEngineUtils/src/test/java/org/openecomp/policy/test/PolicyUtilsTest.java
@@ -40,8 +40,6 @@ public class PolicyUtilsTest {
@Test
public void testJsonConversions() throws Exception{
- @SuppressWarnings("unused")
- PolicyUtils policyUtils = new PolicyUtils();
StdPDPNotification notification = new StdPDPNotification();
notification.setNotificationType(NotificationType.BOTH);
Collection<StdRemovedPolicy> removedPolicies = new ArrayList<>();
diff --git a/packages/base/src/files/install/elk/config/elasticsearch.yml b/packages/base/src/files/install/elk/config/elasticsearch.yml
index 618f2a241..d9e8868bc 100644
--- a/packages/base/src/files/install/elk/config/elasticsearch.yml
+++ b/packages/base/src/files/install/elk/config/elasticsearch.yml
@@ -1,392 +1,90 @@
-##################### Elasticsearch Configuration Example #####################
-
-# This file contains an overview of various configuration settings,
-# targeted at operations staff. Application developers should
-# consult the guide at <http://elasticsearch.org/guide>.
-#
-# The installation procedure is covered at
-# <http://elasticsearch.org/guide/en/elasticsearch/reference/current/setup.html>.
-#
-# Elasticsearch comes with reasonable defaults for most settings,
-# so you can try it out without bothering with configuration.
-#
-# Most of the time, these defaults are just fine for running a production
-# cluster. If you're fine-tuning your cluster, or wondering about the
-# effect of certain configuration option, please _do ask_ on the
-# mailing list or IRC channel [http://elasticsearch.org/community].
-
-# Any element in the configuration can be replaced with environment variables
-# by placing them in ${...} notation. For example:
-#
-#node.rack: ${RACK_ENV_VAR}
-
-# For information on supported formats and syntax for the config file, see
-# <http://elasticsearch.org/guide/en/elasticsearch/reference/current/setup-configuration.html>
-
-
-################################### Cluster ###################################
-
-# Cluster name identifies your cluster for auto-discovery. If you're running
-# multiple clusters on the same network, make sure you're using unique names.
-#
-#cluster.name: elasticsearch
+# ======================== Elasticsearch Configuration =========================
+#
+# NOTE: Elasticsearch comes with reasonable defaults for most settings.
+# Before you set out to tweak and tune the configuration, make sure you
+# understand what are you trying to accomplish and the consequences.
+#
+# The primary way of configuring a node is via this file. This template lists
+# the most important settings you may want to configure for a production cluster.
+#
+# Please consult the documentation for further information on configuration options:
+# https://www.elastic.co/guide/en/elasticsearch/reference/index.html
+#
+# ---------------------------------- Cluster -----------------------------------
+#
+# Use a descriptive name for your cluster:
+#
+#cluster.name: my-application
cluster.name: ${{FQDN}}-policy-sa
-
-
-#################################### Node #####################################
-
-# Node names are generated dynamically on startup, so you're relieved
-# from configuring them manually. You can tie this node to a specific name:
-#
-#node.name: "Franz Kafka"
+#
+# ------------------------------------ Node ------------------------------------
+#
+# Use a descriptive name for the node:
+#
+#node.name: node-1
node.name: "${{FQDN}}"
-
-# Every node can be configured to allow or deny being eligible as the master,
-# and to allow or deny to store the data.
-#
-# Allow this node to be eligible as a master node (enabled by default):
-#
-#node.master: true
-#
-# Allow this node to store data (enabled by default):
-#
-#node.data: true
-
-# You can exploit these settings to design advanced cluster topologies.
-#
-# 1. You want this node to never become a master node, only to hold data.
-# This will be the "workhorse" of your cluster.
-#
-#node.master: false
-#node.data: true
-#
-# 2. You want this node to only serve as a master: to not store any data and
-# to have free resources. This will be the "coordinator" of your cluster.
-#
-#node.master: true
-#node.data: false
-#
-# 3. You want this node to be neither master nor data node, but
-# to act as a "search load balancer" (fetching data from nodes,
-# aggregating results, etc.)
-#
-#node.master: false
-#node.data: false
-
-# Use the Cluster Health API [http://localhost:9200/_cluster/health], the
-# Node Info API [http://localhost:9200/_nodes] or GUI tools
-# such as <http://www.elasticsearch.org/overview/marvel/>,
-# <http://github.com/karmi/elasticsearch-paramedic>,
-# <http://github.com/lukas-vlcek/bigdesk> and
-# <http://mobz.github.com/elasticsearch-head> to inspect the cluster state.
-
-# A node can have generic attributes associated with it, which can later be used
-# for customized shard allocation filtering, or allocation awareness. An attribute
-# is a simple key value pair, similar to node.key: value, here is an example:
-#
-#node.rack: rack314
-
-# By default, multiple nodes are allowed to start from the same installation location
-# to disable it, set the following:
-node.max_local_storage_nodes: 1
-
-
-#################################### Index ####################################
-
-# You can set a number of options (such as shard/replica options, mapping
-# or analyzer definitions, translog settings, ...) for indices globally,
-# in this file.
-#
-# Note, that it makes more sense to configure index settings specifically for
-# a certain index, either when creating it or by using the index templates API.
-#
-# See <http://elasticsearch.org/guide/en/elasticsearch/reference/current/index-modules.html> and
-# <http://elasticsearch.org/guide/en/elasticsearch/reference/current/indices-create-index.html>
-# for more information.
-
-# Set the number of shards (splits) of an index (5 by default):
-#
-#index.number_of_shards: 5
-
-# Set the number of replicas (additional copies) of an index (1 by default):
-#
-#index.number_of_replicas: 1
-
-# Note, that for development on a local machine, with small indices, it usually
-# makes sense to "disable" the distributed features:
-#
-index.number_of_shards: 1
-index.number_of_replicas: 0
-
-# These settings directly affect the performance of index and search operations
-# in your cluster. Assuming you have enough machines to hold shards and
-# replicas, the rule of thumb is:
-#
-# 1. Having more *shards* enhances the _indexing_ performance and allows to
-# _distribute_ a big index across machines.
-# 2. Having more *replicas* enhances the _search_ performance and improves the
-# cluster _availability_.
-#
-# The "number_of_shards" is a one-time setting for an index.
-#
-# The "number_of_replicas" can be increased or decreased anytime,
-# by using the Index Update Settings API.
-#
-# Elasticsearch takes care about load balancing, relocating, gathering the
-# results from nodes, etc. Experiment with different settings to fine-tune
-# your setup.
-
-# Use the Index Status API (<http://localhost:9200/A/_status>) to inspect
-# the index status.
-
-
-#################################### Paths ####################################
-
-# Path to directory containing configuration (this file and logging.yml):
-#
-#path.conf: /path/to/conf
-
-# Path to directory where to store index data allocated for this node.
#
-#path.data: /path/to/data
+# Add custom attributes to the node:
+#
+#node.attr.rack: r1
#
-# Can optionally include more than one location, causing data to be striped across
-# the locations (a la RAID 0) on a file level, favouring locations with most free
-# space on creation. For example:
+# ----------------------------------- Paths ------------------------------------
#
-#path.data: /path/to/data1,/path/to/data2
-
-# Path to temporary files:
+# Path to directory where to store the data (separate multiple locations by comma):
+#
+#path.data: /path/to/data
#
-#path.work: /path/to/work
-
# Path to log files:
#
-#path.logs: /path/to/logs
path.logs: ${{POLICY_HOME}}/logs
-
-# Path to where plugins are installed:
-#
-#path.plugins: /path/to/plugins
-
-
-#################################### Plugin ###################################
-
-# If a plugin listed here is not installed for current node, the node will not start.
-#
-#plugin.mandatory: mapper-attachments,lang-groovy
-
-
-################################### Memory ####################################
-
-# Elasticsearch performs poorly when JVM starts swapping: you should ensure that
-# it _never_ swaps.
-#
-# Set this property to true to lock the memory:
-#
-#bootstrap.mlockall: true
-
-# Make sure that the ES_MIN_MEM and ES_MAX_MEM environment variables are set
-# to the same value, and that the machine has enough memory to allocate
-# for Elasticsearch, leaving enough memory for the operating system itself.
-#
-# You should also make sure that the Elasticsearch process is allowed to lock
-# the memory, eg. by using `ulimit -l unlimited`.
-
-
-############################## Network And HTTP ###############################
-
-# Elasticsearch, by default, binds itself to the 0.0.0.0 address, and listens
-# on port [9200-9300] for HTTP traffic and on port [9300-9400] for node-to-node
-# communication. (the range means that if the port is busy, it will automatically
-# try the next port).
-
-# Set the bind address specifically (IPv4 or IPv6):
-#
-#network.bind_host: 10.00.10.00
-
-# Set the address other nodes will use to communicate with this node. If not
-# set, it is automatically derived. It must point to an actual IP address.
-#
-#network.publish_host: 10.00.10.00
-
-# Set both 'bind_host' and 'publish_host':
-#
-#network.host: 10.00.10.00
-
-# Set a custom port for the node to node communication (9300 by default):
-#
-#transport.tcp.port: 9300
-
-# Enable compression for all communication between nodes (disabled by default):
-#
-#transport.tcp.compress: true
-
-# Set a custom port to listen for HTTP traffic:
+#
+# ----------------------------------- Memory -----------------------------------
+#
+# Lock the memory on startup:
+#
+#bootstrap.memory_lock: true
+#
+# Make sure that the heap size is set to about half the memory available
+# on the system and that the owner of the process is allowed to use this
+# limit.
+#
+# Elasticsearch performs poorly when the system is swapping the memory.
+#
+# ---------------------------------- Network -----------------------------------
+#
+# Set the bind address to a specific IP (IPv4 or IPv6):
+#
+#network.host: 192.168.0.1
+#
+# Set a custom port for HTTP:
#
#http.port: 9200
-
-# Set a custom allowed content length:
-#
-#http.max_content_length: 100mb
-
-# Disable HTTP completely:
-#
-#http.enabled: false
-
-
-################################### Gateway ###################################
-
-# The gateway allows for persisting the cluster state between full cluster
-# restarts. Every change to the state (such as adding an index) will be stored
-# in the gateway, and when the cluster starts up for the first time,
-# it will read its state from the gateway.
-
-# There are several types of gateway implementations. For more information, see
-# <http://elasticsearch.org/guide/en/elasticsearch/reference/current/modules-gateway.html>.
-
-# The default gateway type is the "local" gateway (recommended):
-#
-#gateway.type: local
-
-# Settings below control how and when to start the initial recovery process on
-# a full cluster restart (to reuse as much local data as possible when using shared
-# gateway).
-
-# Allow recovery process after N nodes in a cluster are up:
-#
-#gateway.recover_after_nodes: 1
-
-# Set the timeout to initiate the recovery process, once the N nodes
-# from previous setting are up (accepts time value):
-#
-#gateway.recover_after_time: 5m
-
-# Set how many nodes are expected in this cluster. Once these N nodes
-# are up (and recover_after_nodes is met), begin recovery process immediately
-# (without waiting for recover_after_time to expire):
-#
-#gateway.expected_nodes: 2
-
-
-############################# Recovery Throttling #############################
-
-# These settings allow to control the process of shards allocation between
-# nodes during initial recovery, replica allocation, rebalancing,
-# or when adding and removing nodes.
-
-# Set the number of concurrent recoveries happening on a node:
-#
-# 1. During the initial recovery
-#
-#cluster.routing.allocation.node_initial_primaries_recoveries: 4
-#
-# 2. During adding/removing nodes, rebalancing, etc
-#
-#cluster.routing.allocation.node_concurrent_recoveries: 2
-
-# Set to throttle throughput when recovering (eg. 100mb, by default 20mb):
-#
-#indices.recovery.max_bytes_per_sec: 20mb
-
-# Set to limit the number of open concurrent streams when
-# recovering a shard from a peer:
-#
-#indices.recovery.concurrent_streams: 5
-
-
-################################## Discovery ##################################
-
-# Discovery infrastructure ensures nodes can be found within a cluster
-# and master node is elected. Multicast discovery is the default.
-
-# Set to ensure a node sees N other master eligible nodes to be considered
-# operational within the cluster. This should be set to a quorum/majority of
-# the master-eligible nodes in the cluster.
-#
-#discovery.zen.minimum_master_nodes: 1
-
-# Set the time to wait for ping responses from other nodes when discovering.
-# Set this option to a higher value on a slow or congested network
-# to minimize discovery failures:
-#
-#discovery.zen.ping.timeout: 3s
-
-# For more information, see
-# <http://elasticsearch.org/guide/en/elasticsearch/reference/current/modules-discovery-zen.html>
-
-# Unicast discovery allows to explicitly control which nodes will be used
-# to discover the cluster. It can be used when multicast is not present,
-# or to restrict the cluster communication-wise.
-#
-# 1. Disable multicast discovery (enabled by default):
-#
-#discovery.zen.ping.multicast.enabled: false
-#
-# 2. Configure an initial list of master nodes in the cluster
-# to perform discovery when new nodes (master or data) are started:
-#
-#discovery.zen.ping.unicast.hosts: ["host1", "host2:port"]
-
-# EC2 discovery allows to use AWS EC2 API in order to perform discovery.
-#
-# You have to install the cloud-aws plugin for enabling the EC2 discovery.
-#
-# For more information, see
-# <http://elasticsearch.org/guide/en/elasticsearch/reference/current/modules-discovery-ec2.html>
-#
-# See <http://elasticsearch.org/tutorials/elasticsearch-on-ec2/>
-# for a step-by-step tutorial.
-
-# GCE discovery allows to use Google Compute Engine API in order to perform discovery.
-#
-# You have to install the cloud-gce plugin for enabling the GCE discovery.
-#
-# For more information, see <https://github.com/elasticsearch/elasticsearch-cloud-gce>.
-
-# Azure discovery allows to use Azure API in order to perform discovery.
-#
-# You have to install the cloud-azure plugin for enabling the Azure discovery.
-#
-# For more information, see <https://github.com/elasticsearch/elasticsearch-cloud-azure>.
-
-################################## Slow Log ##################################
-
-# Shard level query and fetch threshold logging.
-
-#index.search.slowlog.threshold.query.warn: 10s
-#index.search.slowlog.threshold.query.info: 5s
-#index.search.slowlog.threshold.query.debug: 2s
-#index.search.slowlog.threshold.query.trace: 500ms
-
-#index.search.slowlog.threshold.fetch.warn: 1s
-#index.search.slowlog.threshold.fetch.info: 800ms
-#index.search.slowlog.threshold.fetch.debug: 500ms
-#index.search.slowlog.threshold.fetch.trace: 200ms
-
-#index.indexing.slowlog.threshold.index.warn: 10s
-#index.indexing.slowlog.threshold.index.info: 5s
-#index.indexing.slowlog.threshold.index.debug: 2s
-#index.indexing.slowlog.threshold.index.trace: 500ms
-
-################################## GC Logging ################################
-
-#monitor.jvm.gc.young.warn: 1000ms
-#monitor.jvm.gc.young.info: 700ms
-#monitor.jvm.gc.young.debug: 400ms
-
-#monitor.jvm.gc.old.warn: 10s
-#monitor.jvm.gc.old.info: 5s
-#monitor.jvm.gc.old.debug: 2s
-
-################################## Security ################################
-
-# Uncomment if you want to enable JSONP as a valid return transport on the
-# http server. With this enabled, it may pose a security risk, so disabling
-# it unless you need it is recommended (it is disabled by default).
-#
-#http.jsonp.enable: true
-
-discovery.zen.ping.multicast.enabled: false
-node.local: true
-action.auto_create_index: false
+#
+# For more information, consult the network module documentation.
+#
+# --------------------------------- Discovery ----------------------------------
+#
+# Pass an initial list of hosts to perform discovery when new node is started:
+# The default list of hosts is ["127.0.0.1", "[::1]"]
+#
+#discovery.zen.ping.unicast.hosts: ["host1", "host2"]
+#
+# Prevent the "split brain" by configuring the majority of nodes (total number of master-eligible nodes / 2 + 1):
+#
+#discovery.zen.minimum_master_nodes: 3
+#
+# For more information, consult the zen discovery module documentation.
+#
+# ---------------------------------- Gateway -----------------------------------
+#
+# Block initial recovery after a full cluster restart until N nodes are started:
+#
+#gateway.recover_after_nodes: 3
+#
+# For more information, consult the gateway module documentation.
+#
+# ---------------------------------- Various -----------------------------------
+#
+# Require explicit names when deleting indices:
+#
+#action.destructive_requires_name: true
diff --git a/packages/base/src/files/install/elk/init.d/elkd b/packages/base/src/files/install/elk/init.d/elkd
index 539b4be3e..7b86904a9 100644
--- a/packages/base/src/files/install/elk/init.d/elkd
+++ b/packages/base/src/files/install/elk/init.d/elkd
@@ -1,7 +1,7 @@
#!/bin/bash
ELK_BASE=${POLICY_HOME}/elk/
-ELK_RUNNING="^$JAVA_HOME/bin/java .* -cp.* org.elasticsearch.bootstrap.Elasticsearch$"
+ELK_RUNNING="^$JAVA_HOME/bin/java .* -cp .* org.elasticsearch.bootstrap.Elasticsearch -d$"
COMPONENT=elk
JMX_JAVA_OPTS="${JMX_JAVA_OPTS} -Dcom.sun.management.jmxremote"
@@ -34,7 +34,7 @@ function stop() {
}
function start() {
- export JAVA_OPTS="${JAVA_OPTS} ${JMX_JAVA_OPTS}"
+ export ES_JAVA_OPTS="${JAVA_OPTS} ${JMX_JAVA_OPTS}"
$POLICY_HOME/elk/bin/elasticsearch -d
RETVAL=$?
if [[ ${RETVAL} != 0 ]]; then
diff --git a/packages/base/src/files/install/mysql/data/161000_upgrade_script.sql b/packages/base/src/files/install/mysql/data/161000_upgrade_script.sql
index 3c3272e0e..d7892c1bf 100755
--- a/packages/base/src/files/install/mysql/data/161000_upgrade_script.sql
+++ b/packages/base/src/files/install/mysql/data/161000_upgrade_script.sql
@@ -6357,7 +6357,7 @@ INSERT INTO `policyentity` VALUES (3156,'doACPolicyPut','2017-03-03 17:26:24',0,
INSERT INTO `configurationdataentity` VALUES (3155,'{\"service\":\"TcaMetrics\",\"location\":\"SampleServiceLocation\",\"uuid\":\"/services/cdap-tca-hi-lo/instances/demo/configuration/metricsPerFunctionalRole/vFirewall\",\"policyName\":\"vFirewall\",\"description\":\"Micro Service vFirewall Demo Policy@CreatedBy:@CreatedBy:@ModifiedBy:@ModifiedBy:\",\"configName\":\"SampleConfigName\",\"templateVersion\":\"OpenSource.version.1\",\"version\":\"1.0.0.5\",\"priority\":\"1\",\"policyScope\":\"resource=SampleResource,service=SampleService,type=SampleType,closedLoopControlName=SampleClosedLoop\",\"content\":{\"thresholds\":[{\"severity\":\"MAJOR\",\"fieldPath\":\"$.event.measurementsForVfScalingFields.vNicUsageArray[*].packetsIn\",\"thresholdValue\":\"300\",\"closedLoopControlName\":\"CL-FRWL-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\",\"version\":\"1.0.2\",\"direction\":\"LESS_OR_EQUAL\"},{\"severity\":\"CRITICAL\",\"fieldPath\":\"$.event.measurementsForVfScalingFields.vNicUsageArray[*].packetsIn\",\"thresholdValue\":\"700\",\"closedLoopControlName\":\"CL-FRWL-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\",\"version\":\"1.0.2\",\"direction\":\"GREATER_OR_EQUAL\"}],\"functionalRole\":\"vFirewall\",\"name\":\"0\"}}\r\n','JSON','com.Config_MS_vFirewall.1.json','doACPolicyPut','2017-03-03 17:26:24',0,'','doACPolicyPut','2017-03-03 17:26:24',1),(3157,'{\"service\":\"TcaMetrics\",\"location\":\"SampleServiceLocation\",\"uuid\":\"/services/cdap-tca-hi-lo/instances/demo/configuration/metricsPerFunctionalRole/vLoadBalancer\",\"policyName\":\"vLoadBalancer\",\"description\":\"Micro Service vLoadBalancer Demo Policy@CreatedBy:@CreatedBy:@ModifiedBy:@ModifiedBy:\",\"configName\":\"SampleConfigName\",\"templateVersion\":\"OpenSource.version.1\",\"version\":\"1.0.0.5\",\"priority\":\"1\",\"policyScope\":\"resource=SampleResource,service=SampleService,type=SampleType,closedLoopControlName=SampleClosedLoop\",\"content\":{\"thresholds\":[{\"severity\":\"MAJOR\",\"fieldPath\":\"$.event.measurementsForVfScalingFields.vNicUsageArray[*].packetsIn\",\"thresholdValue\":\"200\",\"closedLoopControlName\":\"CL-DNS-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\",\"version\":\"1.0.2\",\"direction\":\"GREATER_OR_EQUAL\"}],\"functionalRole\":\"vLoadBalancer\",\"name\":\"0\"}}\r\n','JSON','com.Config_MS_vLoadBalancer.1.json','doACPolicyPut','2017-03-03 17:28:10',0,'','doACPolicyPut','2017-03-03 17:28:10',1);
-INSERT INTO `configurationdataentity` VALUES (3201,'/* Autogenerated Code Please Don\'t change/remove this comment section. This is for the UI purpose. \n <$%BRMSParamTemplate=ControlLoopDemo__closedLoopControlName%$> \n */ \n\r\n\r\n/*-\n * ============LICENSE_START=======================================================\n * archetype-closed-loop-demo-rules\n * ================================================================================\n * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\n * ================================================================================\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * ============LICENSE_END=========================================================\n */\n\npackage org.openecomp.policy.controlloop;\n\nimport java.util.List;\nimport java.util.LinkedList;\nimport java.util.Map;\nimport java.util.HashMap;\nimport java.util.UUID;\n\nimport org.openecomp.policy.controlloop.VirtualControlLoopEvent;\nimport org.openecomp.policy.controlloop.ControlLoopEventStatus;\nimport org.openecomp.policy.controlloop.VirtualControlLoopNotification;\nimport org.openecomp.policy.controlloop.ControlLoopNotificationType;\nimport org.openecomp.policy.controlloop.ControlLoopOperation;\nimport org.openecomp.policy.controlloop.ControlLoopOperationWrapper;\nimport org.openecomp.policy.template.demo.ControlLoopException;\n\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199CloudRegion;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199ExtraProperties;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199ExtraProperty;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199GenericVNF;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199InstanceFilters;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199InventoryResponseItem;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199InventoryResponseItems;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199Manager;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199NamedQuery;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199QueryParameters;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199Request;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199RequestWrapper;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199Response;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199ResponseWrapper;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199ServiceInstance;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199Tenant;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199VfModule;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199VServer;\nimport org.openecomp.policy.aai.util.Serialization;\n\nimport org.openecomp.policy.appc.CommonHeader;\nimport org.openecomp.policy.appc.Request;\nimport org.openecomp.policy.appc.Response;\nimport org.openecomp.policy.appc.ResponseCode;\nimport org.openecomp.policy.appc.ResponseStatus;\nimport org.openecomp.policy.appc.ResponseValue;\n\nimport org.openecomp.policy.template.demo.EventManager;\nimport org.openecomp.policy.vnf.trafficgenerator.PGRequest;\nimport org.openecomp.policy.vnf.trafficgenerator.PGStream;\nimport org.openecomp.policy.vnf.trafficgenerator.PGStreams;\n\nimport org.openecomp.policy.mso.MSOManager;\nimport org.openecomp.policy.mso.MSORequest;\nimport org.openecomp.policy.mso.MSORequestStatus;\nimport org.openecomp.policy.mso.MSORequestDetails;\nimport org.openecomp.policy.mso.MSOModelInfo;\nimport org.openecomp.policy.mso.MSOCloudConfiguration;\nimport org.openecomp.policy.mso.MSORequestInfo;\nimport org.openecomp.policy.mso.MSORequestParameters;\nimport org.openecomp.policy.mso.MSORelatedInstanceListElement;\nimport org.openecomp.policy.mso.MSORelatedInstance;\nimport org.openecomp.policy.mso.MSOResponse;\n\nimport org.openecomp.policy.drools.system.PolicyEngine;\n\n//\n// These parameters are required to build the runtime policy\n//\ndeclare Params\n closedLoopControlName : String\n actor : String\n aaiURL : String\n aaiUsername : String\n aaiPassword : String\n msoURL : String\n msoUsername : String\n msoPassword : String\n aaiNamedQueryUUID : String\n aaiPatternMatch : int \n notificationTopic : String\n appcTopic : String\nend\n\n/*\n*\n* Called once and only once to insert the parameters into working memory for this Closed Loop policy.\n* (Comment SETUP rule out for the first ECOMP opensource release since policy BRMS_GW already puts a Params fact in there)\n*\n*\n*rule \"BRMSParamvFWDemoPolicy.SETUP\"\n* when\n* then\n* System.out.println(\"rule SETUP is triggered.\");\n* Params params = new Params();\n* params.setClosedLoopControlName(\"CL-FRWL-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\");\n* params.setActor(\"APPC\");\n* params.setAaiURL(\"null\");\n* params.setAaiUsername(\"null\");\n* params.setAaiPassword(\"null\");\n* params.setMsoURL(\"null\");\n* params.setMsoUsername(\"null\");\n* params.setMsoPassword(\"null\");\n* params.setAaiNamedQueryUUID(\"null\");\n* params.setAaiPatternMatch(1);\n* params.setNotificationTopic(\"POLICY-CL-MGT\");\n* params.setAppcTopic(\"APPC-CL\");\n* //\n* // This stays in memory as long as the rule is alive and running\n* //\n* insert(params);\n*end\n*/\n/*\n*\n* This rule responds to DCAE Events\n*\n*/\nrule \"BRMSParamvFWDemoPolicy.EVENT\"\n when\n $params : Params( getClosedLoopControlName() == \"CL-FRWL-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )\n not ( EventManager( closedLoopControlName == $event.closedLoopControlName ))\n then\n System.out.println(\"rule EVENT is triggered.\");\n try {\n // \n // Check the requestID in the event to make sure it is not null before we create the EventManager. \n // The EventManager will do extra syntax checking as well check if the closed loop is disabled/\n //\n if ($event.requestID == null) {\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.notification = ControlLoopNotificationType.REJECTED;\n notification.from = \"policy\";\n notification.message = \"Missing requestID from DCAE event\";\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n e.printStackTrace();\n System.out.println(\"Can\'t deliver notification: \" + notification);\n }\n //\n // Retract it from memory\n //\n retract($event);\n System.out.println(\"Event with requestID=null has been retracted.\");\n } else {\n //\n // Create an EventManager\n //\n EventManager manager = new EventManager($params.getClosedLoopControlName(), $event.requestID, $event.target);\n //\n // Determine if EventManager can actively process the event (i.e. syntax)\n //\n VirtualControlLoopNotification notification = manager.activate($event);\n notification.from = \"policy\"; \n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n //\n // Are we actively pursuing this event?\n //\n if (notification.notification == ControlLoopNotificationType.ACTIVE) {\n //\n // Insert Event Manager into memory, this will now kick off processing.\n //\n insert(manager);\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n e.printStackTrace();\n System.out.println(\"Can\'t deliver notification: \" + notification);\n } \n } else {\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n e.printStackTrace();\n System.out.println(\"Can\'t deliver notification: \" + notification);\n }\n //\n // Retract it from memory\n //\n retract($event);\n }\n //\n // Now that the manager is inserted into Drools working memory, we\'ll wait for\n // another rule to fire in order to continue processing. This way we can also\n // then screen for additional ONSET and ABATED events for this same RequestIDs \n // and for different RequestIDs but with the same closedLoopControlName and target.\n //\n }\n //\n } catch (Exception e) {\n e.printStackTrace();\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.notification = ControlLoopNotificationType.REJECTED;\n notification.message = \"Exception occurred \" + e.getMessage();\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n //\n //\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e1) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e1.printStackTrace();\n }\n //\n // Retract the event\n //\n retract($event);\n }\nend\n\n/*\n*\n* This rule happens when we got a valid ONSET, closed loop is enabled and an Event Manager\n* is created. We can start the operations for this closed loop.\n*\n*/\nrule \"BRMSParamvFWDemoPolicy.EVENT.MANAGER\"\n when\n $params : Params( getClosedLoopControlName() == \"CL-FRWL-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )\n $manager : EventManager( closedLoopControlName == $event.closedLoopControlName, controlLoopResult == null)\n then\n System.out.println(\"rule EVENT.MANAGER is triggered.\");\n //\n // Check which event this is.\n //\n EventManager.NEW_EVENT_STATUS eventStatus = $manager.onNewEvent($event);\n //\n // We only want the initial ONSET event in memory,\n // all the other events need to be retracted to support\n // cleanup and avoid the other rules being fired for this event.\n //\n if (eventStatus != EventManager.NEW_EVENT_STATUS.FIRST_ONSET) {\n System.out.println(\"Retracting \"+eventStatus+\" Event.\");\n retract($event);\n return;\n }\n //\n // Now the event in memory is first onset event\n //\n try {\n //\n // Pull the known AAI field from the Event\n //\n // generic-vnf is needed for vFirewall case\n // vserver-name is needed for vLoadBalancer case\n //\n String genericVNF = $event.AAI.get(\"generic-vnf.vnf-id\");\n String vserver = $event.AAI.get(\"vserver.vserver-name\");\n //\n // Check if we are implementing a simple pattern match.\n //\n if ($params.getAaiPatternMatch() == 1) {\n //\n // Yes\n //\n //Basic naming characteristics:\n //VF Name (9 char)+VM name (13 char total)+VFC (19 char total)\n //Example: \n //VF Name (9 characters): cscf0001v\n //VM Name(13 characters): cscf0001vm001\n //VFC name(19 characters): cscf0001vm001cfg001\n //\n // zdfw1fwl01fwl02 or zdfw1fwl01fwl01 \n // replaced with\n // zdfw1fwl01pgn02 or zdfw1fwl01pgn01\n //\n int index = genericVNF.lastIndexOf(\"fwl\");\n if (index == -1) {\n System.err.println(\"The generic-vnf.vnf-id from DCAE Event is not valid.\");\n } else {\n genericVNF = genericVNF.substring(0, index) + \"pgn\" + genericVNF.substring(index+\"fwl\".length());\n }\n //\n // Construct an APPC request\n //\n ControlLoopOperation operation = new ControlLoopOperation();\n operation.actor = $params.getActor();\n operation.operation = \"ModifyConfig\";\n operation.target = $event.target;\n //\n // Create operationWrapper\n //\n ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation);\n //\n // insert operationWrapper into memory\n //\n insert(operationWrapper);\n //\n Request request = new Request();\n request.CommonHeader = new CommonHeader();\n request.CommonHeader.RequestID = $event.requestID;\n request.Action = operation.operation;\n request.Payload = new HashMap<String, Object>();\n //\n // Fill in the payload\n //\n request.Payload.put(\"generic-vnf.vnf-id\", genericVNF);\n //\n PGRequest pgRequest = new PGRequest();\n pgRequest.pgStreams = new PGStreams();\n \n PGStream pgStream;\n for(int i = 0; i < 5; i++){\n pgStream = new PGStream();\n pgStream.streamId = \"fw_udp\"+(i+1);\n pgStream.isEnabled = \"true\";\n pgRequest.pgStreams.pgStream.add(pgStream);\n }\n request.Payload.put(\"pg-streams\", pgRequest.pgStreams);\n \n if (request != null) {\n //\n // Insert request into memory\n //\n insert(request);\n //\n // Tell interested parties we are performing this Operation\n //\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.notification = ControlLoopNotificationType.OPERATION;\n // message and history ??\n notification.from = \"policy\";\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // Now send the operation request\n //\n if (request instanceof Request) {\n try {\n System.out.println(\"APPC request sent:\");\n System.out.println(Serialization.gsonPretty.toJson(request));\n PolicyEngine.manager.deliver($params.getAppcTopic(), request);\n } catch (Exception e) {\n e.printStackTrace();\n System.out.println(\"Can\'t deliver request: \" + request);\n }\n }\n } else {\n //\n // what happens if it is null\n //\n }\n //\n } else {\n //\n // create AAI named-query request with UUID started with \"F199\"\n //\n AAINQF199Request aainqf199request = new AAINQF199Request();\n AAINQF199QueryParameters aainqf199queryparam = new AAINQF199QueryParameters();\n AAINQF199NamedQuery aainqf199namedquery = new AAINQF199NamedQuery();\n AAINQF199InstanceFilters aainqf199instancefilter = new AAINQF199InstanceFilters();\n //\n // queryParameters\n //\n aainqf199namedquery.namedQueryUUID = UUID.fromString($params.getAaiNamedQueryUUID()); \n aainqf199queryparam.namedQuery = aainqf199namedquery;\n aainqf199request.queryParameters = aainqf199queryparam;\n //\n // instanceFilters\n //\n Map aainqf199instancefiltermap = new HashMap();\n Map aainqf199instancefiltermapitem = new HashMap();\n aainqf199instancefiltermapitem.put(\"vserver-name\", vserver); \n aainqf199instancefiltermap.put(\"vserver\", aainqf199instancefiltermapitem);\n aainqf199instancefilter.instanceFilter.add(aainqf199instancefiltermap);\n aainqf199request.instanceFilters = aainqf199instancefilter;\n //\n // print aainqf199request for debug\n //\n System.out.println(\"AAI Request sent:\");\n System.out.println(Serialization.gsonPretty.toJson(aainqf199request));\n //\n // Create AAINQF199RequestWrapper\n //\n AAINQF199RequestWrapper aainqf199RequestWrapper = new AAINQF199RequestWrapper($event.requestID, aainqf199request);\n //\n // insert aainqf199request into memory\n //\n insert(aainqf199RequestWrapper);\n }\n //\n } catch (Exception e) {\n e.printStackTrace();\n }\nend\n\n/*\n*\n* This rule happens when we got a valid ONSET, closed loop is enabled, an Event Manager\n* is created, AAI Manager and AAI Request are ready in memory. We can start sending query to AAI and then wait for response.\n*\n*/\nrule \"BRMSParamvFWDemoPolicy.EVENT.MANAGER.AAINQF199REQUEST\"\n when\n $params : Params( getClosedLoopControlName() == \"CL-FRWL-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )\n $manager : EventManager( closedLoopControlName == $event.closedLoopControlName )\n $aainqf199RequestWrapper : AAINQF199RequestWrapper(requestID == $event.requestID)\n then\n System.out.println(\"rule EVENT.MANAGER.AAINQF199REQUEST is triggered.\");\n //\n // send the request\n //\n AAINQF199Response aainqf199response = AAINQF199Manager.postQuery($params.getAaiURL(), $params.getAaiUsername(), $params.getAaiPassword(),\n $aainqf199RequestWrapper.aainqf199request, $event.requestID);\n //\n // Check AAI response\n //\n if (aainqf199response == null) {\n System.err.println(\"Failed to get AAI response\");\n //\n // Fail and retract everything\n //\n retract($event);\n retract($manager);\n retract($aainqf199RequestWrapper);\n } else {\n //\n // Create AAINQF199ResponseWrapper\n //\n AAINQF199ResponseWrapper aainqf199ResponseWrapper = new AAINQF199ResponseWrapper($event.requestID, aainqf199response);\n //\n // insert aainqf199ResponseWrapper to memeory\n //\n insert(aainqf199ResponseWrapper);\n }\nend\n\n/*\n*\n* This rule happens when we got a valid AAI response. We can start sending request to APPC or MSO now.\n*\n*/\nrule \"BRMSParamvFWDemoPolicy.EVENT.MANAGER.AAINQF199RESPONSE\"\n when \n $params : Params( getClosedLoopControlName() == \"CL-FRWL-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )\n $manager : EventManager( closedLoopControlName == $event.closedLoopControlName )\n $aainqf199RequestWrapper : AAINQF199RequestWrapper(requestID == $event.requestID)\n $aainqf199ResponseWrapper : AAINQF199ResponseWrapper(requestID == $event.requestID)\n then\n System.out.println(\"rule EVENT.MANAGER.AAINQF199RESPONSE is triggered.\");\n //\n // Extract related fields out of AAINQF199RESPONSE\n //\n String vnfItemVnfId, vnfItemVnfType, vnfItemPersonaModelId, vnfItemPersonaModelVersion, vnfItemModelName, \n vnfItemModelVersion, vnfItemModelNameVersionId, serviceItemServiceInstanceId, serviceItemPersonaModelId,\n serviceItemModelName, serviceItemModelType, serviceItemModelVersion, serviceItemModelNameVersionId,\n vfModuleItemVfModuleName, vfModuleItemPersonaModelId, vfModuleItemPersonaModelVersion, vfModuleItemModelName, \n vfModuleItemModelNameVersionId, tenantItemTenantId, cloudRegionItemCloudRegionId;\n try {\n //\n // vnfItem\n //\n vnfItemVnfId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.vnfID;\n vnfItemVnfType = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.vnfType;\n vnfItemVnfType = vnfItemVnfType.substring(vnfItemVnfType.lastIndexOf(\"/\")+1);\n vnfItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.personaModelId;\n vnfItemPersonaModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.personaModelVersion;\n vnfItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(0).propertyValue;\n vnfItemModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(2).propertyValue;\n vnfItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(4).propertyValue;\n //\n // serviceItem\n //\n serviceItemServiceInstanceId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.serviceInstanceID;\n serviceItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.personaModelId;\n serviceItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(0).propertyValue;\n serviceItemModelType = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(1).propertyValue;\n serviceItemModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.personaModelVersion;\n serviceItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(4).propertyValue;\n //\n // Find the index for base vf module and non-base vf module\n //\n int baseIndex = -1;\n int nonBaseIndex = -1;\n List<AAINQF199InventoryResponseItem> inventoryItems = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems;\n for (AAINQF199InventoryResponseItem m : inventoryItems) {\n if (m.vfModule != null && m.vfModule.isBaseVfModule == true) {\n baseIndex = inventoryItems.indexOf(m);\n } else if (m.vfModule != null && m.vfModule.isBaseVfModule == false && m.vfModule.orchestrationStatus == null) {\n nonBaseIndex = inventoryItems.indexOf(m);\n }\n //\n if (baseIndex != -1 && nonBaseIndex != -1) {\n break;\n }\n }\n //\n // Report the error if either base vf module or non-base vf module is not found\n //\n if (baseIndex == -1 || nonBaseIndex == -1) {\n System.err.println(\"Either base or non-base vf module is not found from AAI response.\");\n retract($aainqf199RequestWrapper);\n retract($aainqf199ResponseWrapper);\n retract($manager);\n retract($event);\n return;\n }\n //\n // This comes from the base module\n //\n vfModuleItemVfModuleName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(baseIndex).vfModule.vfModuleName;\n vfModuleItemVfModuleName = vfModuleItemVfModuleName.replace(\"Vfmodule\", \"vDNS\");\n //\n // vfModuleItem - NOT the base module\n //\n vfModuleItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).vfModule.personaModelId;\n vfModuleItemPersonaModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).vfModule.personaModelVersion;\n vfModuleItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).extraProperties.extraProperty.get(0).propertyValue;\n vfModuleItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).extraProperties.extraProperty.get(4).propertyValue;\n //\n // tenantItem\n //\n tenantItemTenantId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(1).tenant.tenantId;\n //\n // cloudRegionItem\n //\n cloudRegionItemCloudRegionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(1).items.inventoryResponseItems.get(0).cloudRegion.cloudRegionId;\n //\n } catch (Exception e) {\n e.printStackTrace();\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.notification = ControlLoopNotificationType.REJECTED;\n notification.message = \"Exception occurred \" + e.getMessage();\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e1) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e1.printStackTrace();\n }\n //\n notification.notification = ControlLoopNotificationType.FINAL_FAILURE;\n notification.message = \"Invalid named-query response from AAI\";\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e1) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e1.printStackTrace();\n }\n //\n // Retract everything\n //\n retract($aainqf199RequestWrapper);\n retract($aainqf199ResponseWrapper);\n retract($manager);\n retract($event);\n return;\n } \n //\n // Extracted fields should not be null\n //\n if ((vnfItemVnfId == null) || (vnfItemVnfType == null) ||\n (vnfItemPersonaModelId == null) || (vnfItemModelName == null) ||\n (vnfItemModelVersion == null) || (vnfItemModelNameVersionId == null) ||\n (serviceItemServiceInstanceId == null) || (serviceItemModelName == null) ||\n (serviceItemModelType == null) || (serviceItemModelVersion == null) ||\n (serviceItemModelNameVersionId == null) || (vfModuleItemVfModuleName == null) ||\n (vfModuleItemPersonaModelId == null) || (vfModuleItemPersonaModelVersion == null) ||\n (vfModuleItemModelName == null) || (vfModuleItemModelNameVersionId == null) ||\n (tenantItemTenantId == null) || (cloudRegionItemCloudRegionId == null)) {\n //\n System.err.println(\"some fields are missing from AAI response.\");\n //\n // Fail and retract everything\n //\n retract($aainqf199RequestWrapper);\n retract($aainqf199ResponseWrapper);\n retract($manager);\n retract($event);\n return;\n }\n //\n // We don\'t need them any more\n //\n retract($aainqf199ResponseWrapper);\n retract($aainqf199RequestWrapper); \n //\n // check the actor of this closed loop\n //\n switch ($params.getActor()) {\n case \"APPC\":\n {\n //\n // Construct an APPC request\n //\n ControlLoopOperation operation = new ControlLoopOperation();\n operation.actor = $params.getActor();\n operation.operation = \"ModifyConfig\";\n operation.target = $event.target;\n //\n // Create operationWrapper\n //\n ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation);\n //\n // insert operationWrapper into memory\n //\n insert(operationWrapper);\n //\n Request request = new Request();\n request.CommonHeader = new CommonHeader();\n request.CommonHeader.RequestID = $event.requestID;\n request.Action = operation.operation;\n request.Payload = new HashMap<String, Object>();\n //\n // Fill in the payload\n // Hardcode genericVNF for now since AAI has not been ready for vFirewall demo case\n //\n String genericVNF = \"zdfw1fwl01pgn02\";\n request.Payload.put(\"generic-vnf.vnf-id\", genericVNF);\n //\n PGRequest pgRequest = new PGRequest();\n pgRequest.pgStreams = new PGStreams();\n \n PGStream pgStream;\n for(int i = 0; i < 5; i++){\n pgStream = new PGStream();\n pgStream.streamId = \"fw_udp\"+(i+1);\n pgStream.isEnabled = \"true\";\n pgRequest.pgStreams.pgStream.add(pgStream);\n }\n request.Payload.put(\"pg-streams\", pgRequest.pgStreams);\n \n if (request != null) {\n //\n // Insert request into memory\n //\n insert(request);\n //\n // Tell interested parties we are performing this Operation\n //\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.notification = ControlLoopNotificationType.OPERATION;\n // message and history ??\n notification.from = \"policy\";\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // Now send the operation request\n //\n if (request instanceof Request) {\n try {\n System.out.println(\"APPC request sent:\");\n System.out.println(Serialization.gsonPretty.toJson(request));\n PolicyEngine.manager.deliver($params.getAppcTopic(), request);\n } catch (Exception e) {\n e.printStackTrace();\n System.out.println(\"Can\'t deliver request: \" + request);\n }\n }\n } else {\n //\n // what happens if it is null\n //\n }\n }\n break;\n case \"MSO\":\n {\n //\n // Construct an operation\n //\n ControlLoopOperation operation = new ControlLoopOperation();\n operation.actor = $params.getActor();\n operation.operation = \"createModuleInstance\";\n operation.target = $event.target;\n //\n // Create operationWrapper\n //\n ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation);\n //\n // Construct an MSO request\n //\n MSORequest request = new MSORequest();\n request.requestDetails = new MSORequestDetails();\n request.requestDetails.modelInfo = new MSOModelInfo();\n request.requestDetails.cloudConfiguration = new MSOCloudConfiguration();\n request.requestDetails.requestInfo = new MSORequestInfo();\n request.requestDetails.requestParameters = new MSORequestParameters();\n request.requestDetails.requestParameters.userParams = null;\n //\n // cloudConfiguration\n //\n request.requestDetails.cloudConfiguration.lcpCloudRegionId = cloudRegionItemCloudRegionId;\n request.requestDetails.cloudConfiguration.tenantId = tenantItemTenantId;\n //\n // modelInfo\n //\n request.requestDetails.modelInfo.modelType = \"vfModule\";\n request.requestDetails.modelInfo.modelInvariantId = vfModuleItemPersonaModelId;\n request.requestDetails.modelInfo.modelNameVersionId = vfModuleItemModelNameVersionId;\n request.requestDetails.modelInfo.modelName = vfModuleItemModelName;\n request.requestDetails.modelInfo.modelVersion = vfModuleItemPersonaModelVersion;\n //\n // requestInfo\n //\n request.requestDetails.requestInfo.instanceName = vfModuleItemVfModuleName;\n request.requestDetails.requestInfo.source = \"POLICY\";\n request.requestDetails.requestInfo.suppressRollback = false;\n //\n // relatedInstanceList\n //\n MSORelatedInstanceListElement relatedInstanceListElement1 = new MSORelatedInstanceListElement();\n MSORelatedInstanceListElement relatedInstanceListElement2 = new MSORelatedInstanceListElement();\n relatedInstanceListElement1.relatedInstance = new MSORelatedInstance();\n relatedInstanceListElement2.relatedInstance = new MSORelatedInstance();\n //\n relatedInstanceListElement1.relatedInstance.instanceId = serviceItemServiceInstanceId;\n relatedInstanceListElement1.relatedInstance.modelInfo = new MSOModelInfo();\n relatedInstanceListElement1.relatedInstance.modelInfo.modelType = \"service\";\n relatedInstanceListElement1.relatedInstance.modelInfo.modelInvariantId = serviceItemPersonaModelId;\n relatedInstanceListElement1.relatedInstance.modelInfo.modelNameVersionId = serviceItemModelNameVersionId;\n relatedInstanceListElement1.relatedInstance.modelInfo.modelName = serviceItemModelName;\n relatedInstanceListElement1.relatedInstance.modelInfo.modelVersion = serviceItemModelVersion;\n //\n relatedInstanceListElement2.relatedInstance.instanceId = vnfItemVnfId;\n relatedInstanceListElement2.relatedInstance.modelInfo = new MSOModelInfo();\n relatedInstanceListElement2.relatedInstance.modelInfo.modelType = \"vnf\";\n relatedInstanceListElement2.relatedInstance.modelInfo.modelInvariantId = vnfItemPersonaModelId;\n relatedInstanceListElement2.relatedInstance.modelInfo.modelNameVersionId = vnfItemModelNameVersionId;\n relatedInstanceListElement2.relatedInstance.modelInfo.modelName = vnfItemModelName;\n relatedInstanceListElement2.relatedInstance.modelInfo.modelVersion = vnfItemModelVersion;\n relatedInstanceListElement2.relatedInstance.modelInfo.modelCustomizationName = vnfItemVnfType;\n // \n request.requestDetails.relatedInstanceList.add(relatedInstanceListElement1);\n request.requestDetails.relatedInstanceList.add(relatedInstanceListElement2);\n //\n // print MSO request for debug\n //\n System.out.println(\"MSO request sent:\");\n System.out.println(Serialization.gsonPretty.toJson(request));\n //\n //\n //\n if (request != null) {\n //\n // Tell interested parties we are performing this Operation\n //\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.notification = ControlLoopNotificationType.OPERATION;\n notification.from = \"policy\";\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // Concatenate serviceItemServiceInstanceId and vnfItemVnfId to msoURL\n //\n String MSOUrl = $params.getMsoURL() + \"/serviceInstances/v2/\" + serviceItemServiceInstanceId + \"/vnfs/\" + vnfItemVnfId + \"/vfModules\";\n //\n // Call MSO\n //\n MSOResponse response = MSOManager.createModuleInstance(MSOUrl, $params.getMsoURL(), $params.getMsoUsername(), $params.getMsoPassword(), request);\n //\n if (response != null) {\n //\n // Assign requestId\n //\n request.requestId = $event.requestID.toString(); \n response.request.requestId = $event.requestID.toString();\n //\n // Insert facts\n //\n insert(operationWrapper);\n insert(request);\n insert(response);\n } else {\n //\n // MSO request not even accepted\n //\n notification.message = operationWrapper.operation.toMessage();\n operationWrapper.operation.message = operationWrapper.operation.toMessage();\n operationWrapper.operation.outcome = \"FAILURE_EXCEPTION\";\n $manager.setControlLoopResult(\"FAILURE_EXCEPTION\");\n notification.history.add(operationWrapper.operation);\n notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n notification.notification = ControlLoopNotificationType.FINAL_FAILURE;\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // Retract everything\n //\n retract($event);\n retract($manager);\n }\n } else {\n System.err.println(\"constructed MSO request is invalid.\");\n }\n }\n break; \n } \nend\n \n/*\n*\n* This rule responds to APPC Response Events\n*\n*/\nrule \"BRMSParamvFWDemoPolicy.APPC.RESPONSE\"\n when\n $params : Params( getClosedLoopControlName() == \"CL-FRWL-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )\n $manager : EventManager( closedLoopControlName == $event.closedLoopControlName )\n $operationWrapper : ControlLoopOperationWrapper( requestID == $event.requestID )\n $request : Request( getCommonHeader().RequestID == $event.requestID )\n $response : Response( getCommonHeader().RequestID == $event.requestID ) \n then\n System.out.println(\"rule APPC.RESPONSE is triggered.\");\n if ($response.Status == null) {\n $operationWrapper.operation.outcome = \"FAILURE_EXCEPTION\";\n $manager.setControlLoopResult(\"FAILURE_EXCEPTION\");\n } \n //\n // Get the Response Code\n //\n ResponseCode code = ResponseCode.toResponseCode($response.Status.Code);\n if (code == null) {\n $operationWrapper.operation.outcome = \"FAILURE_EXCEPTION\";\n $manager.setControlLoopResult(\"FAILURE_EXCEPTION\");\n }\n //\n // Construct notification\n //\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.from = \"policy\";\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n notification.message = $operationWrapper.operation.toMessage();\n $operationWrapper.operation.message = $operationWrapper.operation.toMessage();\n //\n // Ok, let\'s figure out what APP-C\'s response is\n //\n switch (code) {\n case ACCEPT:\n $operationWrapper.operation.outcome = \"PROCESSING\";\n break;\n case ERROR:\n case REJECT:\n $operationWrapper.operation.outcome = \"FAILURE_EXCEPTION\";\n $manager.setControlLoopResult(\"FAILURE_EXCEPTION\");\n break;\n case SUCCESS:\n $operationWrapper.operation.outcome = \"SUCCESS\";\n $manager.setControlLoopResult(\"SUCCESS\");\n break;\n case FAILURE:\n $operationWrapper.operation.outcome = \"FAILURE\";\n $manager.setControlLoopResult(\"FAILURE\");\n break;\n }\n if ($operationWrapper.operation.outcome.equals(\"SUCCESS\")) {\n notification.history.add($operationWrapper.operation);\n notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n notification.notification = ControlLoopNotificationType.FINAL_SUCCESS;\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n\n //\n // We are going to retract these objects from memory\n //\n System.out.println(\"Retracting everything\");\n retract($operationWrapper);\n retract($request);\n retract($response);\n retract($event);\n retract($manager);\n } else if ($operationWrapper.operation.outcome.equals(\"PROCESSING\")) {\n retract($response);\n } else {\n notification.history.add($operationWrapper.operation);\n notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n notification.notification = ControlLoopNotificationType.FINAL_FAILURE;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // We are going to retract these objects from memory\n //\n System.out.println(\"Retracting everything\");\n retract($operationWrapper);\n retract($request);\n retract($response);\n retract($event);\n retract($manager);\n }\n \nend \n\n/*\n*\n* This rule is used to clean up APPC response\n*\n*/ \nrule \"BRMSParamvFWDemoPolicy.APPC.RESPONSE.CLEANUP\"\n when\n $params : Params( getClosedLoopControlName() == \"CL-FRWL-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $response : Response($id : getCommonHeader().RequestID )\n not ( VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), requestID == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) ) \n then\n System.out.println(\"rule APPC.RESPONSE.CLEANUP is triggered.\");\n retract($response);\nend\n\n/*\n*\n* This rule responds to MSO Response Events\n*\n*/\nrule \"BRMSParamvFWDemoPolicy.MSO.RESPONSE\"\n when\n $params : Params( getClosedLoopControlName() == \"CL-FRWL-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )\n $manager : EventManager( closedLoopControlName == $event.closedLoopControlName )\n $operationWrapper : ControlLoopOperationWrapper( requestID == $event.requestID )\n $request : MSORequest( requestId == $event.requestID.toString() )\n $response : MSOResponse( request.requestId == $event.requestID.toString() ) \n then\n System.out.println(\"rule MSO.RESPONSE is triggered.\");\n //\n // Construct notification\n //\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.from = \"policy\";\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n notification.message = $operationWrapper.operation.toMessage();\n $operationWrapper.operation.message = $operationWrapper.operation.toMessage();\n //\n // The operation can either be succeeded or failed\n // \n if($response.request.requestStatus.requestState.equals(\"COMPLETE\")) {\n $operationWrapper.operation.outcome = \"SUCCESS\";\n $manager.setControlLoopResult(\"SUCCESS\");\n notification.history.add($operationWrapper.operation);\n notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n notification.notification = ControlLoopNotificationType.FINAL_SUCCESS;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // We are going to retract these objects from memory\n //\n System.out.println(\"Retracting everything\");\n retract($operationWrapper);\n retract($request);\n retract($response);\n retract($event);\n retract($manager);\n } else {\n $operationWrapper.operation.outcome = \"FAILURE\";\n $manager.setControlLoopResult(\"FAILURE\");\n notification.history.add($operationWrapper.operation);\n notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n notification.notification = ControlLoopNotificationType.FINAL_FAILURE;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // We are going to retract these objects from memory\n //\n System.out.println(\"Retracting everything\");\n retract($operationWrapper);\n retract($request);\n retract($response);\n retract($event);\n retract($manager);\n }\n \nend \nrule \"Params\" \n salience 1000 \n when\n then\n Params params = new Params();\n params.setAaiPatternMatch(1);\n params.setAppcTopic(\"APPC-CL\");\n params.setAaiURL(\"null\");\n params.setMsoPassword(\"null\");\n params.setClosedLoopControlName(\"CL-FRWL-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\");\n params.setMsoURL(\"null\");\n params.setAaiUsername(\"null\");\n params.setActor(\"APPC\");\n params.setMsoUsername(\"null\");\n params.setAaiNamedQueryUUID(\"null\");\n params.setAaiPassword(\"null\");\n params.setNotificationTopic(\"POLICY-CL-MGT\");\n insert(params);\nend\r\n','OTHER','com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt','doACPolicyPut','2017-03-14 19:58:19',0,'','doACPolicyPut','2017-03-14 19:58:19',1),(3203,'/* Autogenerated Code Please Don\'t change/remove this comment section. This is for the UI purpose. \n <$%BRMSParamTemplate=ControlLoopDemo__closedLoopControlName%$> \n */ \n\r\n\r\n/*-\n * ============LICENSE_START=======================================================\n * archetype-closed-loop-demo-rules\n * ================================================================================\n * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\n * ================================================================================\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * ============LICENSE_END=========================================================\n */\n\npackage org.openecomp.policy.controlloop;\n\nimport java.util.List;\nimport java.util.LinkedList;\nimport java.util.Map;\nimport java.util.HashMap;\nimport java.util.UUID;\n\nimport org.openecomp.policy.controlloop.VirtualControlLoopEvent;\nimport org.openecomp.policy.controlloop.ControlLoopEventStatus;\nimport org.openecomp.policy.controlloop.VirtualControlLoopNotification;\nimport org.openecomp.policy.controlloop.ControlLoopNotificationType;\nimport org.openecomp.policy.controlloop.ControlLoopOperation;\nimport org.openecomp.policy.controlloop.ControlLoopOperationWrapper;\nimport org.openecomp.policy.template.demo.ControlLoopException;\n\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199CloudRegion;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199ExtraProperties;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199ExtraProperty;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199GenericVNF;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199InstanceFilters;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199InventoryResponseItem;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199InventoryResponseItems;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199Manager;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199NamedQuery;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199QueryParameters;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199Request;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199RequestWrapper;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199Response;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199ResponseWrapper;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199ServiceInstance;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199Tenant;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199VfModule;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199VServer;\nimport org.openecomp.policy.aai.util.Serialization;\n\nimport org.openecomp.policy.appc.CommonHeader;\nimport org.openecomp.policy.appc.Request;\nimport org.openecomp.policy.appc.Response;\nimport org.openecomp.policy.appc.ResponseCode;\nimport org.openecomp.policy.appc.ResponseStatus;\nimport org.openecomp.policy.appc.ResponseValue;\n\nimport org.openecomp.policy.template.demo.EventManager;\nimport org.openecomp.policy.vnf.trafficgenerator.PGRequest;\nimport org.openecomp.policy.vnf.trafficgenerator.PGStream;\nimport org.openecomp.policy.vnf.trafficgenerator.PGStreams;\n\nimport org.openecomp.policy.mso.MSOManager;\nimport org.openecomp.policy.mso.MSORequest;\nimport org.openecomp.policy.mso.MSORequestStatus;\nimport org.openecomp.policy.mso.MSORequestDetails;\nimport org.openecomp.policy.mso.MSOModelInfo;\nimport org.openecomp.policy.mso.MSOCloudConfiguration;\nimport org.openecomp.policy.mso.MSORequestInfo;\nimport org.openecomp.policy.mso.MSORequestParameters;\nimport org.openecomp.policy.mso.MSORelatedInstanceListElement;\nimport org.openecomp.policy.mso.MSORelatedInstance;\nimport org.openecomp.policy.mso.MSOResponse;\n\nimport org.openecomp.policy.drools.system.PolicyEngine;\n\n//\n// These parameters are required to build the runtime policy\n//\ndeclare Params\n closedLoopControlName : String\n actor : String\n aaiURL : String\n aaiUsername : String\n aaiPassword : String\n msoURL : String\n msoUsername : String\n msoPassword : String\n aaiNamedQueryUUID : String\n aaiPatternMatch : int \n notificationTopic : String\n appcTopic : String\nend\n\n/*\n*\n* Called once and only once to insert the parameters into working memory for this Closed Loop policy.\n* (Comment SETUP rule out for the first ECOMP opensource release since policy BRMS_GW already puts a Params fact in there)\n*\n*\n*rule \"BRMSParamvLBDemoPolicy.SETUP\"\n* when\n* then\n* System.out.println(\"rule SETUP is triggered.\");\n* Params params = new Params();\n* params.setClosedLoopControlName(\"CL-DNS-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\");\n* params.setActor(\"MSO\");\n* params.setAaiURL(\"https://aai.api.simpledemo.openecomp.org:8443\");\n* params.setAaiUsername(\"POLICY\");\n* params.setAaiPassword(\"POLICY\");\n* params.setMsoURL(\"http://vm1.mso.simpledemo.openecomp.org:8080/ecomp/mso/infra\");\n* params.setMsoUsername(\"InfraPortalClient\");\n* params.setMsoPassword(\"password1$\");\n* params.setAaiNamedQueryUUID(\"f199cb88-5e69-4b1f-93e0-6f257877d066\");\n* params.setAaiPatternMatch(0);\n* params.setNotificationTopic(\"POLICY-CL-MGT\");\n* params.setAppcTopic(\"APPC-CL\");\n* //\n* // This stays in memory as long as the rule is alive and running\n* //\n* insert(params);\n*end\n*/\n/*\n*\n* This rule responds to DCAE Events\n*\n*/\nrule \"BRMSParamvLBDemoPolicy.EVENT\"\n when\n $params : Params( getClosedLoopControlName() == \"CL-DNS-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )\n not ( EventManager( closedLoopControlName == $event.closedLoopControlName ))\n then\n System.out.println(\"rule EVENT is triggered.\");\n try {\n // \n // Check the requestID in the event to make sure it is not null before we create the EventManager. \n // The EventManager will do extra syntax checking as well check if the closed loop is disabled/\n //\n if ($event.requestID == null) {\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.notification = ControlLoopNotificationType.REJECTED;\n notification.from = \"policy\";\n notification.message = \"Missing requestID from DCAE event\";\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n e.printStackTrace();\n System.out.println(\"Can\'t deliver notification: \" + notification);\n }\n //\n // Retract it from memory\n //\n retract($event);\n System.out.println(\"Event with requestID=null has been retracted.\");\n } else {\n //\n // Create an EventManager\n //\n EventManager manager = new EventManager($params.getClosedLoopControlName(), $event.requestID, $event.target);\n //\n // Determine if EventManager can actively process the event (i.e. syntax)\n //\n VirtualControlLoopNotification notification = manager.activate($event);\n notification.from = \"policy\"; \n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n //\n // Are we actively pursuing this event?\n //\n if (notification.notification == ControlLoopNotificationType.ACTIVE) {\n //\n // Insert Event Manager into memory, this will now kick off processing.\n //\n insert(manager);\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n e.printStackTrace();\n System.out.println(\"Can\'t deliver notification: \" + notification);\n } \n } else {\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n e.printStackTrace();\n System.out.println(\"Can\'t deliver notification: \" + notification);\n }\n //\n // Retract it from memory\n //\n retract($event);\n }\n //\n // Now that the manager is inserted into Drools working memory, we\'ll wait for\n // another rule to fire in order to continue processing. This way we can also\n // then screen for additional ONSET and ABATED events for this same RequestIDs \n // and for different RequestIDs but with the same closedLoopControlName and target.\n //\n }\n //\n } catch (Exception e) {\n e.printStackTrace();\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.notification = ControlLoopNotificationType.REJECTED;\n notification.message = \"Exception occurred \" + e.getMessage();\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n //\n //\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e1) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e1.printStackTrace();\n }\n //\n // Retract the event\n //\n retract($event);\n }\nend\n\n/*\n*\n* This rule happens when we got a valid ONSET, closed loop is enabled and an Event Manager\n* is created. We can start the operations for this closed loop.\n*\n*/\nrule \"BRMSParamvLBDemoPolicy.EVENT.MANAGER\"\n when\n $params : Params( getClosedLoopControlName() == \"CL-DNS-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )\n $manager : EventManager( closedLoopControlName == $event.closedLoopControlName, controlLoopResult == null)\n then\n System.out.println(\"rule EVENT.MANAGER is triggered.\");\n //\n // Check which event this is.\n //\n EventManager.NEW_EVENT_STATUS eventStatus = $manager.onNewEvent($event);\n //\n // We only want the initial ONSET event in memory,\n // all the other events need to be retracted to support\n // cleanup and avoid the other rules being fired for this event.\n //\n if (eventStatus != EventManager.NEW_EVENT_STATUS.FIRST_ONSET) {\n System.out.println(\"Retracting \"+eventStatus+\" Event.\");\n retract($event);\n return;\n }\n //\n // Now the event in memory is first onset event\n //\n try {\n //\n // Pull the known AAI field from the Event\n //\n // generic-vnf is needed for vFirewall case\n // vserver-name is needed for vLoadBalancer case\n //\n String genericVNF = $event.AAI.get(\"generic-vnf.vnf-id\");\n String vserver = $event.AAI.get(\"vserver.vserver-name\");\n //\n // Check if we are implementing a simple pattern match.\n //\n if ($params.getAaiPatternMatch() == 1) {\n //\n // Yes\n //\n //Basic naming characteristics:\n //VF Name (9 char)+VM name (13 char total)+VFC (19 char total)\n //Example: \n //VF Name (9 characters): cscf0001v\n //VM Name(13 characters): cscf0001vm001\n //VFC name(19 characters): cscf0001vm001cfg001\n //\n // zdfw1fwl01fwl02 or zdfw1fwl01fwl01 \n // replaced with\n // zdfw1fwl01pgn02 or zdfw1fwl01pgn01\n //\n int index = genericVNF.lastIndexOf(\"fwl\");\n if (index == -1) {\n System.err.println(\"The generic-vnf.vnf-id from DCAE Event is not valid.\");\n } else {\n genericVNF = genericVNF.substring(0, index) + \"pgn\" + genericVNF.substring(index+\"fwl\".length());\n }\n //\n // Construct an APPC request\n //\n ControlLoopOperation operation = new ControlLoopOperation();\n operation.actor = $params.getActor();\n operation.operation = \"ModifyConfig\";\n operation.target = $event.target;\n //\n // Create operationWrapper\n //\n ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation);\n //\n // insert operationWrapper into memory\n //\n insert(operationWrapper);\n //\n Request request = new Request();\n request.CommonHeader = new CommonHeader();\n request.CommonHeader.RequestID = $event.requestID;\n request.Action = operation.operation;\n request.Payload = new HashMap<String, Object>();\n //\n // Fill in the payload\n //\n request.Payload.put(\"generic-vnf.vnf-id\", genericVNF);\n //\n PGRequest pgRequest = new PGRequest();\n pgRequest.pgStreams = new PGStreams();\n \n PGStream pgStream;\n for(int i = 0; i < 5; i++){\n pgStream = new PGStream();\n pgStream.streamId = \"fw_udp\"+(i+1);\n pgStream.isEnabled = \"true\";\n pgRequest.pgStreams.pgStream.add(pgStream);\n }\n request.Payload.put(\"pg-streams\", pgRequest.pgStreams);\n \n if (request != null) {\n //\n // Insert request into memory\n //\n insert(request);\n //\n // Tell interested parties we are performing this Operation\n //\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.notification = ControlLoopNotificationType.OPERATION;\n // message and history ??\n notification.from = \"policy\";\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // Now send the operation request\n //\n if (request instanceof Request) {\n try {\n System.out.println(\"APPC request sent:\");\n System.out.println(Serialization.gsonPretty.toJson(request));\n PolicyEngine.manager.deliver($params.getAppcTopic(), request);\n } catch (Exception e) {\n e.printStackTrace();\n System.out.println(\"Can\'t deliver request: \" + request);\n }\n }\n } else {\n //\n // what happens if it is null\n //\n }\n //\n } else {\n //\n // create AAI named-query request with UUID started with \"F199\"\n //\n AAINQF199Request aainqf199request = new AAINQF199Request();\n AAINQF199QueryParameters aainqf199queryparam = new AAINQF199QueryParameters();\n AAINQF199NamedQuery aainqf199namedquery = new AAINQF199NamedQuery();\n AAINQF199InstanceFilters aainqf199instancefilter = new AAINQF199InstanceFilters();\n //\n // queryParameters\n //\n aainqf199namedquery.namedQueryUUID = UUID.fromString($params.getAaiNamedQueryUUID()); \n aainqf199queryparam.namedQuery = aainqf199namedquery;\n aainqf199request.queryParameters = aainqf199queryparam;\n //\n // instanceFilters\n //\n Map aainqf199instancefiltermap = new HashMap();\n Map aainqf199instancefiltermapitem = new HashMap();\n aainqf199instancefiltermapitem.put(\"vserver-name\", vserver); \n aainqf199instancefiltermap.put(\"vserver\", aainqf199instancefiltermapitem);\n aainqf199instancefilter.instanceFilter.add(aainqf199instancefiltermap);\n aainqf199request.instanceFilters = aainqf199instancefilter;\n //\n // print aainqf199request for debug\n //\n System.out.println(\"AAI Request sent:\");\n System.out.println(Serialization.gsonPretty.toJson(aainqf199request));\n //\n // Create AAINQF199RequestWrapper\n //\n AAINQF199RequestWrapper aainqf199RequestWrapper = new AAINQF199RequestWrapper($event.requestID, aainqf199request);\n //\n // insert aainqf199request into memory\n //\n insert(aainqf199RequestWrapper);\n }\n //\n } catch (Exception e) {\n e.printStackTrace();\n }\nend\n\n/*\n*\n* This rule happens when we got a valid ONSET, closed loop is enabled, an Event Manager\n* is created, AAI Manager and AAI Request are ready in memory. We can start sending query to AAI and then wait for response.\n*\n*/\nrule \"BRMSParamvLBDemoPolicy.EVENT.MANAGER.AAINQF199REQUEST\"\n when\n $params : Params( getClosedLoopControlName() == \"CL-DNS-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )\n $manager : EventManager( closedLoopControlName == $event.closedLoopControlName )\n $aainqf199RequestWrapper : AAINQF199RequestWrapper(requestID == $event.requestID)\n then\n System.out.println(\"rule EVENT.MANAGER.AAINQF199REQUEST is triggered.\");\n //\n // send the request\n //\n AAINQF199Response aainqf199response = AAINQF199Manager.postQuery($params.getAaiURL(), $params.getAaiUsername(), $params.getAaiPassword(),\n $aainqf199RequestWrapper.aainqf199request, $event.requestID);\n //\n // Check AAI response\n //\n if (aainqf199response == null) {\n System.err.println(\"Failed to get AAI response\");\n //\n // Fail and retract everything\n //\n retract($event);\n retract($manager);\n retract($aainqf199RequestWrapper);\n } else {\n //\n // Create AAINQF199ResponseWrapper\n //\n AAINQF199ResponseWrapper aainqf199ResponseWrapper = new AAINQF199ResponseWrapper($event.requestID, aainqf199response);\n //\n // insert aainqf199ResponseWrapper to memeory\n //\n insert(aainqf199ResponseWrapper);\n }\nend\n\n/*\n*\n* This rule happens when we got a valid AAI response. We can start sending request to APPC or MSO now.\n*\n*/\nrule \"BRMSParamvLBDemoPolicy.EVENT.MANAGER.AAINQF199RESPONSE\"\n when \n $params : Params( getClosedLoopControlName() == \"CL-DNS-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )\n $manager : EventManager( closedLoopControlName == $event.closedLoopControlName )\n $aainqf199RequestWrapper : AAINQF199RequestWrapper(requestID == $event.requestID)\n $aainqf199ResponseWrapper : AAINQF199ResponseWrapper(requestID == $event.requestID)\n then\n System.out.println(\"rule EVENT.MANAGER.AAINQF199RESPONSE is triggered.\");\n //\n // Extract related fields out of AAINQF199RESPONSE\n //\n String vnfItemVnfId, vnfItemVnfType, vnfItemPersonaModelId, vnfItemPersonaModelVersion, vnfItemModelName, \n vnfItemModelVersion, vnfItemModelNameVersionId, serviceItemServiceInstanceId, serviceItemPersonaModelId,\n serviceItemModelName, serviceItemModelType, serviceItemModelVersion, serviceItemModelNameVersionId,\n vfModuleItemVfModuleName, vfModuleItemPersonaModelId, vfModuleItemPersonaModelVersion, vfModuleItemModelName, \n vfModuleItemModelNameVersionId, tenantItemTenantId, cloudRegionItemCloudRegionId;\n try {\n //\n // vnfItem\n //\n vnfItemVnfId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.vnfID;\n vnfItemVnfType = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.vnfType;\n vnfItemVnfType = vnfItemVnfType.substring(vnfItemVnfType.lastIndexOf(\"/\")+1);\n vnfItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.personaModelId;\n vnfItemPersonaModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.personaModelVersion;\n vnfItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(0).propertyValue;\n vnfItemModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(2).propertyValue;\n vnfItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(4).propertyValue;\n //\n // serviceItem\n //\n serviceItemServiceInstanceId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.serviceInstanceID;\n serviceItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.personaModelId;\n serviceItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(0).propertyValue;\n serviceItemModelType = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(1).propertyValue;\n serviceItemModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.personaModelVersion;\n serviceItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(4).propertyValue;\n //\n // Find the index for base vf module and non-base vf module\n //\n int baseIndex = -1;\n int nonBaseIndex = -1;\n List<AAINQF199InventoryResponseItem> inventoryItems = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems;\n for (AAINQF199InventoryResponseItem m : inventoryItems) {\n if (m.vfModule != null && m.vfModule.isBaseVfModule == true) {\n baseIndex = inventoryItems.indexOf(m);\n } else if (m.vfModule != null && m.vfModule.isBaseVfModule == false && m.vfModule.orchestrationStatus == null) {\n nonBaseIndex = inventoryItems.indexOf(m);\n }\n //\n if (baseIndex != -1 && nonBaseIndex != -1) {\n break;\n }\n }\n //\n // Report the error if either base vf module or non-base vf module is not found\n //\n if (baseIndex == -1 || nonBaseIndex == -1) {\n System.err.println(\"Either base or non-base vf module is not found from AAI response.\");\n retract($aainqf199RequestWrapper);\n retract($aainqf199ResponseWrapper);\n retract($manager);\n retract($event);\n return;\n }\n //\n // This comes from the base module\n //\n vfModuleItemVfModuleName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(baseIndex).vfModule.vfModuleName;\n vfModuleItemVfModuleName = vfModuleItemVfModuleName.replace(\"Vfmodule\", \"vDNS\");\n //\n // vfModuleItem - NOT the base module\n //\n vfModuleItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).vfModule.personaModelId;\n vfModuleItemPersonaModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).vfModule.personaModelVersion;\n vfModuleItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).extraProperties.extraProperty.get(0).propertyValue;\n vfModuleItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).extraProperties.extraProperty.get(4).propertyValue;\n //\n // tenantItem\n //\n tenantItemTenantId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(1).tenant.tenantId;\n //\n // cloudRegionItem\n //\n cloudRegionItemCloudRegionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(1).items.inventoryResponseItems.get(0).cloudRegion.cloudRegionId;\n //\n } catch (Exception e) {\n e.printStackTrace();\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.notification = ControlLoopNotificationType.REJECTED;\n notification.message = \"Exception occurred \" + e.getMessage();\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e1) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e1.printStackTrace();\n }\n //\n notification.notification = ControlLoopNotificationType.FINAL_FAILURE;\n notification.message = \"Invalid named-query response from AAI\";\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e1) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e1.printStackTrace();\n }\n //\n // Retract everything\n //\n retract($aainqf199RequestWrapper);\n retract($aainqf199ResponseWrapper);\n retract($manager);\n retract($event);\n return;\n } \n //\n // Extracted fields should not be null\n //\n if ((vnfItemVnfId == null) || (vnfItemVnfType == null) ||\n (vnfItemPersonaModelId == null) || (vnfItemModelName == null) ||\n (vnfItemModelVersion == null) || (vnfItemModelNameVersionId == null) ||\n (serviceItemServiceInstanceId == null) || (serviceItemModelName == null) ||\n (serviceItemModelType == null) || (serviceItemModelVersion == null) ||\n (serviceItemModelNameVersionId == null) || (vfModuleItemVfModuleName == null) ||\n (vfModuleItemPersonaModelId == null) || (vfModuleItemPersonaModelVersion == null) ||\n (vfModuleItemModelName == null) || (vfModuleItemModelNameVersionId == null) ||\n (tenantItemTenantId == null) || (cloudRegionItemCloudRegionId == null)) {\n //\n System.err.println(\"some fields are missing from AAI response.\");\n //\n // Fail and retract everything\n //\n retract($aainqf199RequestWrapper);\n retract($aainqf199ResponseWrapper);\n retract($manager);\n retract($event);\n return;\n }\n //\n // We don\'t need them any more\n //\n retract($aainqf199ResponseWrapper);\n retract($aainqf199RequestWrapper); \n //\n // check the actor of this closed loop\n //\n switch ($params.getActor()) {\n case \"APPC\":\n {\n //\n // Construct an APPC request\n //\n ControlLoopOperation operation = new ControlLoopOperation();\n operation.actor = $params.getActor();\n operation.operation = \"ModifyConfig\";\n operation.target = $event.target;\n //\n // Create operationWrapper\n //\n ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation);\n //\n // insert operationWrapper into memory\n //\n insert(operationWrapper);\n //\n Request request = new Request();\n request.CommonHeader = new CommonHeader();\n request.CommonHeader.RequestID = $event.requestID;\n request.Action = operation.operation;\n request.Payload = new HashMap<String, Object>();\n //\n // Fill in the payload\n // Hardcode genericVNF for now since AAI has not been ready for vFirewall demo case\n //\n String genericVNF = \"zdfw1fwl01pgn02\";\n request.Payload.put(\"generic-vnf.vnf-id\", genericVNF);\n //\n PGRequest pgRequest = new PGRequest();\n pgRequest.pgStreams = new PGStreams();\n \n PGStream pgStream;\n for(int i = 0; i < 5; i++){\n pgStream = new PGStream();\n pgStream.streamId = \"fw_udp\"+(i+1);\n pgStream.isEnabled = \"true\";\n pgRequest.pgStreams.pgStream.add(pgStream);\n }\n request.Payload.put(\"pg-streams\", pgRequest.pgStreams);\n \n if (request != null) {\n //\n // Insert request into memory\n //\n insert(request);\n //\n // Tell interested parties we are performing this Operation\n //\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.notification = ControlLoopNotificationType.OPERATION;\n // message and history ??\n notification.from = \"policy\";\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // Now send the operation request\n //\n if (request instanceof Request) {\n try {\n System.out.println(\"APPC request sent:\");\n System.out.println(Serialization.gsonPretty.toJson(request));\n PolicyEngine.manager.deliver($params.getAppcTopic(), request);\n } catch (Exception e) {\n e.printStackTrace();\n System.out.println(\"Can\'t deliver request: \" + request);\n }\n }\n } else {\n //\n // what happens if it is null\n //\n }\n }\n break;\n case \"MSO\":\n {\n //\n // Construct an operation\n //\n ControlLoopOperation operation = new ControlLoopOperation();\n operation.actor = $params.getActor();\n operation.operation = \"createModuleInstance\";\n operation.target = $event.target;\n //\n // Create operationWrapper\n //\n ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation);\n //\n // Construct an MSO request\n //\n MSORequest request = new MSORequest();\n request.requestDetails = new MSORequestDetails();\n request.requestDetails.modelInfo = new MSOModelInfo();\n request.requestDetails.cloudConfiguration = new MSOCloudConfiguration();\n request.requestDetails.requestInfo = new MSORequestInfo();\n request.requestDetails.requestParameters = new MSORequestParameters();\n request.requestDetails.requestParameters.userParams = null;\n //\n // cloudConfiguration\n //\n request.requestDetails.cloudConfiguration.lcpCloudRegionId = cloudRegionItemCloudRegionId;\n request.requestDetails.cloudConfiguration.tenantId = tenantItemTenantId;\n //\n // modelInfo\n //\n request.requestDetails.modelInfo.modelType = \"vfModule\";\n request.requestDetails.modelInfo.modelInvariantId = vfModuleItemPersonaModelId;\n request.requestDetails.modelInfo.modelNameVersionId = vfModuleItemModelNameVersionId;\n request.requestDetails.modelInfo.modelName = vfModuleItemModelName;\n request.requestDetails.modelInfo.modelVersion = vfModuleItemPersonaModelVersion;\n //\n // requestInfo\n //\n request.requestDetails.requestInfo.instanceName = vfModuleItemVfModuleName;\n request.requestDetails.requestInfo.source = \"POLICY\";\n request.requestDetails.requestInfo.suppressRollback = false;\n //\n // relatedInstanceList\n //\n MSORelatedInstanceListElement relatedInstanceListElement1 = new MSORelatedInstanceListElement();\n MSORelatedInstanceListElement relatedInstanceListElement2 = new MSORelatedInstanceListElement();\n relatedInstanceListElement1.relatedInstance = new MSORelatedInstance();\n relatedInstanceListElement2.relatedInstance = new MSORelatedInstance();\n //\n relatedInstanceListElement1.relatedInstance.instanceId = serviceItemServiceInstanceId;\n relatedInstanceListElement1.relatedInstance.modelInfo = new MSOModelInfo();\n relatedInstanceListElement1.relatedInstance.modelInfo.modelType = \"service\";\n relatedInstanceListElement1.relatedInstance.modelInfo.modelInvariantId = serviceItemPersonaModelId;\n relatedInstanceListElement1.relatedInstance.modelInfo.modelNameVersionId = serviceItemModelNameVersionId;\n relatedInstanceListElement1.relatedInstance.modelInfo.modelName = serviceItemModelName;\n relatedInstanceListElement1.relatedInstance.modelInfo.modelVersion = serviceItemModelVersion;\n //\n relatedInstanceListElement2.relatedInstance.instanceId = vnfItemVnfId;\n relatedInstanceListElement2.relatedInstance.modelInfo = new MSOModelInfo();\n relatedInstanceListElement2.relatedInstance.modelInfo.modelType = \"vnf\";\n relatedInstanceListElement2.relatedInstance.modelInfo.modelInvariantId = vnfItemPersonaModelId;\n relatedInstanceListElement2.relatedInstance.modelInfo.modelNameVersionId = vnfItemModelNameVersionId;\n relatedInstanceListElement2.relatedInstance.modelInfo.modelName = vnfItemModelName;\n relatedInstanceListElement2.relatedInstance.modelInfo.modelVersion = vnfItemModelVersion;\n relatedInstanceListElement2.relatedInstance.modelInfo.modelCustomizationName = vnfItemVnfType;\n // \n request.requestDetails.relatedInstanceList.add(relatedInstanceListElement1);\n request.requestDetails.relatedInstanceList.add(relatedInstanceListElement2);\n //\n // print MSO request for debug\n //\n System.out.println(\"MSO request sent:\");\n System.out.println(Serialization.gsonPretty.toJson(request));\n //\n //\n //\n if (request != null) {\n //\n // Tell interested parties we are performing this Operation\n //\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.notification = ControlLoopNotificationType.OPERATION;\n notification.from = \"policy\";\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // Concatenate serviceItemServiceInstanceId and vnfItemVnfId to msoURL\n //\n String MSOUrl = $params.getMsoURL() + \"/serviceInstances/v2/\" + serviceItemServiceInstanceId + \"/vnfs/\" + vnfItemVnfId + \"/vfModules\";\n //\n // Call MSO\n //\n MSOResponse response = MSOManager.createModuleInstance(MSOUrl, $params.getMsoURL(), $params.getMsoUsername(), $params.getMsoPassword(), request);\n //\n if (response != null) {\n //\n // Assign requestId\n //\n request.requestId = $event.requestID.toString(); \n response.request.requestId = $event.requestID.toString();\n //\n // Insert facts\n //\n insert(operationWrapper);\n insert(request);\n insert(response);\n } else {\n //\n // MSO request not even accepted\n //\n notification.message = operationWrapper.operation.toMessage();\n operationWrapper.operation.message = operationWrapper.operation.toMessage();\n operationWrapper.operation.outcome = \"FAILURE_EXCEPTION\";\n $manager.setControlLoopResult(\"FAILURE_EXCEPTION\");\n notification.history.add(operationWrapper.operation);\n notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n notification.notification = ControlLoopNotificationType.FINAL_FAILURE;\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // Retract everything\n //\n retract($event);\n retract($manager);\n }\n } else {\n System.err.println(\"constructed MSO request is invalid.\");\n }\n }\n break; \n } \nend\n \n/*\n*\n* This rule responds to APPC Response Events\n*\n*/\nrule \"BRMSParamvLBDemoPolicy.APPC.RESPONSE\"\n when\n $params : Params( getClosedLoopControlName() == \"CL-DNS-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )\n $manager : EventManager( closedLoopControlName == $event.closedLoopControlName )\n $operationWrapper : ControlLoopOperationWrapper( requestID == $event.requestID )\n $request : Request( getCommonHeader().RequestID == $event.requestID )\n $response : Response( getCommonHeader().RequestID == $event.requestID ) \n then\n System.out.println(\"rule APPC.RESPONSE is triggered.\");\n if ($response.Status == null) {\n $operationWrapper.operation.outcome = \"FAILURE_EXCEPTION\";\n $manager.setControlLoopResult(\"FAILURE_EXCEPTION\");\n } \n //\n // Get the Response Code\n //\n ResponseCode code = ResponseCode.toResponseCode($response.Status.Code);\n if (code == null) {\n $operationWrapper.operation.outcome = \"FAILURE_EXCEPTION\";\n $manager.setControlLoopResult(\"FAILURE_EXCEPTION\");\n }\n //\n // Construct notification\n //\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.from = \"policy\";\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n notification.message = $operationWrapper.operation.toMessage();\n $operationWrapper.operation.message = $operationWrapper.operation.toMessage();\n //\n // Ok, let\'s figure out what APP-C\'s response is\n //\n switch (code) {\n case ACCEPT:\n $operationWrapper.operation.outcome = \"PROCESSING\";\n break;\n case ERROR:\n case REJECT:\n $operationWrapper.operation.outcome = \"FAILURE_EXCEPTION\";\n $manager.setControlLoopResult(\"FAILURE_EXCEPTION\");\n break;\n case SUCCESS:\n $operationWrapper.operation.outcome = \"SUCCESS\";\n $manager.setControlLoopResult(\"SUCCESS\");\n break;\n case FAILURE:\n $operationWrapper.operation.outcome = \"FAILURE\";\n $manager.setControlLoopResult(\"FAILURE\");\n break;\n }\n if ($operationWrapper.operation.outcome.equals(\"SUCCESS\")) {\n notification.history.add($operationWrapper.operation);\n notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n notification.notification = ControlLoopNotificationType.FINAL_SUCCESS;\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n\n //\n // We are going to retract these objects from memory\n //\n System.out.println(\"Retracting everything\");\n retract($operationWrapper);\n retract($request);\n retract($response);\n retract($event);\n retract($manager);\n } else if ($operationWrapper.operation.outcome.equals(\"PROCESSING\")) {\n retract($response);\n } else {\n notification.history.add($operationWrapper.operation);\n notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n notification.notification = ControlLoopNotificationType.FINAL_FAILURE;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // We are going to retract these objects from memory\n //\n System.out.println(\"Retracting everything\");\n retract($operationWrapper);\n retract($request);\n retract($response);\n retract($event);\n retract($manager);\n }\n \nend \n\n/*\n*\n* This rule is used to clean up APPC response\n*\n*/ \nrule \"BRMSParamvLBDemoPolicy.APPC.RESPONSE.CLEANUP\"\n when\n $params : Params( getClosedLoopControlName() == \"CL-DNS-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $response : Response($id : getCommonHeader().RequestID )\n not ( VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), requestID == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) ) \n then\n System.out.println(\"rule APPC.RESPONSE.CLEANUP is triggered.\");\n retract($response);\nend\n\n/*\n*\n* This rule responds to MSO Response Events\n*\n*/\nrule \"BRMSParamvLBDemoPolicy.MSO.RESPONSE\"\n when\n $params : Params( getClosedLoopControlName() == \"CL-DNS-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )\n $manager : EventManager( closedLoopControlName == $event.closedLoopControlName )\n $operationWrapper : ControlLoopOperationWrapper( requestID == $event.requestID )\n $request : MSORequest( requestId == $event.requestID.toString() )\n $response : MSOResponse( request.requestId == $event.requestID.toString() ) \n then\n System.out.println(\"rule MSO.RESPONSE is triggered.\");\n //\n // Construct notification\n //\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.from = \"policy\";\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n notification.message = $operationWrapper.operation.toMessage();\n $operationWrapper.operation.message = $operationWrapper.operation.toMessage();\n //\n // The operation can either be succeeded or failed\n // \n if($response.request.requestStatus.requestState.equals(\"COMPLETE\")) {\n $operationWrapper.operation.outcome = \"SUCCESS\";\n $manager.setControlLoopResult(\"SUCCESS\");\n notification.history.add($operationWrapper.operation);\n notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n notification.notification = ControlLoopNotificationType.FINAL_SUCCESS;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // We are going to retract these objects from memory\n //\n System.out.println(\"Retracting everything\");\n retract($operationWrapper);\n retract($request);\n retract($response);\n retract($event);\n retract($manager);\n } else {\n $operationWrapper.operation.outcome = \"FAILURE\";\n $manager.setControlLoopResult(\"FAILURE\");\n notification.history.add($operationWrapper.operation);\n notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n notification.notification = ControlLoopNotificationType.FINAL_FAILURE;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // We are going to retract these objects from memory\n //\n System.out.println(\"Retracting everything\");\n retract($operationWrapper);\n retract($request);\n retract($response);\n retract($event);\n retract($manager);\n }\n \nend \nrule \"Params\" \n salience 1000 \n when\n then\n Params params = new Params();\n params.setAaiPatternMatch(0);\n params.setAppcTopic(\"APPC-CL\");\n params.setAaiURL(\"https://aai.api.simpledemo.openecomp.org:8443\");\n params.setMsoPassword(\"password1$\");\n params.setClosedLoopControlName(\"CL-DNS-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\");\n params.setAaiUsername(\"POLICY\");\n params.setMsoURL(\"http://vm1.mso.simpledemo.openecomp.org:8080/ecomp/mso/infra\");\n params.setActor(\"MSO\");\n params.setMsoUsername(\"InfraPortalClient\");\n params.setAaiNamedQueryUUID(\"f199cb88-5e69-4b1f-93e0-6f257877d066\");\n params.setAaiPassword(\"POLICY\");\n params.setNotificationTopic(\"POLICY-CL-MGT\");\n insert(params);\nend\r\n','OTHER','com.Config_BRMS_Param_BRMSParamvLBDemoPolicy.1.txt','doACPolicyPut','2017-03-14 20:00:56',0,'','doACPolicyPut','2017-03-14 20:00:56',1);
+INSERT INTO `configurationdataentity` VALUES (3201,'/* Autogenerated Code Please Don\'t change/remove this comment section. This is for the UI purpose. \n <$%BRMSParamTemplate=ControlLoopDemo__closedLoopControlName%$> \n */ \n\r\n\r\n/*-\n * ============LICENSE_START=======================================================\n * archetype-closed-loop-demo-rules\n * ================================================================================\n * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\n * ================================================================================\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * ============LICENSE_END=========================================================\n */\n\npackage org.openecomp.policy.controlloop;\n\nimport java.util.List;\nimport java.util.LinkedList;\nimport java.util.Map;\nimport java.util.HashMap;\nimport java.util.UUID;\n\nimport org.openecomp.policy.controlloop.VirtualControlLoopEvent;\nimport org.openecomp.policy.controlloop.ControlLoopEventStatus;\nimport org.openecomp.policy.controlloop.VirtualControlLoopNotification;\nimport org.openecomp.policy.controlloop.ControlLoopNotificationType;\nimport org.openecomp.policy.controlloop.ControlLoopOperation;\nimport org.openecomp.policy.controlloop.ControlLoopOperationWrapper;\nimport org.openecomp.policy.template.demo.ControlLoopException;\n\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199CloudRegion;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199ExtraProperties;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199ExtraProperty;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199GenericVNF;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199InstanceFilters;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199InventoryResponseItem;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199InventoryResponseItems;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199Manager;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199NamedQuery;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199QueryParameters;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199Request;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199RequestWrapper;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199Response;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199ResponseWrapper;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199ServiceInstance;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199Tenant;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199VfModule;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199VServer;\nimport org.openecomp.policy.aai.util.Serialization;\n\nimport org.openecomp.policy.appc.CommonHeader;\nimport org.openecomp.policy.appc.Request;\nimport org.openecomp.policy.appc.Response;\nimport org.openecomp.policy.appc.ResponseCode;\nimport org.openecomp.policy.appc.ResponseStatus;\nimport org.openecomp.policy.appc.ResponseValue;\n\nimport org.openecomp.policy.template.demo.EventManager;\nimport org.openecomp.policy.vnf.trafficgenerator.PGRequest;\nimport org.openecomp.policy.vnf.trafficgenerator.PGStream;\nimport org.openecomp.policy.vnf.trafficgenerator.PGStreams;\n\nimport org.openecomp.policy.mso.MSOManager;\nimport org.openecomp.policy.mso.MSORequest;\nimport org.openecomp.policy.mso.MSORequestStatus;\nimport org.openecomp.policy.mso.MSORequestDetails;\nimport org.openecomp.policy.mso.MSOModelInfo;\nimport org.openecomp.policy.mso.MSOCloudConfiguration;\nimport org.openecomp.policy.mso.MSORequestInfo;\nimport org.openecomp.policy.mso.MSORequestParameters;\nimport org.openecomp.policy.mso.MSORelatedInstanceListElement;\nimport org.openecomp.policy.mso.MSORelatedInstance;\nimport org.openecomp.policy.mso.MSOResponse;\n\nimport org.openecomp.policy.drools.system.PolicyEngine;\n\n//\n// These parameters are required to build the runtime policy\n//\ndeclare Params\n closedLoopControlName : String\n actor : String\n aaiURL : String\n aaiUsername : String\n aaiPassword : String\n msoURL : String\n msoUsername : String\n msoPassword : String\n aaiNamedQueryUUID : String\n aaiPatternMatch : int \n notificationTopic : String\n appcTopic : String\nend\n\n/*\n*\n* Called once and only once to insert the parameters into working memory for this Closed Loop policy.\n* (Comment SETUP rule out for the first ECOMP opensource release since policy BRMS_GW already puts a Params fact in there)\n*\n*\n*rule \"BRMSParamvFWDemoPolicy.SETUP\"\n* when\n* then\n* System.out.println(\"rule SETUP is triggered.\");\n* Params params = new Params();\n* params.setClosedLoopControlName(\"CL-FRWL-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\");\n* params.setActor(\"APPC\");\n* params.setAaiURL(\"null\");\n* params.setAaiUsername(\"null\");\n* params.setAaiPassword(\"null\");\n* params.setMsoURL(\"null\");\n* params.setMsoUsername(\"null\");\n* params.setMsoPassword(\"null\");\n* params.setAaiNamedQueryUUID(\"null\");\n* params.setAaiPatternMatch(1);\n* params.setNotificationTopic(\"POLICY-CL-MGT\");\n* params.setAppcTopic(\"APPC-CL\");\n* //\n* // This stays in memory as long as the rule is alive and running\n* //\n* insert(params);\n*end\n*/\n/*\n*\n* This rule responds to DCAE Events\n*\n*/\nrule \"BRMSParamvFWDemoPolicy.EVENT\"\n when\n $params : Params( getClosedLoopControlName() == \"CL-FRWL-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )\n not ( EventManager( closedLoopControlName == $event.closedLoopControlName ))\n then\n System.out.println(\"rule EVENT is triggered.\");\n try {\n // \n // Check the requestID in the event to make sure it is not null before we create the EventManager. \n // The EventManager will do extra syntax checking as well check if the closed loop is disabled/\n //\n if ($event.requestID == null) {\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.notification = ControlLoopNotificationType.REJECTED;\n notification.from = \"policy\";\n notification.message = \"Missing requestID from DCAE event\";\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n e.printStackTrace();\n System.out.println(\"Can\'t deliver notification: \" + notification);\n }\n //\n // Retract it from memory\n //\n retract($event);\n System.out.println(\"Event with requestID=null has been retracted.\");\n } else {\n //\n // Create an EventManager\n //\n EventManager manager = new EventManager($params.getClosedLoopControlName(), $event.requestID, $event.target);\n //\n // Determine if EventManager can actively process the event (i.e. syntax)\n //\n VirtualControlLoopNotification notification = manager.activate($event);\n notification.from = \"policy\"; \n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n //\n // Are we actively pursuing this event?\n //\n if (notification.notification == ControlLoopNotificationType.ACTIVE) {\n //\n // Insert Event Manager into memory, this will now kick off processing.\n //\n insert(manager);\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n e.printStackTrace();\n System.out.println(\"Can\'t deliver notification: \" + notification);\n } \n } else {\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n e.printStackTrace();\n System.out.println(\"Can\'t deliver notification: \" + notification);\n }\n //\n // Retract it from memory\n //\n retract($event);\n }\n //\n // Now that the manager is inserted into Drools working memory, we\'ll wait for\n // another rule to fire in order to continue processing. This way we can also\n // then screen for additional ONSET and ABATED events for this same RequestIDs \n // and for different RequestIDs but with the same closedLoopControlName and target.\n //\n }\n //\n } catch (Exception e) {\n e.printStackTrace();\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.notification = ControlLoopNotificationType.REJECTED;\n notification.message = \"Exception occurred \" + e.getMessage();\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n //\n //\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e1) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e1.printStackTrace();\n }\n //\n // Retract the event\n //\n retract($event);\n }\nend\n\n/*\n*\n* This rule happens when we got a valid ONSET, closed loop is enabled and an Event Manager\n* is created. We can start the operations for this closed loop.\n*\n*/\nrule \"BRMSParamvFWDemoPolicy.EVENT.MANAGER\"\n when\n $params : Params( getClosedLoopControlName() == \"CL-FRWL-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )\n $manager : EventManager( closedLoopControlName == $event.closedLoopControlName, controlLoopResult == null)\n then\n System.out.println(\"rule EVENT.MANAGER is triggered.\");\n //\n // Check which event this is.\n //\n EventManager.NEW_EVENT_STATUS eventStatus = $manager.onNewEvent($event);\n //\n // We only want the initial ONSET event in memory,\n // all the other events need to be retracted to support\n // cleanup and avoid the other rules being fired for this event.\n //\n if (eventStatus != EventManager.NEW_EVENT_STATUS.FIRST_ONSET) {\n System.out.println(\"Retracting \"+eventStatus+\" Event.\");\n retract($event);\n return;\n }\n //\n // Now the event in memory is first onset event\n //\n try {\n //\n // Pull the known AAI field from the Event\n //\n // generic-vnf is needed for vFirewall case\n // vserver-name is needed for vLoadBalancer case\n //\n String genericVNF = $event.AAI.get(\"generic-vnf.vnf-id\");\n String vserver = $event.AAI.get(\"vserver.vserver-name\");\n //\n // Check if we are implementing a simple pattern match.\n //\n if ($params.getAaiPatternMatch() == 1) {\n //\n // Yes\n //\n //Basic naming characteristics:\n //VF Name (9 char)+VM name (13 char total)+VFC (19 char total)\n //Example: \n //VF Name (9 characters): cscf0001v\n //VM Name(13 characters): cscf0001vm001\n //VFC name(19 characters): cscf0001vm001cfg001\n //\n // zdfw1fwl01fwl02 or zdfw1fwl01fwl01 \n // replaced with\n // zdfw1fwl01pgn02 or zdfw1fwl01pgn01\n //\n int index = genericVNF.lastIndexOf(\"fwl\");\n if (index == -1) {\n System.err.println(\"The generic-vnf.vnf-id from DCAE Event is not valid.\");\n } else {\n genericVNF = genericVNF.substring(0, index) + \"pgn\" + genericVNF.substring(index+\"fwl\".length());\n }\n //\n // Construct an APPC request\n //\n ControlLoopOperation operation = new ControlLoopOperation();\n operation.actor = $params.getActor();\n operation.operation = \"ModifyConfig\";\n operation.target = $event.target;\n //\n // Create operationWrapper\n //\n ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation);\n //\n // insert operationWrapper into memory\n //\n insert(operationWrapper);\n //\n Request request = new Request();\n request.CommonHeader = new CommonHeader();\n request.CommonHeader.RequestID = $event.requestID;\n request.Action = operation.operation;\n request.Payload = new HashMap<String, Object>();\n //\n // Fill in the payload\n //\n request.Payload.put(\"generic-vnf.vnf-id\", genericVNF);\n //\n PGRequest pgRequest = new PGRequest();\n pgRequest.pgStreams = new PGStreams();\n \n PGStream pgStream;\n for(int i = 0; i < 5; i++){\n pgStream = new PGStream();\n pgStream.streamId = \"fw_udp\"+(i+1);\n pgStream.isEnabled = \"true\";\n pgRequest.pgStreams.pgStream.add(pgStream);\n }\n request.Payload.put(\"pg-streams\", pgRequest.pgStreams);\n \n if (request != null) {\n //\n // Insert request into memory\n //\n insert(request);\n //\n // Tell interested parties we are performing this Operation\n //\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.notification = ControlLoopNotificationType.OPERATION;\n // message and history ??\n notification.from = \"policy\";\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // Now send the operation request\n //\n if (request instanceof Request) {\n try {\n System.out.println(\"APPC request sent:\");\n System.out.println(Serialization.gsonPretty.toJson(request));\n PolicyEngine.manager.deliver($params.getAppcTopic(), request);\n } catch (Exception e) {\n e.printStackTrace();\n System.out.println(\"Can\'t deliver request: \" + request);\n }\n }\n } else {\n //\n // what happens if it is null\n //\n }\n //\n } else {\n //\n // create AAI named-query request with UUID started with \"F199\"\n //\n AAINQF199Request aainqf199request = new AAINQF199Request();\n AAINQF199QueryParameters aainqf199queryparam = new AAINQF199QueryParameters();\n AAINQF199NamedQuery aainqf199namedquery = new AAINQF199NamedQuery();\n AAINQF199InstanceFilters aainqf199instancefilter = new AAINQF199InstanceFilters();\n //\n // queryParameters\n //\n aainqf199namedquery.namedQueryUUID = UUID.fromString($params.getAaiNamedQueryUUID()); \n aainqf199queryparam.namedQuery = aainqf199namedquery;\n aainqf199request.queryParameters = aainqf199queryparam;\n //\n // instanceFilters\n //\n Map aainqf199instancefiltermap = new HashMap();\n Map aainqf199instancefiltermapitem = new HashMap();\n aainqf199instancefiltermapitem.put(\"vserver-name\", vserver); \n aainqf199instancefiltermap.put(\"vserver\", aainqf199instancefiltermapitem);\n aainqf199instancefilter.instanceFilter.add(aainqf199instancefiltermap);\n aainqf199request.instanceFilters = aainqf199instancefilter;\n //\n // print aainqf199request for debug\n //\n System.out.println(\"AAI Request sent:\");\n System.out.println(Serialization.gsonPretty.toJson(aainqf199request));\n //\n // Create AAINQF199RequestWrapper\n //\n AAINQF199RequestWrapper aainqf199RequestWrapper = new AAINQF199RequestWrapper($event.requestID, aainqf199request);\n //\n // insert aainqf199request into memory\n //\n insert(aainqf199RequestWrapper);\n }\n //\n } catch (Exception e) {\n e.printStackTrace();\n }\nend\n\n/*\n*\n* This rule happens when we got a valid ONSET, closed loop is enabled, an Event Manager\n* is created, AAI Manager and AAI Request are ready in memory. We can start sending query to AAI and then wait for response.\n*\n*/\nrule \"BRMSParamvFWDemoPolicy.EVENT.MANAGER.AAINQF199REQUEST\"\n when\n $params : Params( getClosedLoopControlName() == \"CL-FRWL-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )\n $manager : EventManager( closedLoopControlName == $event.closedLoopControlName )\n $aainqf199RequestWrapper : AAINQF199RequestWrapper(requestID == $event.requestID)\n then\n System.out.println(\"rule EVENT.MANAGER.AAINQF199REQUEST is triggered.\");\n //\n // send the request\n //\n AAINQF199Response aainqf199response = AAINQF199Manager.postQuery($params.getAaiURL(), $params.getAaiUsername(), $params.getAaiPassword(),\n $aainqf199RequestWrapper.aainqf199request, $event.requestID);\n //\n // Check AAI response\n //\n if (aainqf199response == null) {\n System.err.println(\"Failed to get AAI response\");\n //\n // Fail and retract everything\n //\n retract($event);\n retract($manager);\n retract($aainqf199RequestWrapper);\n } else {\n //\n // Create AAINQF199ResponseWrapper\n //\n AAINQF199ResponseWrapper aainqf199ResponseWrapper = new AAINQF199ResponseWrapper($event.requestID, aainqf199response);\n //\n // insert aainqf199ResponseWrapper to memeory\n //\n insert(aainqf199ResponseWrapper);\n }\nend\n\n/*\n*\n* This rule happens when we got a valid AAI response. We can start sending request to APPC or MSO now.\n*\n*/\nrule \"BRMSParamvFWDemoPolicy.EVENT.MANAGER.AAINQF199RESPONSE\"\n when \n $params : Params( getClosedLoopControlName() == \"CL-FRWL-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )\n $manager : EventManager( closedLoopControlName == $event.closedLoopControlName )\n $aainqf199RequestWrapper : AAINQF199RequestWrapper(requestID == $event.requestID)\n $aainqf199ResponseWrapper : AAINQF199ResponseWrapper(requestID == $event.requestID)\n then\n System.out.println(\"rule EVENT.MANAGER.AAINQF199RESPONSE is triggered.\");\n //\n // Extract related fields out of AAINQF199RESPONSE\n //\n String vnfItemVnfId, vnfItemVnfType, vnfItemPersonaModelId, vnfItemPersonaModelVersion, vnfItemModelName, \n vnfItemModelVersion, vnfItemModelNameVersionId, serviceItemServiceInstanceId, serviceItemPersonaModelId,\n serviceItemModelName, serviceItemModelType, serviceItemModelVersion, serviceItemModelNameVersionId,\n vfModuleItemVfModuleName, vfModuleItemPersonaModelId, vfModuleItemPersonaModelVersion, vfModuleItemModelName, \n vfModuleItemModelNameVersionId, tenantItemTenantId, cloudRegionItemCloudRegionId;\n try {\n //\n // vnfItem\n //\n vnfItemVnfId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.vnfID;\n vnfItemVnfType = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.vnfType;\n vnfItemVnfType = vnfItemVnfType.substring(vnfItemVnfType.lastIndexOf(\"/\")+1);\n vnfItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.personaModelId;\n vnfItemPersonaModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.personaModelVersion;\n vnfItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(0).propertyValue;\n vnfItemModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(2).propertyValue;\n vnfItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(4).propertyValue;\n //\n // serviceItem\n //\n serviceItemServiceInstanceId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.serviceInstanceID;\n serviceItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.personaModelId;\n serviceItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(0).propertyValue;\n serviceItemModelType = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(1).propertyValue;\n serviceItemModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.personaModelVersion;\n serviceItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(4).propertyValue;\n //\n // Find the index for base vf module and non-base vf module\n //\n int baseIndex = -1;\n int nonBaseIndex = -1;\n List<AAINQF199InventoryResponseItem> inventoryItems = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems;\n for (AAINQF199InventoryResponseItem m : inventoryItems) {\n if (m.vfModule != null && m.vfModule.isBaseVfModule == true) {\n baseIndex = inventoryItems.indexOf(m);\n } else if (m.vfModule != null && m.vfModule.isBaseVfModule == false && m.vfModule.orchestrationStatus == null) {\n nonBaseIndex = inventoryItems.indexOf(m);\n }\n //\n if (baseIndex != -1 && nonBaseIndex != -1) {\n break;\n }\n }\n //\n // Report the error if either base vf module or non-base vf module is not found\n //\n if (baseIndex == -1 || nonBaseIndex == -1) {\n System.err.println(\"Either base or non-base vf module is not found from AAI response.\");\n retract($aainqf199RequestWrapper);\n retract($aainqf199ResponseWrapper);\n retract($manager);\n retract($event);\n return;\n }\n //\n // This comes from the base module\n //\n vfModuleItemVfModuleName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(baseIndex).vfModule.vfModuleName;\n vfModuleItemVfModuleName = vfModuleItemVfModuleName.replace(\"Vfmodule\", \"vDNS\");\n //\n // vfModuleItem - NOT the base module\n //\n vfModuleItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).vfModule.personaModelId;\n vfModuleItemPersonaModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).vfModule.personaModelVersion;\n vfModuleItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).extraProperties.extraProperty.get(0).propertyValue;\n vfModuleItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).extraProperties.extraProperty.get(4).propertyValue;\n //\n // tenantItem\n //\n tenantItemTenantId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(1).tenant.tenantId;\n //\n // cloudRegionItem\n //\n cloudRegionItemCloudRegionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(1).items.inventoryResponseItems.get(0).cloudRegion.cloudRegionId;\n //\n } catch (Exception e) {\n e.printStackTrace();\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.notification = ControlLoopNotificationType.REJECTED;\n notification.message = \"Exception occurred \" + e.getMessage();\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e1) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e1.printStackTrace();\n }\n //\n notification.notification = ControlLoopNotificationType.FINAL_FAILURE;\n notification.message = \"Invalid named-query response from AAI\";\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e1) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e1.printStackTrace();\n }\n //\n // Retract everything\n //\n retract($aainqf199RequestWrapper);\n retract($aainqf199ResponseWrapper);\n retract($manager);\n retract($event);\n return;\n } \n //\n // Extracted fields should not be null\n //\n if ((vnfItemVnfId == null) || (vnfItemVnfType == null) ||\n (vnfItemPersonaModelId == null) || (vnfItemModelName == null) ||\n (vnfItemModelVersion == null) || (vnfItemModelNameVersionId == null) ||\n (serviceItemServiceInstanceId == null) || (serviceItemModelName == null) ||\n (serviceItemModelType == null) || (serviceItemModelVersion == null) ||\n (serviceItemModelNameVersionId == null) || (vfModuleItemVfModuleName == null) ||\n (vfModuleItemPersonaModelId == null) || (vfModuleItemPersonaModelVersion == null) ||\n (vfModuleItemModelName == null) || (vfModuleItemModelNameVersionId == null) ||\n (tenantItemTenantId == null) || (cloudRegionItemCloudRegionId == null)) {\n //\n System.err.println(\"some fields are missing from AAI response.\");\n //\n // Fail and retract everything\n //\n retract($aainqf199RequestWrapper);\n retract($aainqf199ResponseWrapper);\n retract($manager);\n retract($event);\n return;\n }\n //\n // We don\'t need them any more\n //\n retract($aainqf199ResponseWrapper);\n retract($aainqf199RequestWrapper); \n //\n // check the actor of this closed loop\n //\n switch ($params.getActor()) {\n case \"APPC\":\n {\n //\n // Construct an APPC request\n //\n ControlLoopOperation operation = new ControlLoopOperation();\n operation.actor = $params.getActor();\n operation.operation = \"ModifyConfig\";\n operation.target = $event.target;\n //\n // Create operationWrapper\n //\n ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation);\n //\n // insert operationWrapper into memory\n //\n insert(operationWrapper);\n //\n Request request = new Request();\n request.CommonHeader = new CommonHeader();\n request.CommonHeader.RequestID = $event.requestID;\n request.Action = operation.operation;\n request.Payload = new HashMap<String, Object>();\n //\n // Fill in the payload\n // Hardcode genericVNF for now since AAI has not been ready for vFirewall demo case\n //\n String genericVNF = \"zdfw1fwl01pgn02\";\n request.Payload.put(\"generic-vnf.vnf-id\", genericVNF);\n //\n PGRequest pgRequest = new PGRequest();\n pgRequest.pgStreams = new PGStreams();\n \n PGStream pgStream;\n for(int i = 0; i < 5; i++){\n pgStream = new PGStream();\n pgStream.streamId = \"fw_udp\"+(i+1);\n pgStream.isEnabled = \"true\";\n pgRequest.pgStreams.pgStream.add(pgStream);\n }\n request.Payload.put(\"pg-streams\", pgRequest.pgStreams);\n \n if (request != null) {\n //\n // Insert request into memory\n //\n insert(request);\n //\n // Tell interested parties we are performing this Operation\n //\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.notification = ControlLoopNotificationType.OPERATION;\n // message and history ??\n notification.from = \"policy\";\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // Now send the operation request\n //\n if (request instanceof Request) {\n try {\n System.out.println(\"APPC request sent:\");\n System.out.println(Serialization.gsonPretty.toJson(request));\n PolicyEngine.manager.deliver($params.getAppcTopic(), request);\n } catch (Exception e) {\n e.printStackTrace();\n System.out.println(\"Can\'t deliver request: \" + request);\n }\n }\n } else {\n //\n // what happens if it is null\n //\n }\n }\n break;\n case \"MSO\":\n {\n //\n // Construct an operation\n //\n ControlLoopOperation operation = new ControlLoopOperation();\n operation.actor = $params.getActor();\n operation.operation = \"createModuleInstance\";\n operation.target = $event.target;\n //\n // Create operationWrapper\n //\n ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation);\n //\n // Construct an MSO request\n //\n MSORequest request = new MSORequest();\n request.requestDetails = new MSORequestDetails();\n request.requestDetails.modelInfo = new MSOModelInfo();\n request.requestDetails.cloudConfiguration = new MSOCloudConfiguration();\n request.requestDetails.requestInfo = new MSORequestInfo();\n request.requestDetails.requestParameters = new MSORequestParameters();\n request.requestDetails.requestParameters.userParams = null;\n //\n // cloudConfiguration\n //\n request.requestDetails.cloudConfiguration.lcpCloudRegionId = cloudRegionItemCloudRegionId;\n request.requestDetails.cloudConfiguration.tenantId = tenantItemTenantId;\n //\n // modelInfo\n //\n request.requestDetails.modelInfo.modelType = \"vfModule\";\n request.requestDetails.modelInfo.modelInvariantId = vfModuleItemPersonaModelId;\n request.requestDetails.modelInfo.modelNameVersionId = vfModuleItemModelNameVersionId;\n request.requestDetails.modelInfo.modelName = vfModuleItemModelName;\n request.requestDetails.modelInfo.modelVersion = vfModuleItemPersonaModelVersion;\n //\n // requestInfo\n //\n request.requestDetails.requestInfo.instanceName = vfModuleItemVfModuleName;\n request.requestDetails.requestInfo.source = \"POLICY\";\n request.requestDetails.requestInfo.suppressRollback = false;\n //\n // relatedInstanceList\n //\n MSORelatedInstanceListElement relatedInstanceListElement1 = new MSORelatedInstanceListElement();\n MSORelatedInstanceListElement relatedInstanceListElement2 = new MSORelatedInstanceListElement();\n relatedInstanceListElement1.relatedInstance = new MSORelatedInstance();\n relatedInstanceListElement2.relatedInstance = new MSORelatedInstance();\n //\n relatedInstanceListElement1.relatedInstance.instanceId = serviceItemServiceInstanceId;\n relatedInstanceListElement1.relatedInstance.modelInfo = new MSOModelInfo();\n relatedInstanceListElement1.relatedInstance.modelInfo.modelType = \"service\";\n relatedInstanceListElement1.relatedInstance.modelInfo.modelInvariantId = serviceItemPersonaModelId;\n relatedInstanceListElement1.relatedInstance.modelInfo.modelNameVersionId = serviceItemModelNameVersionId;\n relatedInstanceListElement1.relatedInstance.modelInfo.modelName = serviceItemModelName;\n relatedInstanceListElement1.relatedInstance.modelInfo.modelVersion = serviceItemModelVersion;\n //\n relatedInstanceListElement2.relatedInstance.instanceId = vnfItemVnfId;\n relatedInstanceListElement2.relatedInstance.modelInfo = new MSOModelInfo();\n relatedInstanceListElement2.relatedInstance.modelInfo.modelType = \"vnf\";\n relatedInstanceListElement2.relatedInstance.modelInfo.modelInvariantId = vnfItemPersonaModelId;\n relatedInstanceListElement2.relatedInstance.modelInfo.modelNameVersionId = vnfItemModelNameVersionId;\n relatedInstanceListElement2.relatedInstance.modelInfo.modelName = vnfItemModelName;\n relatedInstanceListElement2.relatedInstance.modelInfo.modelVersion = vnfItemModelVersion;\n relatedInstanceListElement2.relatedInstance.modelInfo.modelCustomizationName = vnfItemVnfType;\n // \n request.requestDetails.relatedInstanceList.add(relatedInstanceListElement1);\n request.requestDetails.relatedInstanceList.add(relatedInstanceListElement2);\n //\n // print MSO request for debug\n //\n System.out.println(\"MSO request sent:\");\n System.out.println(Serialization.gsonPretty.toJson(request));\n //\n //\n //\n if (request != null) {\n //\n // Tell interested parties we are performing this Operation\n //\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.notification = ControlLoopNotificationType.OPERATION;\n notification.from = \"policy\";\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // Concatenate serviceItemServiceInstanceId and vnfItemVnfId to msoURL\n //\n String MSOUrl = $params.getMsoURL() + \"/serviceInstances/v2/\" + serviceItemServiceInstanceId + \"/vnfs/\" + vnfItemVnfId + \"/vfModules\";\n //\n // Call MSO\n //\n MSOResponse response = MSOManager.createModuleInstance(MSOUrl, $params.getMsoURL(), $params.getMsoUsername(), $params.getMsoPassword(), request);\n //\n if (response != null) {\n //\n // Assign requestId\n //\n request.requestId = $event.requestID.toString(); \n response.request.requestId = $event.requestID.toString();\n //\n // Insert facts\n //\n insert(operationWrapper);\n insert(request);\n insert(response);\n } else {\n //\n // MSO request not even accepted\n //\n notification.message = operationWrapper.operation.toMessage();\n operationWrapper.operation.message = operationWrapper.operation.toMessage();\n operationWrapper.operation.outcome = \"FAILURE_EXCEPTION\";\n $manager.setControlLoopResult(\"FAILURE_EXCEPTION\");\n notification.history.add(operationWrapper.operation);\n notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n notification.notification = ControlLoopNotificationType.FINAL_FAILURE;\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // Retract everything\n //\n retract($event);\n retract($manager);\n }\n } else {\n System.err.println(\"constructed MSO request is invalid.\");\n }\n }\n break; \n } \nend\n \n/*\n*\n* This rule responds to APPC Response Events\n*\n*/\nrule \"BRMSParamvFWDemoPolicy.APPC.RESPONSE\"\n when\n $params : Params( getClosedLoopControlName() == \"CL-FRWL-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )\n $manager : EventManager( closedLoopControlName == $event.closedLoopControlName )\n $operationWrapper : ControlLoopOperationWrapper( requestID == $event.requestID )\n $request : Request( getCommonHeader().RequestID == $event.requestID )\n $response : Response( getCommonHeader().RequestID == $event.requestID ) \n then\n System.out.println(\"rule APPC.RESPONSE is triggered.\");\n if ($response.Status == null) {\n $operationWrapper.operation.outcome = \"FAILURE_EXCEPTION\";\n $manager.setControlLoopResult(\"FAILURE_EXCEPTION\");\n } \n //\n // Get the Response Code\n //\n ResponseCode code = ResponseCode.toResponseCode($response.Status.Code);\n if (code == null) {\n $operationWrapper.operation.outcome = \"FAILURE_EXCEPTION\";\n $manager.setControlLoopResult(\"FAILURE_EXCEPTION\");\n }\n //\n // Construct notification\n //\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.from = \"policy\";\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n notification.message = $operationWrapper.operation.toMessage();\n $operationWrapper.operation.message = $operationWrapper.operation.toMessage();\n //\n // Ok, let\'s figure out what APP-C\'s response is\n //\n switch (code) {\n case ACCEPT:\n $operationWrapper.operation.outcome = \"PROCESSING\";\n break;\n case ERROR:\n case REJECT:\n $operationWrapper.operation.outcome = \"FAILURE_EXCEPTION\";\n $manager.setControlLoopResult(\"FAILURE_EXCEPTION\");\n break;\n case SUCCESS:\n $operationWrapper.operation.outcome = \"SUCCESS\";\n $manager.setControlLoopResult(\"SUCCESS\");\n break;\n case FAILURE:\n $operationWrapper.operation.outcome = \"FAILURE\";\n $manager.setControlLoopResult(\"FAILURE\");\n break;\n }\n if ($operationWrapper.operation.outcome.equals(\"SUCCESS\")) {\n notification.history.add($operationWrapper.operation);\n notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n notification.notification = ControlLoopNotificationType.FINAL_SUCCESS;\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n\n //\n // We are going to retract these objects from memory\n //\n System.out.println(\"Retracting everything\");\n retract($operationWrapper);\n retract($request);\n retract($response);\n retract($event);\n retract($manager);\n } else if ($operationWrapper.operation.outcome.equals(\"PROCESSING\")) {\n retract($response);\n } else {\n notification.history.add($operationWrapper.operation);\n notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n notification.notification = ControlLoopNotificationType.FINAL_FAILURE;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // We are going to retract these objects from memory\n //\n System.out.println(\"Retracting everything\");\n retract($operationWrapper);\n retract($request);\n retract($response);\n retract($event);\n retract($manager);\n }\n \nend \n\n/*\n*\n* This rule is used to clean up APPC response\n*\n*/ \nrule \"BRMSParamvFWDemoPolicy.APPC.RESPONSE.CLEANUP\"\n when\n $params : Params( getClosedLoopControlName() == \"CL-FRWL-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $response : Response($id : getCommonHeader().RequestID )\n not ( VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), requestID == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) ) \n then\n System.out.println(\"rule APPC.RESPONSE.CLEANUP is triggered.\");\n retract($response);\nend\n\n/*\n*\n* This rule responds to MSO Response Events\n*\n*/\nrule \"BRMSParamvFWDemoPolicy.MSO.RESPONSE\"\n when\n $params : Params( getClosedLoopControlName() == \"CL-FRWL-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )\n $manager : EventManager( closedLoopControlName == $event.closedLoopControlName )\n $operationWrapper : ControlLoopOperationWrapper( requestID == $event.requestID )\n $request : MSORequest( requestId == $event.requestID.toString() )\n $response : MSOResponse( request.requestId == $event.requestID.toString() ) \n then\n System.out.println(\"rule MSO.RESPONSE is triggered.\");\n //\n // Construct notification\n //\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.from = \"policy\";\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n notification.message = $operationWrapper.operation.toMessage();\n $operationWrapper.operation.message = $operationWrapper.operation.toMessage();\n //\n // The operation can either be succeeded or failed\n // \n if($response.request.requestStatus.requestState.equals(\"COMPLETE\")) {\n $operationWrapper.operation.outcome = \"SUCCESS\";\n $manager.setControlLoopResult(\"SUCCESS\");\n notification.history.add($operationWrapper.operation);\n notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n notification.notification = ControlLoopNotificationType.FINAL_SUCCESS;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // We are going to retract these objects from memory\n //\n System.out.println(\"Retracting everything\");\n retract($operationWrapper);\n retract($request);\n retract($response);\n retract($event);\n retract($manager);\n } else {\n $operationWrapper.operation.outcome = \"FAILURE\";\n $manager.setControlLoopResult(\"FAILURE\");\n notification.history.add($operationWrapper.operation);\n notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n notification.notification = ControlLoopNotificationType.FINAL_FAILURE;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // We are going to retract these objects from memory\n //\n System.out.println(\"Retracting everything\");\n retract($operationWrapper);\n retract($request);\n retract($response);\n retract($event);\n retract($manager);\n }\n \nend \nrule \"com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.Params\" \n salience 1000 \n when\n then\n Params params = new Params();\n params.setAaiPatternMatch(1);\n params.setAppcTopic(\"APPC-CL\");\n params.setAaiURL(\"null\");\n params.setMsoPassword(\"null\");\n params.setClosedLoopControlName(\"CL-FRWL-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\");\n params.setMsoURL(\"null\");\n params.setAaiUsername(\"null\");\n params.setActor(\"APPC\");\n params.setMsoUsername(\"null\");\n params.setAaiNamedQueryUUID(\"null\");\n params.setAaiPassword(\"null\");\n params.setNotificationTopic(\"POLICY-CL-MGT\");\n insert(params);\nend\r\n','OTHER','com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt','doACPolicyPut','2017-03-14 19:58:19',0,'','doACPolicyPut','2017-03-14 19:58:19',1),(3203,'/* Autogenerated Code Please Don\'t change/remove this comment section. This is for the UI purpose. \n <$%BRMSParamTemplate=ControlLoopDemo__closedLoopControlName%$> \n */ \n\r\n\r\n/*-\n * ============LICENSE_START=======================================================\n * archetype-closed-loop-demo-rules\n * ================================================================================\n * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\n * ================================================================================\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * ============LICENSE_END=========================================================\n */\n\npackage org.openecomp.policy.controlloop;\n\nimport java.util.List;\nimport java.util.LinkedList;\nimport java.util.Map;\nimport java.util.HashMap;\nimport java.util.UUID;\n\nimport org.openecomp.policy.controlloop.VirtualControlLoopEvent;\nimport org.openecomp.policy.controlloop.ControlLoopEventStatus;\nimport org.openecomp.policy.controlloop.VirtualControlLoopNotification;\nimport org.openecomp.policy.controlloop.ControlLoopNotificationType;\nimport org.openecomp.policy.controlloop.ControlLoopOperation;\nimport org.openecomp.policy.controlloop.ControlLoopOperationWrapper;\nimport org.openecomp.policy.template.demo.ControlLoopException;\n\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199CloudRegion;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199ExtraProperties;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199ExtraProperty;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199GenericVNF;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199InstanceFilters;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199InventoryResponseItem;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199InventoryResponseItems;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199Manager;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199NamedQuery;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199QueryParameters;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199Request;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199RequestWrapper;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199Response;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199ResponseWrapper;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199ServiceInstance;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199Tenant;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199VfModule;\nimport org.openecomp.policy.aai.AAINQF199.AAINQF199VServer;\nimport org.openecomp.policy.aai.util.Serialization;\n\nimport org.openecomp.policy.appc.CommonHeader;\nimport org.openecomp.policy.appc.Request;\nimport org.openecomp.policy.appc.Response;\nimport org.openecomp.policy.appc.ResponseCode;\nimport org.openecomp.policy.appc.ResponseStatus;\nimport org.openecomp.policy.appc.ResponseValue;\n\nimport org.openecomp.policy.template.demo.EventManager;\nimport org.openecomp.policy.vnf.trafficgenerator.PGRequest;\nimport org.openecomp.policy.vnf.trafficgenerator.PGStream;\nimport org.openecomp.policy.vnf.trafficgenerator.PGStreams;\n\nimport org.openecomp.policy.mso.MSOManager;\nimport org.openecomp.policy.mso.MSORequest;\nimport org.openecomp.policy.mso.MSORequestStatus;\nimport org.openecomp.policy.mso.MSORequestDetails;\nimport org.openecomp.policy.mso.MSOModelInfo;\nimport org.openecomp.policy.mso.MSOCloudConfiguration;\nimport org.openecomp.policy.mso.MSORequestInfo;\nimport org.openecomp.policy.mso.MSORequestParameters;\nimport org.openecomp.policy.mso.MSORelatedInstanceListElement;\nimport org.openecomp.policy.mso.MSORelatedInstance;\nimport org.openecomp.policy.mso.MSOResponse;\n\nimport org.openecomp.policy.drools.system.PolicyEngine;\n\n//\n// These parameters are required to build the runtime policy\n//\ndeclare Params\n closedLoopControlName : String\n actor : String\n aaiURL : String\n aaiUsername : String\n aaiPassword : String\n msoURL : String\n msoUsername : String\n msoPassword : String\n aaiNamedQueryUUID : String\n aaiPatternMatch : int \n notificationTopic : String\n appcTopic : String\nend\n\n/*\n*\n* Called once and only once to insert the parameters into working memory for this Closed Loop policy.\n* (Comment SETUP rule out for the first ECOMP opensource release since policy BRMS_GW already puts a Params fact in there)\n*\n*\n*rule \"BRMSParamvLBDemoPolicy.SETUP\"\n* when\n* then\n* System.out.println(\"rule SETUP is triggered.\");\n* Params params = new Params();\n* params.setClosedLoopControlName(\"CL-DNS-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\");\n* params.setActor(\"MSO\");\n* params.setAaiURL(\"https://aai.api.simpledemo.openecomp.org:8443\");\n* params.setAaiUsername(\"POLICY\");\n* params.setAaiPassword(\"POLICY\");\n* params.setMsoURL(\"http://vm1.mso.simpledemo.openecomp.org:8080/ecomp/mso/infra\");\n* params.setMsoUsername(\"InfraPortalClient\");\n* params.setMsoPassword(\"password1$\");\n* params.setAaiNamedQueryUUID(\"f199cb88-5e69-4b1f-93e0-6f257877d066\");\n* params.setAaiPatternMatch(0);\n* params.setNotificationTopic(\"POLICY-CL-MGT\");\n* params.setAppcTopic(\"APPC-CL\");\n* //\n* // This stays in memory as long as the rule is alive and running\n* //\n* insert(params);\n*end\n*/\n/*\n*\n* This rule responds to DCAE Events\n*\n*/\nrule \"BRMSParamvLBDemoPolicy.EVENT\"\n when\n $params : Params( getClosedLoopControlName() == \"CL-DNS-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )\n not ( EventManager( closedLoopControlName == $event.closedLoopControlName ))\n then\n System.out.println(\"rule EVENT is triggered.\");\n try {\n // \n // Check the requestID in the event to make sure it is not null before we create the EventManager. \n // The EventManager will do extra syntax checking as well check if the closed loop is disabled/\n //\n if ($event.requestID == null) {\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.notification = ControlLoopNotificationType.REJECTED;\n notification.from = \"policy\";\n notification.message = \"Missing requestID from DCAE event\";\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n e.printStackTrace();\n System.out.println(\"Can\'t deliver notification: \" + notification);\n }\n //\n // Retract it from memory\n //\n retract($event);\n System.out.println(\"Event with requestID=null has been retracted.\");\n } else {\n //\n // Create an EventManager\n //\n EventManager manager = new EventManager($params.getClosedLoopControlName(), $event.requestID, $event.target);\n //\n // Determine if EventManager can actively process the event (i.e. syntax)\n //\n VirtualControlLoopNotification notification = manager.activate($event);\n notification.from = \"policy\"; \n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n //\n // Are we actively pursuing this event?\n //\n if (notification.notification == ControlLoopNotificationType.ACTIVE) {\n //\n // Insert Event Manager into memory, this will now kick off processing.\n //\n insert(manager);\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n e.printStackTrace();\n System.out.println(\"Can\'t deliver notification: \" + notification);\n } \n } else {\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n e.printStackTrace();\n System.out.println(\"Can\'t deliver notification: \" + notification);\n }\n //\n // Retract it from memory\n //\n retract($event);\n }\n //\n // Now that the manager is inserted into Drools working memory, we\'ll wait for\n // another rule to fire in order to continue processing. This way we can also\n // then screen for additional ONSET and ABATED events for this same RequestIDs \n // and for different RequestIDs but with the same closedLoopControlName and target.\n //\n }\n //\n } catch (Exception e) {\n e.printStackTrace();\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.notification = ControlLoopNotificationType.REJECTED;\n notification.message = \"Exception occurred \" + e.getMessage();\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n //\n //\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e1) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e1.printStackTrace();\n }\n //\n // Retract the event\n //\n retract($event);\n }\nend\n\n/*\n*\n* This rule happens when we got a valid ONSET, closed loop is enabled and an Event Manager\n* is created. We can start the operations for this closed loop.\n*\n*/\nrule \"BRMSParamvLBDemoPolicy.EVENT.MANAGER\"\n when\n $params : Params( getClosedLoopControlName() == \"CL-DNS-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )\n $manager : EventManager( closedLoopControlName == $event.closedLoopControlName, controlLoopResult == null)\n then\n System.out.println(\"rule EVENT.MANAGER is triggered.\");\n //\n // Check which event this is.\n //\n EventManager.NEW_EVENT_STATUS eventStatus = $manager.onNewEvent($event);\n //\n // We only want the initial ONSET event in memory,\n // all the other events need to be retracted to support\n // cleanup and avoid the other rules being fired for this event.\n //\n if (eventStatus != EventManager.NEW_EVENT_STATUS.FIRST_ONSET) {\n System.out.println(\"Retracting \"+eventStatus+\" Event.\");\n retract($event);\n return;\n }\n //\n // Now the event in memory is first onset event\n //\n try {\n //\n // Pull the known AAI field from the Event\n //\n // generic-vnf is needed for vFirewall case\n // vserver-name is needed for vLoadBalancer case\n //\n String genericVNF = $event.AAI.get(\"generic-vnf.vnf-id\");\n String vserver = $event.AAI.get(\"vserver.vserver-name\");\n //\n // Check if we are implementing a simple pattern match.\n //\n if ($params.getAaiPatternMatch() == 1) {\n //\n // Yes\n //\n //Basic naming characteristics:\n //VF Name (9 char)+VM name (13 char total)+VFC (19 char total)\n //Example: \n //VF Name (9 characters): cscf0001v\n //VM Name(13 characters): cscf0001vm001\n //VFC name(19 characters): cscf0001vm001cfg001\n //\n // zdfw1fwl01fwl02 or zdfw1fwl01fwl01 \n // replaced with\n // zdfw1fwl01pgn02 or zdfw1fwl01pgn01\n //\n int index = genericVNF.lastIndexOf(\"fwl\");\n if (index == -1) {\n System.err.println(\"The generic-vnf.vnf-id from DCAE Event is not valid.\");\n } else {\n genericVNF = genericVNF.substring(0, index) + \"pgn\" + genericVNF.substring(index+\"fwl\".length());\n }\n //\n // Construct an APPC request\n //\n ControlLoopOperation operation = new ControlLoopOperation();\n operation.actor = $params.getActor();\n operation.operation = \"ModifyConfig\";\n operation.target = $event.target;\n //\n // Create operationWrapper\n //\n ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation);\n //\n // insert operationWrapper into memory\n //\n insert(operationWrapper);\n //\n Request request = new Request();\n request.CommonHeader = new CommonHeader();\n request.CommonHeader.RequestID = $event.requestID;\n request.Action = operation.operation;\n request.Payload = new HashMap<String, Object>();\n //\n // Fill in the payload\n //\n request.Payload.put(\"generic-vnf.vnf-id\", genericVNF);\n //\n PGRequest pgRequest = new PGRequest();\n pgRequest.pgStreams = new PGStreams();\n \n PGStream pgStream;\n for(int i = 0; i < 5; i++){\n pgStream = new PGStream();\n pgStream.streamId = \"fw_udp\"+(i+1);\n pgStream.isEnabled = \"true\";\n pgRequest.pgStreams.pgStream.add(pgStream);\n }\n request.Payload.put(\"pg-streams\", pgRequest.pgStreams);\n \n if (request != null) {\n //\n // Insert request into memory\n //\n insert(request);\n //\n // Tell interested parties we are performing this Operation\n //\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.notification = ControlLoopNotificationType.OPERATION;\n // message and history ??\n notification.from = \"policy\";\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // Now send the operation request\n //\n if (request instanceof Request) {\n try {\n System.out.println(\"APPC request sent:\");\n System.out.println(Serialization.gsonPretty.toJson(request));\n PolicyEngine.manager.deliver($params.getAppcTopic(), request);\n } catch (Exception e) {\n e.printStackTrace();\n System.out.println(\"Can\'t deliver request: \" + request);\n }\n }\n } else {\n //\n // what happens if it is null\n //\n }\n //\n } else {\n //\n // create AAI named-query request with UUID started with \"F199\"\n //\n AAINQF199Request aainqf199request = new AAINQF199Request();\n AAINQF199QueryParameters aainqf199queryparam = new AAINQF199QueryParameters();\n AAINQF199NamedQuery aainqf199namedquery = new AAINQF199NamedQuery();\n AAINQF199InstanceFilters aainqf199instancefilter = new AAINQF199InstanceFilters();\n //\n // queryParameters\n //\n aainqf199namedquery.namedQueryUUID = UUID.fromString($params.getAaiNamedQueryUUID()); \n aainqf199queryparam.namedQuery = aainqf199namedquery;\n aainqf199request.queryParameters = aainqf199queryparam;\n //\n // instanceFilters\n //\n Map aainqf199instancefiltermap = new HashMap();\n Map aainqf199instancefiltermapitem = new HashMap();\n aainqf199instancefiltermapitem.put(\"vserver-name\", vserver); \n aainqf199instancefiltermap.put(\"vserver\", aainqf199instancefiltermapitem);\n aainqf199instancefilter.instanceFilter.add(aainqf199instancefiltermap);\n aainqf199request.instanceFilters = aainqf199instancefilter;\n //\n // print aainqf199request for debug\n //\n System.out.println(\"AAI Request sent:\");\n System.out.println(Serialization.gsonPretty.toJson(aainqf199request));\n //\n // Create AAINQF199RequestWrapper\n //\n AAINQF199RequestWrapper aainqf199RequestWrapper = new AAINQF199RequestWrapper($event.requestID, aainqf199request);\n //\n // insert aainqf199request into memory\n //\n insert(aainqf199RequestWrapper);\n }\n //\n } catch (Exception e) {\n e.printStackTrace();\n }\nend\n\n/*\n*\n* This rule happens when we got a valid ONSET, closed loop is enabled, an Event Manager\n* is created, AAI Manager and AAI Request are ready in memory. We can start sending query to AAI and then wait for response.\n*\n*/\nrule \"BRMSParamvLBDemoPolicy.EVENT.MANAGER.AAINQF199REQUEST\"\n when\n $params : Params( getClosedLoopControlName() == \"CL-DNS-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )\n $manager : EventManager( closedLoopControlName == $event.closedLoopControlName )\n $aainqf199RequestWrapper : AAINQF199RequestWrapper(requestID == $event.requestID)\n then\n System.out.println(\"rule EVENT.MANAGER.AAINQF199REQUEST is triggered.\");\n //\n // send the request\n //\n AAINQF199Response aainqf199response = AAINQF199Manager.postQuery($params.getAaiURL(), $params.getAaiUsername(), $params.getAaiPassword(),\n $aainqf199RequestWrapper.aainqf199request, $event.requestID);\n //\n // Check AAI response\n //\n if (aainqf199response == null) {\n System.err.println(\"Failed to get AAI response\");\n //\n // Fail and retract everything\n //\n retract($event);\n retract($manager);\n retract($aainqf199RequestWrapper);\n } else {\n //\n // Create AAINQF199ResponseWrapper\n //\n AAINQF199ResponseWrapper aainqf199ResponseWrapper = new AAINQF199ResponseWrapper($event.requestID, aainqf199response);\n //\n // insert aainqf199ResponseWrapper to memeory\n //\n insert(aainqf199ResponseWrapper);\n }\nend\n\n/*\n*\n* This rule happens when we got a valid AAI response. We can start sending request to APPC or MSO now.\n*\n*/\nrule \"BRMSParamvLBDemoPolicy.EVENT.MANAGER.AAINQF199RESPONSE\"\n when \n $params : Params( getClosedLoopControlName() == \"CL-DNS-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )\n $manager : EventManager( closedLoopControlName == $event.closedLoopControlName )\n $aainqf199RequestWrapper : AAINQF199RequestWrapper(requestID == $event.requestID)\n $aainqf199ResponseWrapper : AAINQF199ResponseWrapper(requestID == $event.requestID)\n then\n System.out.println(\"rule EVENT.MANAGER.AAINQF199RESPONSE is triggered.\");\n //\n // Extract related fields out of AAINQF199RESPONSE\n //\n String vnfItemVnfId, vnfItemVnfType, vnfItemPersonaModelId, vnfItemPersonaModelVersion, vnfItemModelName, \n vnfItemModelVersion, vnfItemModelNameVersionId, serviceItemServiceInstanceId, serviceItemPersonaModelId,\n serviceItemModelName, serviceItemModelType, serviceItemModelVersion, serviceItemModelNameVersionId,\n vfModuleItemVfModuleName, vfModuleItemPersonaModelId, vfModuleItemPersonaModelVersion, vfModuleItemModelName, \n vfModuleItemModelNameVersionId, tenantItemTenantId, cloudRegionItemCloudRegionId;\n try {\n //\n // vnfItem\n //\n vnfItemVnfId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.vnfID;\n vnfItemVnfType = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.vnfType;\n vnfItemVnfType = vnfItemVnfType.substring(vnfItemVnfType.lastIndexOf(\"/\")+1);\n vnfItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.personaModelId;\n vnfItemPersonaModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.personaModelVersion;\n vnfItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(0).propertyValue;\n vnfItemModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(2).propertyValue;\n vnfItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(4).propertyValue;\n //\n // serviceItem\n //\n serviceItemServiceInstanceId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.serviceInstanceID;\n serviceItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.personaModelId;\n serviceItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(0).propertyValue;\n serviceItemModelType = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(1).propertyValue;\n serviceItemModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.personaModelVersion;\n serviceItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(4).propertyValue;\n //\n // Find the index for base vf module and non-base vf module\n //\n int baseIndex = -1;\n int nonBaseIndex = -1;\n List<AAINQF199InventoryResponseItem> inventoryItems = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems;\n for (AAINQF199InventoryResponseItem m : inventoryItems) {\n if (m.vfModule != null && m.vfModule.isBaseVfModule == true) {\n baseIndex = inventoryItems.indexOf(m);\n } else if (m.vfModule != null && m.vfModule.isBaseVfModule == false && m.vfModule.orchestrationStatus == null) {\n nonBaseIndex = inventoryItems.indexOf(m);\n }\n //\n if (baseIndex != -1 && nonBaseIndex != -1) {\n break;\n }\n }\n //\n // Report the error if either base vf module or non-base vf module is not found\n //\n if (baseIndex == -1 || nonBaseIndex == -1) {\n System.err.println(\"Either base or non-base vf module is not found from AAI response.\");\n retract($aainqf199RequestWrapper);\n retract($aainqf199ResponseWrapper);\n retract($manager);\n retract($event);\n return;\n }\n //\n // This comes from the base module\n //\n vfModuleItemVfModuleName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(baseIndex).vfModule.vfModuleName;\n vfModuleItemVfModuleName = vfModuleItemVfModuleName.replace(\"Vfmodule\", \"vDNS\");\n //\n // vfModuleItem - NOT the base module\n //\n vfModuleItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).vfModule.personaModelId;\n vfModuleItemPersonaModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).vfModule.personaModelVersion;\n vfModuleItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).extraProperties.extraProperty.get(0).propertyValue;\n vfModuleItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).extraProperties.extraProperty.get(4).propertyValue;\n //\n // tenantItem\n //\n tenantItemTenantId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(1).tenant.tenantId;\n //\n // cloudRegionItem\n //\n cloudRegionItemCloudRegionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(1).items.inventoryResponseItems.get(0).cloudRegion.cloudRegionId;\n //\n } catch (Exception e) {\n e.printStackTrace();\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.notification = ControlLoopNotificationType.REJECTED;\n notification.message = \"Exception occurred \" + e.getMessage();\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e1) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e1.printStackTrace();\n }\n //\n notification.notification = ControlLoopNotificationType.FINAL_FAILURE;\n notification.message = \"Invalid named-query response from AAI\";\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e1) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e1.printStackTrace();\n }\n //\n // Retract everything\n //\n retract($aainqf199RequestWrapper);\n retract($aainqf199ResponseWrapper);\n retract($manager);\n retract($event);\n return;\n } \n //\n // Extracted fields should not be null\n //\n if ((vnfItemVnfId == null) || (vnfItemVnfType == null) ||\n (vnfItemPersonaModelId == null) || (vnfItemModelName == null) ||\n (vnfItemModelVersion == null) || (vnfItemModelNameVersionId == null) ||\n (serviceItemServiceInstanceId == null) || (serviceItemModelName == null) ||\n (serviceItemModelType == null) || (serviceItemModelVersion == null) ||\n (serviceItemModelNameVersionId == null) || (vfModuleItemVfModuleName == null) ||\n (vfModuleItemPersonaModelId == null) || (vfModuleItemPersonaModelVersion == null) ||\n (vfModuleItemModelName == null) || (vfModuleItemModelNameVersionId == null) ||\n (tenantItemTenantId == null) || (cloudRegionItemCloudRegionId == null)) {\n //\n System.err.println(\"some fields are missing from AAI response.\");\n //\n // Fail and retract everything\n //\n retract($aainqf199RequestWrapper);\n retract($aainqf199ResponseWrapper);\n retract($manager);\n retract($event);\n return;\n }\n //\n // We don\'t need them any more\n //\n retract($aainqf199ResponseWrapper);\n retract($aainqf199RequestWrapper); \n //\n // check the actor of this closed loop\n //\n switch ($params.getActor()) {\n case \"APPC\":\n {\n //\n // Construct an APPC request\n //\n ControlLoopOperation operation = new ControlLoopOperation();\n operation.actor = $params.getActor();\n operation.operation = \"ModifyConfig\";\n operation.target = $event.target;\n //\n // Create operationWrapper\n //\n ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation);\n //\n // insert operationWrapper into memory\n //\n insert(operationWrapper);\n //\n Request request = new Request();\n request.CommonHeader = new CommonHeader();\n request.CommonHeader.RequestID = $event.requestID;\n request.Action = operation.operation;\n request.Payload = new HashMap<String, Object>();\n //\n // Fill in the payload\n // Hardcode genericVNF for now since AAI has not been ready for vFirewall demo case\n //\n String genericVNF = \"zdfw1fwl01pgn02\";\n request.Payload.put(\"generic-vnf.vnf-id\", genericVNF);\n //\n PGRequest pgRequest = new PGRequest();\n pgRequest.pgStreams = new PGStreams();\n \n PGStream pgStream;\n for(int i = 0; i < 5; i++){\n pgStream = new PGStream();\n pgStream.streamId = \"fw_udp\"+(i+1);\n pgStream.isEnabled = \"true\";\n pgRequest.pgStreams.pgStream.add(pgStream);\n }\n request.Payload.put(\"pg-streams\", pgRequest.pgStreams);\n \n if (request != null) {\n //\n // Insert request into memory\n //\n insert(request);\n //\n // Tell interested parties we are performing this Operation\n //\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.notification = ControlLoopNotificationType.OPERATION;\n // message and history ??\n notification.from = \"policy\";\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // Now send the operation request\n //\n if (request instanceof Request) {\n try {\n System.out.println(\"APPC request sent:\");\n System.out.println(Serialization.gsonPretty.toJson(request));\n PolicyEngine.manager.deliver($params.getAppcTopic(), request);\n } catch (Exception e) {\n e.printStackTrace();\n System.out.println(\"Can\'t deliver request: \" + request);\n }\n }\n } else {\n //\n // what happens if it is null\n //\n }\n }\n break;\n case \"MSO\":\n {\n //\n // Construct an operation\n //\n ControlLoopOperation operation = new ControlLoopOperation();\n operation.actor = $params.getActor();\n operation.operation = \"createModuleInstance\";\n operation.target = $event.target;\n //\n // Create operationWrapper\n //\n ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation);\n //\n // Construct an MSO request\n //\n MSORequest request = new MSORequest();\n request.requestDetails = new MSORequestDetails();\n request.requestDetails.modelInfo = new MSOModelInfo();\n request.requestDetails.cloudConfiguration = new MSOCloudConfiguration();\n request.requestDetails.requestInfo = new MSORequestInfo();\n request.requestDetails.requestParameters = new MSORequestParameters();\n request.requestDetails.requestParameters.userParams = null;\n //\n // cloudConfiguration\n //\n request.requestDetails.cloudConfiguration.lcpCloudRegionId = cloudRegionItemCloudRegionId;\n request.requestDetails.cloudConfiguration.tenantId = tenantItemTenantId;\n //\n // modelInfo\n //\n request.requestDetails.modelInfo.modelType = \"vfModule\";\n request.requestDetails.modelInfo.modelInvariantId = vfModuleItemPersonaModelId;\n request.requestDetails.modelInfo.modelNameVersionId = vfModuleItemModelNameVersionId;\n request.requestDetails.modelInfo.modelName = vfModuleItemModelName;\n request.requestDetails.modelInfo.modelVersion = vfModuleItemPersonaModelVersion;\n //\n // requestInfo\n //\n request.requestDetails.requestInfo.instanceName = vfModuleItemVfModuleName;\n request.requestDetails.requestInfo.source = \"POLICY\";\n request.requestDetails.requestInfo.suppressRollback = false;\n //\n // relatedInstanceList\n //\n MSORelatedInstanceListElement relatedInstanceListElement1 = new MSORelatedInstanceListElement();\n MSORelatedInstanceListElement relatedInstanceListElement2 = new MSORelatedInstanceListElement();\n relatedInstanceListElement1.relatedInstance = new MSORelatedInstance();\n relatedInstanceListElement2.relatedInstance = new MSORelatedInstance();\n //\n relatedInstanceListElement1.relatedInstance.instanceId = serviceItemServiceInstanceId;\n relatedInstanceListElement1.relatedInstance.modelInfo = new MSOModelInfo();\n relatedInstanceListElement1.relatedInstance.modelInfo.modelType = \"service\";\n relatedInstanceListElement1.relatedInstance.modelInfo.modelInvariantId = serviceItemPersonaModelId;\n relatedInstanceListElement1.relatedInstance.modelInfo.modelNameVersionId = serviceItemModelNameVersionId;\n relatedInstanceListElement1.relatedInstance.modelInfo.modelName = serviceItemModelName;\n relatedInstanceListElement1.relatedInstance.modelInfo.modelVersion = serviceItemModelVersion;\n //\n relatedInstanceListElement2.relatedInstance.instanceId = vnfItemVnfId;\n relatedInstanceListElement2.relatedInstance.modelInfo = new MSOModelInfo();\n relatedInstanceListElement2.relatedInstance.modelInfo.modelType = \"vnf\";\n relatedInstanceListElement2.relatedInstance.modelInfo.modelInvariantId = vnfItemPersonaModelId;\n relatedInstanceListElement2.relatedInstance.modelInfo.modelNameVersionId = vnfItemModelNameVersionId;\n relatedInstanceListElement2.relatedInstance.modelInfo.modelName = vnfItemModelName;\n relatedInstanceListElement2.relatedInstance.modelInfo.modelVersion = vnfItemModelVersion;\n relatedInstanceListElement2.relatedInstance.modelInfo.modelCustomizationName = vnfItemVnfType;\n // \n request.requestDetails.relatedInstanceList.add(relatedInstanceListElement1);\n request.requestDetails.relatedInstanceList.add(relatedInstanceListElement2);\n //\n // print MSO request for debug\n //\n System.out.println(\"MSO request sent:\");\n System.out.println(Serialization.gsonPretty.toJson(request));\n //\n //\n //\n if (request != null) {\n //\n // Tell interested parties we are performing this Operation\n //\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.notification = ControlLoopNotificationType.OPERATION;\n notification.from = \"policy\";\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // Concatenate serviceItemServiceInstanceId and vnfItemVnfId to msoURL\n //\n String MSOUrl = $params.getMsoURL() + \"/serviceInstances/v2/\" + serviceItemServiceInstanceId + \"/vnfs/\" + vnfItemVnfId + \"/vfModules\";\n //\n // Call MSO\n //\n MSOResponse response = MSOManager.createModuleInstance(MSOUrl, $params.getMsoURL(), $params.getMsoUsername(), $params.getMsoPassword(), request);\n //\n if (response != null) {\n //\n // Assign requestId\n //\n request.requestId = $event.requestID.toString(); \n response.request.requestId = $event.requestID.toString();\n //\n // Insert facts\n //\n insert(operationWrapper);\n insert(request);\n insert(response);\n } else {\n //\n // MSO request not even accepted\n //\n notification.message = operationWrapper.operation.toMessage();\n operationWrapper.operation.message = operationWrapper.operation.toMessage();\n operationWrapper.operation.outcome = \"FAILURE_EXCEPTION\";\n $manager.setControlLoopResult(\"FAILURE_EXCEPTION\");\n notification.history.add(operationWrapper.operation);\n notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n notification.notification = ControlLoopNotificationType.FINAL_FAILURE;\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // Retract everything\n //\n retract($event);\n retract($manager);\n }\n } else {\n System.err.println(\"constructed MSO request is invalid.\");\n }\n }\n break; \n } \nend\n \n/*\n*\n* This rule responds to APPC Response Events\n*\n*/\nrule \"BRMSParamvLBDemoPolicy.APPC.RESPONSE\"\n when\n $params : Params( getClosedLoopControlName() == \"CL-DNS-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )\n $manager : EventManager( closedLoopControlName == $event.closedLoopControlName )\n $operationWrapper : ControlLoopOperationWrapper( requestID == $event.requestID )\n $request : Request( getCommonHeader().RequestID == $event.requestID )\n $response : Response( getCommonHeader().RequestID == $event.requestID ) \n then\n System.out.println(\"rule APPC.RESPONSE is triggered.\");\n if ($response.Status == null) {\n $operationWrapper.operation.outcome = \"FAILURE_EXCEPTION\";\n $manager.setControlLoopResult(\"FAILURE_EXCEPTION\");\n } \n //\n // Get the Response Code\n //\n ResponseCode code = ResponseCode.toResponseCode($response.Status.Code);\n if (code == null) {\n $operationWrapper.operation.outcome = \"FAILURE_EXCEPTION\";\n $manager.setControlLoopResult(\"FAILURE_EXCEPTION\");\n }\n //\n // Construct notification\n //\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.from = \"policy\";\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n notification.message = $operationWrapper.operation.toMessage();\n $operationWrapper.operation.message = $operationWrapper.operation.toMessage();\n //\n // Ok, let\'s figure out what APP-C\'s response is\n //\n switch (code) {\n case ACCEPT:\n $operationWrapper.operation.outcome = \"PROCESSING\";\n break;\n case ERROR:\n case REJECT:\n $operationWrapper.operation.outcome = \"FAILURE_EXCEPTION\";\n $manager.setControlLoopResult(\"FAILURE_EXCEPTION\");\n break;\n case SUCCESS:\n $operationWrapper.operation.outcome = \"SUCCESS\";\n $manager.setControlLoopResult(\"SUCCESS\");\n break;\n case FAILURE:\n $operationWrapper.operation.outcome = \"FAILURE\";\n $manager.setControlLoopResult(\"FAILURE\");\n break;\n }\n if ($operationWrapper.operation.outcome.equals(\"SUCCESS\")) {\n notification.history.add($operationWrapper.operation);\n notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n notification.notification = ControlLoopNotificationType.FINAL_SUCCESS;\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n\n //\n // We are going to retract these objects from memory\n //\n System.out.println(\"Retracting everything\");\n retract($operationWrapper);\n retract($request);\n retract($response);\n retract($event);\n retract($manager);\n } else if ($operationWrapper.operation.outcome.equals(\"PROCESSING\")) {\n retract($response);\n } else {\n notification.history.add($operationWrapper.operation);\n notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n notification.notification = ControlLoopNotificationType.FINAL_FAILURE;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // We are going to retract these objects from memory\n //\n System.out.println(\"Retracting everything\");\n retract($operationWrapper);\n retract($request);\n retract($response);\n retract($event);\n retract($manager);\n }\n \nend \n\n/*\n*\n* This rule is used to clean up APPC response\n*\n*/ \nrule \"BRMSParamvLBDemoPolicy.APPC.RESPONSE.CLEANUP\"\n when\n $params : Params( getClosedLoopControlName() == \"CL-DNS-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $response : Response($id : getCommonHeader().RequestID )\n not ( VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), requestID == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) ) \n then\n System.out.println(\"rule APPC.RESPONSE.CLEANUP is triggered.\");\n retract($response);\nend\n\n/*\n*\n* This rule responds to MSO Response Events\n*\n*/\nrule \"BRMSParamvLBDemoPolicy.MSO.RESPONSE\"\n when\n $params : Params( getClosedLoopControlName() == \"CL-DNS-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\" )\n $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET )\n $manager : EventManager( closedLoopControlName == $event.closedLoopControlName )\n $operationWrapper : ControlLoopOperationWrapper( requestID == $event.requestID )\n $request : MSORequest( requestId == $event.requestID.toString() )\n $response : MSOResponse( request.requestId == $event.requestID.toString() ) \n then\n System.out.println(\"rule MSO.RESPONSE is triggered.\");\n //\n // Construct notification\n //\n VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event);\n notification.from = \"policy\";\n notification.policyName = drools.getRule().getName();\n notification.policyScope = \"com\";\n notification.policyVersion = \"1\";\n notification.message = $operationWrapper.operation.toMessage();\n $operationWrapper.operation.message = $operationWrapper.operation.toMessage();\n //\n // The operation can either be succeeded or failed\n // \n if($response.request.requestStatus.requestState.equals(\"COMPLETE\")) {\n $operationWrapper.operation.outcome = \"SUCCESS\";\n $manager.setControlLoopResult(\"SUCCESS\");\n notification.history.add($operationWrapper.operation);\n notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n notification.notification = ControlLoopNotificationType.FINAL_SUCCESS;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // We are going to retract these objects from memory\n //\n System.out.println(\"Retracting everything\");\n retract($operationWrapper);\n retract($request);\n retract($response);\n retract($event);\n retract($manager);\n } else {\n $operationWrapper.operation.outcome = \"FAILURE\";\n $manager.setControlLoopResult(\"FAILURE\");\n notification.history.add($operationWrapper.operation);\n notification.notification = ControlLoopNotificationType.OPERATION_FAILURE;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n notification.notification = ControlLoopNotificationType.FINAL_FAILURE;\n //\n // Let interested parties know\n //\n try {\n System.out.println(Serialization.gsonPretty.toJson(notification));\n PolicyEngine.manager.deliver($params.getNotificationTopic(), notification);\n } catch (Exception e) {\n System.out.println(\"Can\'t deliver notification: \" + notification);\n e.printStackTrace();\n }\n //\n // We are going to retract these objects from memory\n //\n System.out.println(\"Retracting everything\");\n retract($operationWrapper);\n retract($request);\n retract($response);\n retract($event);\n retract($manager);\n }\n \nend \nrule \"com.Config_BRMS_Param_BRMSParamvLBDemoPolicy.Params\" \n salience 1000 \n when\n then\n Params params = new Params();\n params.setAaiPatternMatch(0);\n params.setAppcTopic(\"APPC-CL\");\n params.setAaiURL(\"https://aai.api.simpledemo.openecomp.org:8443\");\n params.setMsoPassword(\"password1$\");\n params.setClosedLoopControlName(\"CL-DNS-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8\");\n params.setAaiUsername(\"POLICY\");\n params.setMsoURL(\"http://vm1.mso.simpledemo.openecomp.org:8080/ecomp/mso/infra\");\n params.setActor(\"MSO\");\n params.setMsoUsername(\"InfraPortalClient\");\n params.setAaiNamedQueryUUID(\"f199cb88-5e69-4b1f-93e0-6f257877d066\");\n params.setAaiPassword(\"POLICY\");\n params.setNotificationTopic(\"POLICY-CL-MGT\");\n insert(params);\nend\r\n','OTHER','com.Config_BRMS_Param_BRMSParamvLBDemoPolicy.1.txt','doACPolicyPut','2017-03-14 20:00:56',0,'','doACPolicyPut','2017-03-14 20:00:56',1);
INSERT INTO `policyentity` VALUES (3202,'doACPolicyPut','2017-03-14 19:58:19',0,'BRMSParam vFW Demo Policy@CreatedBy:@CreatedBy:@ModifiedBy:@ModifiedBy:','doACPolicyPut','2017-03-14 19:58:19','<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<Policy xmlns=\"urn:oasis:names:tc:xacml:3.0:core:schema:wd-17\" PolicyId=\"urn:com:xacml:policy:id:256f4712-a965-4817-a851-a71bdeb9fb49\" Version=\"1\" RuleCombiningAlgId=\"urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides\">\n <Description>BRMSParam vFW Demo Policy@CreatedBy:@CreatedBy:@ModifiedBy:@ModifiedBy:</Description>\n <Target>\n <AnyOf>\n <AllOf>\n <Match MatchId=\"org.openecomp.function.regex-match\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml</AttributeValue>\n <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\"/>\n </Match>\n </AllOf>\n <AllOf>\n <Match MatchId=\"org.openecomp.function.regex-match\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">DROOLS</AttributeValue>\n <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\"/>\n </Match>\n <Match MatchId=\"org.openecomp.function.regex-match\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">BRMS_PARAM_RULE</AttributeValue>\n <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\"/>\n </Match>\n <Match MatchId=\"org.openecomp.function.regex-match\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">SampleRiskType</AttributeValue>\n <AttributeDesignator Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" AttributeId=\"RiskType\" DataType=\"http://www.w3.org/2001/XMLSchema#string\" MustBePresent=\"false\"/>\n </Match>\n <Match MatchId=\"org.openecomp.function.regex-match\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">1</AttributeValue>\n <AttributeDesignator Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" AttributeId=\"RiskLevel\" DataType=\"http://www.w3.org/2001/XMLSchema#string\" MustBePresent=\"false\"/>\n </Match>\n <Match MatchId=\"org.openecomp.function.regex-match\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">False</AttributeValue>\n <AttributeDesignator Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" AttributeId=\"guard\" DataType=\"http://www.w3.org/2001/XMLSchema#string\" MustBePresent=\"false\"/>\n </Match>\n <Match MatchId=\"org.openecomp.function.regex-match\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">NA</AttributeValue>\n <AttributeDesignator Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" AttributeId=\"TTLDate\" DataType=\"http://www.w3.org/2001/XMLSchema#string\" MustBePresent=\"false\"/>\n </Match>\n </AllOf>\n </AnyOf>\n </Target>\n <Rule RuleId=\"urn:com:xacml:rule:id:8cdb88aa-448b-4ed1-bce5-6a037651e73c\" Effect=\"Permit\">\n <Target>\n <AnyOf>\n <AllOf>\n <Match MatchId=\"urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">ACCESS</AttributeValue>\n <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\"/>\n </Match>\n <Match MatchId=\"urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">Config</AttributeValue>\n <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\"/>\n </Match>\n </AllOf>\n </AnyOf>\n </Target>\n <AdviceExpressions>\n <AdviceExpression AdviceId=\"BRMSPARAMID\" AppliesTo=\"Permit\">\n <AttributeAssignmentExpression AttributeId=\"type\" Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" Issuer=\"\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">Configuration</AttributeValue>\n </AttributeAssignmentExpression>\n <AttributeAssignmentExpression AttributeId=\"URLID\" Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" Issuer=\"\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#anyURI\">$URL/Config/com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt</AttributeValue>\n </AttributeAssignmentExpression>\n <AttributeAssignmentExpression AttributeId=\"PolicyName\" Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" Issuer=\"\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml</AttributeValue>\n </AttributeAssignmentExpression>\n <AttributeAssignmentExpression AttributeId=\"VersionNumber\" Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" Issuer=\"\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">1</AttributeValue>\n </AttributeAssignmentExpression>\n <AttributeAssignmentExpression AttributeId=\"matching:ECOMPName\" Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" Issuer=\"\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">DROOLS</AttributeValue>\n </AttributeAssignmentExpression>\n <AttributeAssignmentExpression AttributeId=\"matching:ConfigName\" Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" Issuer=\"\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">BRMS_PARAM_RULE</AttributeValue>\n </AttributeAssignmentExpression>\n <AttributeAssignmentExpression AttributeId=\"key:controller\" Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" Issuer=\"\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">vFW</AttributeValue>\n </AttributeAssignmentExpression>\n <AttributeAssignmentExpression AttributeId=\"RiskType\" Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" Issuer=\"\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">SampleRiskType</AttributeValue>\n </AttributeAssignmentExpression>\n <AttributeAssignmentExpression AttributeId=\"RiskLevel\" Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" Issuer=\"\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">1</AttributeValue>\n </AttributeAssignmentExpression>\n <AttributeAssignmentExpression AttributeId=\"guard\" Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" Issuer=\"\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">False</AttributeValue>\n </AttributeAssignmentExpression>\n <AttributeAssignmentExpression AttributeId=\"TTLDate\" Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" Issuer=\"\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">NA</AttributeValue>\n </AttributeAssignmentExpression>\n </AdviceExpression>\n </AdviceExpressions>\n </Rule>\n</Policy>\n','Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml',0,'com',1,NULL,3201),(3204,'doACPolicyPut','2017-03-14 20:00:56',0,'BRMSParam vLB Demo Policy@CreatedBy:@CreatedBy:@ModifiedBy:@ModifiedBy:','doACPolicyPut','2017-03-14 20:00:56','<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<Policy xmlns=\"urn:oasis:names:tc:xacml:3.0:core:schema:wd-17\" PolicyId=\"urn:com:xacml:policy:id:ace93d23-7a21-450a-87b4-5ff11e01d4b1\" Version=\"1\" RuleCombiningAlgId=\"urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides\">\n <Description>BRMSParam vLB Demo Policy@CreatedBy:@CreatedBy:@ModifiedBy:@ModifiedBy:</Description>\n <Target>\n <AnyOf>\n <AllOf>\n <Match MatchId=\"org.openecomp.function.regex-match\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">com.Config_BRMS_Param_BRMSParamvLBDemoPolicy.1.xml</AttributeValue>\n <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\"/>\n </Match>\n </AllOf>\n <AllOf>\n <Match MatchId=\"org.openecomp.function.regex-match\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">DROOLS</AttributeValue>\n <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\"/>\n </Match>\n <Match MatchId=\"org.openecomp.function.regex-match\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">BRMS_PARAM_RULE</AttributeValue>\n <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\"/>\n </Match>\n <Match MatchId=\"org.openecomp.function.regex-match\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">SampleRiskType</AttributeValue>\n <AttributeDesignator Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" AttributeId=\"RiskType\" DataType=\"http://www.w3.org/2001/XMLSchema#string\" MustBePresent=\"false\"/>\n </Match>\n <Match MatchId=\"org.openecomp.function.regex-match\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">1</AttributeValue>\n <AttributeDesignator Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" AttributeId=\"RiskLevel\" DataType=\"http://www.w3.org/2001/XMLSchema#string\" MustBePresent=\"false\"/>\n </Match>\n <Match MatchId=\"org.openecomp.function.regex-match\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">False</AttributeValue>\n <AttributeDesignator Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" AttributeId=\"guard\" DataType=\"http://www.w3.org/2001/XMLSchema#string\" MustBePresent=\"false\"/>\n </Match>\n <Match MatchId=\"org.openecomp.function.regex-match\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">NA</AttributeValue>\n <AttributeDesignator Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" AttributeId=\"TTLDate\" DataType=\"http://www.w3.org/2001/XMLSchema#string\" MustBePresent=\"false\"/>\n </Match>\n </AllOf>\n </AnyOf>\n </Target>\n <Rule RuleId=\"urn:com:xacml:rule:id:9d472f3a-bab1-4bee-8bfc-0ee1b4e11ad6\" Effect=\"Permit\">\n <Target>\n <AnyOf>\n <AllOf>\n <Match MatchId=\"urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">ACCESS</AttributeValue>\n <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\"/>\n </Match>\n <Match MatchId=\"urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">Config</AttributeValue>\n <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\"/>\n </Match>\n </AllOf>\n </AnyOf>\n </Target>\n <AdviceExpressions>\n <AdviceExpression AdviceId=\"BRMSPARAMID\" AppliesTo=\"Permit\">\n <AttributeAssignmentExpression AttributeId=\"type\" Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" Issuer=\"\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">Configuration</AttributeValue>\n </AttributeAssignmentExpression>\n <AttributeAssignmentExpression AttributeId=\"URLID\" Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" Issuer=\"\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#anyURI\">$URL/Config/com.Config_BRMS_Param_BRMSParamvLBDemoPolicy.1.txt</AttributeValue>\n </AttributeAssignmentExpression>\n <AttributeAssignmentExpression AttributeId=\"PolicyName\" Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" Issuer=\"\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">com.Config_BRMS_Param_BRMSParamvLBDemoPolicy.1.xml</AttributeValue>\n </AttributeAssignmentExpression>\n <AttributeAssignmentExpression AttributeId=\"VersionNumber\" Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" Issuer=\"\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">1</AttributeValue>\n </AttributeAssignmentExpression>\n <AttributeAssignmentExpression AttributeId=\"matching:ECOMPName\" Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" Issuer=\"\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">DROOLS</AttributeValue>\n </AttributeAssignmentExpression>\n <AttributeAssignmentExpression AttributeId=\"matching:ConfigName\" Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" Issuer=\"\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">BRMS_PARAM_RULE</AttributeValue>\n </AttributeAssignmentExpression>\n <AttributeAssignmentExpression AttributeId=\"key:controller\" Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" Issuer=\"\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">vDNS</AttributeValue>\n </AttributeAssignmentExpression>\n <AttributeAssignmentExpression AttributeId=\"RiskType\" Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" Issuer=\"\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">SampleRiskType</AttributeValue>\n </AttributeAssignmentExpression>\n <AttributeAssignmentExpression AttributeId=\"RiskLevel\" Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" Issuer=\"\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">1</AttributeValue>\n </AttributeAssignmentExpression>\n <AttributeAssignmentExpression AttributeId=\"guard\" Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" Issuer=\"\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">False</AttributeValue>\n </AttributeAssignmentExpression>\n <AttributeAssignmentExpression AttributeId=\"TTLDate\" Category=\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\" Issuer=\"\">\n <AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">NA</AttributeValue>\n </AttributeAssignmentExpression>\n </AdviceExpression>\n </AdviceExpressions>\n </Rule>\n</Policy>\n','Config_BRMS_Param_BRMSParamvLBDemoPolicy.1.xml',0,'com',1,NULL,3203);
diff --git a/packages/base/src/files/install/mysql/data/170701_upgrade_script.sql b/packages/base/src/files/install/mysql/data/170701_upgrade_script.sql
index c8e19f8f4..7d990b42f 100644
--- a/packages/base/src/files/install/mysql/data/170701_upgrade_script.sql
+++ b/packages/base/src/files/install/mysql/data/170701_upgrade_script.sql
@@ -18,4 +18,6 @@
* ============LICENSE_END=========================================================
*/
use ecomp_sdk;
-ALTER TABLE fwtagpicker add networkRole varchar(64); \ No newline at end of file
+ALTER TABLE fwtagpicker add networkRole varchar(64);
+
+INSERT INTO policyeditorscopes (`id`, `scopename`, `created_date`, `created_by`, `modified_date`, `modified_by`) VALUES ('1', 'com', '2017-06-01 11:45:36', 'demo', '2017-06-01 11:45:36', 'demo');
diff --git a/packages/base/src/files/install/servers/console/bin/xacml.admin.properties b/packages/base/src/files/install/servers/console/bin/xacml.admin.properties
index dbbcc59fb..7c2d1d270 100644
--- a/packages/base/src/files/install/servers/console/bin/xacml.admin.properties
+++ b/packages/base/src/files/install/servers/console/bin/xacml.admin.properties
@@ -41,6 +41,10 @@ xacml.att.evaluationContextFactory=com.att.research.xacmlatt.pdp.std.StdEvaluati
xacml.att.combiningAlgorithmFactory=com.att.research.xacmlatt.pdp.std.StdCombiningAlgorithmFactory
xacml.att.functionDefinitionFactory=org.openecomp.policy.xacml.custom.EcompFunctionDefinitionFactory
xacml.att.policyFinderFactory=com.att.research.xacmlatt.pdp.std.StdPolicyFinderFactory
+#
+# Policy Adapter Implementation class
+#
+policyAdapter.impl.className = org.openecomp.policy.admin.PolicyAdapter
#
# This is an extremely simple policy to demonstrate authorization
diff --git a/packages/base/src/files/install/servers/pap/bin/xacml.pap.properties b/packages/base/src/files/install/servers/pap/bin/xacml.pap.properties
index 143aeabce..3e30bde80 100644
--- a/packages/base/src/files/install/servers/pap/bin/xacml.pap.properties
+++ b/packages/base/src/files/install/servers/pap/bin/xacml.pap.properties
@@ -110,6 +110,8 @@ xacml.rest.pap.autopush.flag=false
xacml.rest.pap.autopush.file=autopush.properties
#Patter to identify if a attribute is ready. Currently just a place holder
xacm.xcor.required.pattern=1,1
+#the number of times an incoming policy update notification will be tried to be processed (or until it succeeds)
+xacml.rest.pap.incomingnotification.tries=4
#***Properties for IntegrityMonitor integration defined in XACMLRestProperties.java***
#The name of the PAP. Must be unique across the system
diff --git a/packages/base/src/files/install/servers/pap/webapps/Config/com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt b/packages/base/src/files/install/servers/pap/webapps/Config/com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt
index 25b53d0ca..955afbd0f 100755
--- a/packages/base/src/files/install/servers/pap/webapps/Config/com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt
+++ b/packages/base/src/files/install/servers/pap/webapps/Config/com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt
@@ -1124,7 +1124,7 @@ rule "BRMSParamvFWDemoPolicy.MSO.RESPONSE"
}
end
-rule "Params"
+rule "com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.Params"
salience 1000
when
then
diff --git a/packages/base/src/files/install/servers/pap/webapps/Config/com.Config_BRMS_Param_BRMSParamvLBDemoPolicy.1.txt b/packages/base/src/files/install/servers/pap/webapps/Config/com.Config_BRMS_Param_BRMSParamvLBDemoPolicy.1.txt
index e640d007d..90ae05aa3 100755
--- a/packages/base/src/files/install/servers/pap/webapps/Config/com.Config_BRMS_Param_BRMSParamvLBDemoPolicy.1.txt
+++ b/packages/base/src/files/install/servers/pap/webapps/Config/com.Config_BRMS_Param_BRMSParamvLBDemoPolicy.1.txt
@@ -1124,7 +1124,7 @@ rule "BRMSParamvLBDemoPolicy.MSO.RESPONSE"
}
end
-rule "Params"
+rule "com.Config_BRMS_Param_BRMSParamvLBDemoPolicy.Params"
salience 1000
when
then
diff --git a/packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties b/packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties
index 3b0431958..7750047f7 100644
--- a/packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties
+++ b/packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties
@@ -132,6 +132,7 @@ javax.persistence.jdbc.user=${{JDBC_USER}}
javax.persistence.jdbc.password=${{JDBC_PASSWORD}}
# Environment should be Set either DEV, TEST or PROD
ENVIRONMENT=${{ENVIRONMENT}}
+xacml.rest.pep.idfile = client.properties
#AAF Policy Name space
#Required only, when we use AAF