Merge "Clean up pom.xml and fix CLM"
authorPamela Dragosh <pdragosh@research.att.com>
Wed, 7 Mar 2018 14:16:13 +0000 (14:16 +0000)
committerGerrit Code Review <gerrit@onap.org>
Wed, 7 Mar 2018 14:16:13 +0000 (14:16 +0000)
19 files changed:
BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSHandler.java
BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSPush.java
ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java
ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/XACMLPAPTest.java
ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/BRMSPolicyTest.java
ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/MicroServicePolicyTest.java
ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandlerTest.java [new file with mode: 0644]
ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/utils/test/PolicyApiUtilsTest.java [new file with mode: 0644]
POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java
POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java
POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyManagerServletTest.java
POLICY-SDK-APP/src/test/resources/com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt
POLICY-SDK-APP/src/test/resources/com.Config_BRMS_Raw_TestBRMSRawPolicy.1.txt
PolicyEngineAPI/src/main/java/org/onap/policy/api/PolicyEngine.java
PolicyEngineAPI/src/main/java/org/onap/policy/std/AutoClientEnd.java
PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyEngine.java
PolicyEngineAPI/src/test/java/org/onap/policy/std/StdPolicyEngineTest.java
PolicyEngineClient/testResources/test.drl
PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/PolicyUtilsTest.java

index c0a9cd2..b460fb8 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP Policy Engine
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -120,6 +120,8 @@ public class BRMSHandler implements BackUpHandler{
         */
        @Override
        public void runOnNotification(PDPNotification notification){
+               // reset the BRMSPush data structures
+               bRMSPush.resetDS();
                if(notification.getNotificationType().equals(NotificationType.REMOVE)){
                        removedPolicies(notification.getRemovedPolicies());
                }else if(notification.getNotificationType().equals(NotificationType.UPDATE)|| notification.getNotificationType().equals(NotificationType.BOTH)){
index ac1d0ac..b76812b 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP Policy Engine
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -374,6 +374,11 @@ public class BRMSPush {
         if (flag)
             syncGroupInfo();
     }
+    
+    public void resetDS(){
+       resetModifiedGroups();
+        controllers = new ArrayList<>();
+    }
 
     private static void resetModifiedGroups() {
         modifiedGroups = new HashMap<>();
@@ -410,6 +415,7 @@ public class BRMSPush {
                         PEDependency dependency = PolicyUtils.jsonStringToObject(value,
                                 PEDependency.class);
                         userControllerName = key.replaceFirst("$controller:", "");
+                        LOGGER.info("addRule: userControllerName - " + userControllerName + ", dependency: - " + dependency);
                         addToGroup(userControllerName, dependency);
                     } catch (Exception e) {
                         LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while resolving Controller: " + e);
@@ -445,6 +451,7 @@ public class BRMSPush {
             // If the key is not got as parameters set by the user, setting the default value for kSessionName as
             // closedLoop
             if (kSessionName == null) {
+               LOGGER.info("kSessionName is null, selectedName is  : " + selectedName );
                 if (selectedName == defaultName) {
                     kSessionName = "closedloop";
                 } else {
@@ -747,6 +754,7 @@ public class BRMSPush {
                 InvocationResult result = null;
                String group = entry.getKey();
                 try {
+                       LOGGER.info("PushRules: ModifiedGroups, Key: " + group + ", Value: " + entry.getValue());
                     InvocationRequest request = new DefaultInvocationRequest();
                     setVersion(group);
                     createPom(group);
index 3ed2ee3..4de65fd 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP-PAP-REST
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -86,7 +86,7 @@ public class CreateBrmsParamPolicy extends Policy {
 
                Map<String,String> copyMap=new HashMap<>();
                copyMap.putAll(brmsParamBody);
-               copyMap.put("policyName", policyName.substring(0, policyName.replace(".xml", "").lastIndexOf(".")));
+               copyMap.put("policyName", policyName.substring(0, policyName.replace(".xml", "").lastIndexOf('.')));
                copyMap.put("policyScope", policyAdapter.getDomainDir());
                copyMap.put("policyVersion",policyAdapter.getHighestVersion().toString());
                copyMap.put("unique", ("p"+policyName+UUID.randomUUID().toString()).replaceAll("[^A-Za-z0-9]", ""));
@@ -123,12 +123,10 @@ public class CreateBrmsParamPolicy extends Policy {
        
        // Saving the Configurations file at server location for config policy.
        protected void saveConfigurations(String policyName, String ruleBody) {
-               try {
-                       if (policyName.endsWith(".xml")) {
-                               policyName = policyName.substring(0,
-                                               policyName.lastIndexOf(".xml"));
-                       }
-                       PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".txt");
+           if (policyName.endsWith(".xml")) {
+            policyName = policyName.substring(0, policyName.lastIndexOf(".xml"));
+        }
+               try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".txt")) {
                        String expandedBody=expandConfigBody(ruleBody,policyAdapter.getBrmsParamBody());
                        out.println(expandedBody);
                        policyAdapter.setJsonBody(expandedBody);
@@ -251,7 +249,7 @@ public class CreateBrmsParamPolicy extends Policy {
                                        if (flag) {
                                                params.append(line);
                                        }
-                                       if (line.contains("declare PapParams")) {
+                                       if (line.contains("declare Params")) {
                                                params.append(line);
                                                flag = true;
                                        }
@@ -259,7 +257,7 @@ public class CreateBrmsParamPolicy extends Policy {
                                                break;
                                        }
                                }
-                               String param = params.toString().replace("declare PapParams", "").replace("end", "")
+                               String param = params.toString().replace("declare Params", "").replace("end", "")
                                                .replaceAll("\\s+", "");
                                String[] components = param.split(":");
                                String caption = "";
@@ -327,60 +325,26 @@ public class CreateBrmsParamPolicy extends Policy {
                
                if (policyAdapter.getData() != null) {  
                        Map<String,String> ruleAndUIValue= policyAdapter.getBrmsParamBody();
-                       String tempateValue= ruleAndUIValue.get("templateName");
-                       String valueFromDictionary= getValueFromDictionary(tempateValue);
+                       String templateValue= ruleAndUIValue.get("templateName");
+                       String valueFromDictionary= getValueFromDictionary(templateValue);
                        
-                       //Get the type of the UI Fields. 
-                       Map<String,String> typeOfUIField=findType(valueFromDictionary);
-                       StringBuilder generatedRule = new StringBuilder();
                        StringBuilder body = new StringBuilder();
                        
                        try {
-                               
-                               try {
-                                       body.append("/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " +
-                                                               "<$%BRMSParamTemplate=" + tempateValue + "%$> \n */ \n");
-                                       body.append(valueFromDictionary + "\n");
-                                       generatedRule.append("rule \"" +policyName.substring(0, policyName.replace(".xml", "").lastIndexOf(".")) +".PapParams\" \n\tsalience 1000 \n\twhen\n\tthen\n\t\tPapParams params = new PapParams();");
-                                       
-                                       //We first read the map data structure(ruleAndUIValue) received from the PAP-ADMIN
-                                       //We ignore if the key is "templateName as we are interested only in the UI fields and its value. 
-                                       //We have one more map data structure(typeOfUIField) created by parsing the Drools rule. 
-                                       //From the type of the UI field(String/int) we structure whether to put the "" or not. 
-                                       for (Map.Entry<String, String> entry : ruleAndUIValue.entrySet()) {
-                                               if(entry.getKey()!="templateName")
-                                               {
-                                                       for(Map.Entry<String, String> fieldType:typeOfUIField.entrySet())
-                                                       {
-                                                               if(fieldType.getKey().equalsIgnoreCase(entry.getKey()))
-                                                               {
-                                                                       String key = entry.getKey().substring(0, 1).toUpperCase() + entry.getKey().substring(1); 
-                                                                       if(fieldType.getValue()=="String")
-                                                                       {
-                                                                               //Type is String
-                                                                               generatedRule.append("\n\t\tparams.set"
-                                                                                               + key + "(\""
-                                                                                               + entry.getValue() + "\");");
-                                                                       }
-                                                                       else{
-                                                                           generatedRule.append("\n\t\tparams.set"
-                                                                                               + key  + "("
-                                                                                               +  entry.getValue() + ");");
-                                                                       }
-                                                               }
-                                                       }
-                                               }
-                                       }
-                                       
-                                       generatedRule.append("\n\t\tinsert(params);\nend");
-                                       LOGGER.info("New rule generated with :" + generatedRule);
-                                       body.append(generatedRule);
-                               } catch (Exception e) {
-                                       PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", "Exception saving policy");
-                               }
+                           body.append("/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " +
+                                   "<$%BRMSParamTemplate=" + templateValue + "%$> \n");
+                           body.append("<%$Values=");
+                           for (Map.Entry<String, String> entry : ruleAndUIValue.entrySet()) {
+                               String uiKey = entry.getKey();
+                               if(!"templateName".equals(uiKey)) {
+                                   body.append(uiKey+":-:"+entry.getValue()+":|:");
+                               }
+                           }
+                           body.append("$%> \n*/ \n");
+                           body.append(valueFromDictionary + "\n");
                        }
                        catch (Exception e) {
-                               PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", "Exception saving policy");
+                           PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", "Exception saving policy");
                        }
                        
                        saveConfigurations(policyName,body.toString());
index 2b84cca..ca2b679 100644 (file)
@@ -335,7 +335,7 @@ public class XACMLPAPTest {
         template.setUserCreatedBy(userInfo);
         String rule = "package com.sample;\n"
                 + "import com.sample.DroolsTest.Message;\n"
-                + "declare PapParams\n"
+                + "declare Params\n"
                 + "samPoll : int\n"
                 + "value : String\n"
                 + "end\n"
index bb537db..c13d1f1 100644 (file)
@@ -46,8 +46,8 @@ public class BRMSPolicyTest {
        
        @Test
        public void testReadFile() throws IOException {
-               String goodRule = "declare PapParams\nparam1 : int\nend\n";
-               String badRule = "declare PapParams\nparam1+ : int\nend\n";
+               String goodRule = "declare Params\nparam1 : int\nend\n";
+               String badRule = "declare Params\nparam1+ : int\nend\n";
                assertEquals(CreateBRMSRuleTemplate.validateRuleParams(goodRule), true);
                assertEquals(CreateBRMSRuleTemplate.validateRuleParams(badRule), false);
        }
index d162649..39b21f1 100644 (file)
@@ -20,6 +20,7 @@
 package org.onap.policy.pap.xacml.rest.components;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.fail;
 import static org.mockito.Matchers.anyString;
@@ -35,9 +36,10 @@ import org.onap.policy.rest.adapter.PolicyRestAdapter;
 import org.powermock.api.mockito.PowerMockito;
 import org.powermock.core.classloader.annotations.PrepareForTest;
 import org.powermock.modules.junit4.PowerMockRunner;
+import java.io.File;
+import java.util.Collections;
 
 @RunWith(PowerMockRunner.class)
-@PrepareForTest(MicroServiceConfigPolicy.class)
 public class MicroServicePolicyTest {
        @Rule
     public ExpectedException thrown = ExpectedException.none();
@@ -57,6 +59,7 @@ public class MicroServicePolicyTest {
                assertNull(policy.getCorrectPolicyDataObject());
        }
        
+       @PrepareForTest({MicroServiceConfigPolicy.class})
        @Test
        public void testPrepareToSave() throws Exception {
                // Need to mock internal dictionary retrieval
@@ -74,4 +77,35 @@ public class MicroServicePolicyTest {
                policy.prepareToSave();
                assertEquals(policy.isPreparedToSave(), true);
        }
-}
\ No newline at end of file
+       
+       @Test
+       public void testCreateConstructor1() {
+               CreateNewMicroServiceModel model = new CreateNewMicroServiceModel(null, null, null, null);
+               assertNotNull(model);
+       }
+       
+       @PrepareForTest({CreateNewMicroServiceModel.class})
+       @Test
+       public void testCreateModel() throws Exception {
+               // Mock file retrieval
+               File testFile = new File("testFile");
+               File[] testList = new File[1];
+               testList[0] = testFile;
+               File impl = Mockito.mock(File.class);
+               PowerMockito.whenNew(File.class).withAnyArguments().thenReturn(impl);
+               when(impl.listFiles()).thenReturn(testList);
+               when(impl.isFile()).thenReturn(true);
+
+               // Mock internal dictionary retrieval
+               CommonClassDaoImpl daoImpl = Mockito.mock(CommonClassDaoImpl.class);
+               PowerMockito.whenNew(CommonClassDaoImpl.class).withNoArguments().thenReturn(daoImpl);
+               when(daoImpl.getDataById(any(), anyString(), anyString())).thenReturn(Collections.emptyList());
+
+               // Test create methods
+               String testFileName = "testFile.zip";
+               String testVal = "testVal";
+               CreateNewMicroServiceModel model = new CreateNewMicroServiceModel(testFileName, testVal, testVal, testVal, testVal);
+               model.addValuesToNewModel();
+               model.saveImportService();
+       }
+}
diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandlerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandlerTest.java
new file mode 100644 (file)
index 0000000..3941593
--- /dev/null
@@ -0,0 +1,114 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP-PAP-REST
+ * ================================================================================
+ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.pap.xacml.rest.handler;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.when;
+import static org.mockito.Matchers.any;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mockito;
+import org.onap.policy.common.logging.ONAPLoggingContext;
+import org.onap.policy.pap.xacml.rest.XACMLPapServlet;
+import org.onap.policy.pap.xacml.rest.elk.client.PolicyElasticSearchController;
+import org.onap.policy.rest.jpa.PolicyEntity;
+import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
+import org.onap.policy.xacml.std.pap.StdEngine;
+import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+import com.mockrunner.mock.web.MockHttpServletRequest;
+import com.mockrunner.mock.web.MockHttpServletResponse;
+import java.sql.Connection;
+import java.util.Collections;
+import java.util.List;
+import javax.persistence.EntityManager;
+
+@RunWith(PowerMockRunner.class)
+public class DeleteHandlerTest {
+       @Test
+       public void testGets() {
+               DeleteHandler handler = new DeleteHandler();
+               assertNotNull(handler);
+               assertEquals(handler.preSafetyCheck(null), true);
+               assertNull(handler.getDeletedGroup());
+       }
+       
+       @Test
+       public void testGetInstance() {
+               DeleteHandler handler = DeleteHandler.getInstance();
+               assertNotNull(handler);
+       }
+       
+       @PrepareForTest({DeleteHandler.class, XACMLPapServlet.class})
+       @Test
+       public void testDeletes() throws Exception {
+               // Mock request
+               DeleteHandler handler = new DeleteHandler();
+               MockHttpServletRequest request = new MockHttpServletRequest();
+               request.setBodyContent("{\n\"PAPPolicyType\": \"StdPAPPolicy\"\n}\n");
+               
+               // Mock servlet
+               PAPPolicyEngine engine = Mockito.mock(StdEngine.class);
+               PowerMockito.mockStatic(XACMLPapServlet.class);
+               when(XACMLPapServlet.getPAPEngine()).thenReturn(engine);
+               when(engine.getGroup(any())).thenReturn(null);
+               
+               // Mock elastic search
+               PolicyElasticSearchController controller = Mockito.mock(PolicyElasticSearchController.class);
+               PowerMockito.whenNew(PolicyElasticSearchController.class).withNoArguments().thenReturn(controller);
+               
+               // Mock entity manager
+               EntityManager em = Mockito.mock(EntityManager.class);
+               
+               // Test deletion from PAP
+               MockHttpServletResponse response = new MockHttpServletResponse();
+               try {
+                       handler.doAPIDeleteFromPAP(request, response);
+               }
+               catch (Exception ex) {
+                       fail("Not expecting an exception: " + ex);
+               }
+               
+               // Test deletion from PDP
+               ONAPLoggingContext loggingContext = Mockito.mock(ONAPLoggingContext.class);
+               try {
+                       handler.doAPIDeleteFromPDP(request, response, loggingContext);
+               }
+               catch (Exception ex) {
+                       fail("Not expecting an exception: " + ex);
+               }
+               
+               // Test delete entity
+               PolicyEntity policyEntity = new PolicyEntity();
+               policyEntity.setPolicyName("testVal");
+               String result = DeleteHandler.deletePolicyEntityData(em, policyEntity);
+               assertEquals(result, "success");
+               
+               // Test check entity
+               Connection con = null;
+               List<?> peResult = Collections.emptyList();
+               assertEquals(DeleteHandler.checkPolicyGroupEntity(con, peResult), false);
+       }
+}
diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/utils/test/PolicyApiUtilsTest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/utils/test/PolicyApiUtilsTest.java
new file mode 100644 (file)
index 0000000..a38603a
--- /dev/null
@@ -0,0 +1,268 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP-PDP-REST
+ * ================================================================================
+ * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.pdp.rest.api.utils.test;
+
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import javax.json.Json;
+import javax.json.JsonArray;
+import javax.json.JsonObject;
+
+import org.json.JSONObject;
+import org.junit.Test;
+import org.onap.policy.pdp.rest.api.utils.PolicyApiUtils;
+
+public class PolicyApiUtilsTest {
+
+       @Test
+       public void testValidateDirectoryJsonFields() {
+               
+               String dictonaryAction = "Action";
+
+               
+               JsonObject jsonObjAttrGood = Json.createObjectBuilder().add("attributeName", "success")
+                               .add("type", "REST")
+                               .add("method", "GET")
+                               .add("url", "http://foobar.com")
+                               .add("body", "foobody")
+                               .build();
+               
+               JsonObject jsonObjAttrNull = Json.createObjectBuilder().add("attributeName", "").build();
+               JsonObject jsonObjAttrBad = Json.createObjectBuilder().add("attributeName", "succ ess").build();
+               JsonObject jsonObjectMissingAttrName = Json.createObjectBuilder().add("foo", "bar").build();
+       
+               
+               assertTrue(PolicyApiUtils.validateDictionaryJsonFields(jsonObjAttrGood, dictonaryAction).contains("success"));
+               assertTrue(PolicyApiUtils.validateDictionaryJsonFields(jsonObjAttrNull, dictonaryAction).contains("No Attribute Name provided"));
+               assertTrue(PolicyApiUtils.validateDictionaryJsonFields(jsonObjAttrBad, dictonaryAction).contains("Invalid Attribute Name"));
+               assertTrue(PolicyApiUtils.validateDictionaryJsonFields(jsonObjectMissingAttrName, dictonaryAction).contains("Missing attributeName"));
+               
+                       /* "type" parameter variations. */
+               JsonObject jsonObjAttrGoodTemp = jsonObjAttrGood;
+
+                       //null/empty type
+               jsonObjAttrGoodTemp = Json.createObjectBuilder().add("attributeName", "success")
+                               .add("type", "")
+                               .add("method", "GET")
+                               .add("url", "http://foobar.com")
+                               .add("body", "foobody")
+                               .build();
+               assertTrue(PolicyApiUtils.validateDictionaryJsonFields(jsonObjAttrGoodTemp, dictonaryAction).contains("No Type provided"));
+               
+                       //missing type
+               jsonObjAttrGoodTemp = Json.createObjectBuilder().add("attributeName", "success")
+                               .add("method", "GET")
+                               .add("url", "http://foobar.com")
+                               .add("body", "foobody")
+                               .build();
+               
+               assertTrue(PolicyApiUtils.validateDictionaryJsonFields(jsonObjAttrGoodTemp, dictonaryAction).contains("Missing type key in the dictionaryJson parameter"));
+               
+                       //invalid type
+               jsonObjAttrGoodTemp = Json.createObjectBuilder().add("attributeName", "success")
+                               .add("type", "INVALID")
+                               .add("method", "GET")
+                               .add("url", "http://foobar.com")
+                               .add("body", "foobody")
+                               .build();
+               
+               assertTrue(PolicyApiUtils.validateDictionaryJsonFields(jsonObjAttrGoodTemp, dictonaryAction).contains("Invalid Type value"));
+               
+                       /* "method" parameter variations. */
+               jsonObjAttrGoodTemp = jsonObjAttrGood;
+               
+                       //null/empty method
+               jsonObjAttrGoodTemp = Json.createObjectBuilder().add("attributeName", "success")
+                               .add("type", "REST")
+                               .add("method", "")
+                               .add("url", "http://foobar.com")
+                               .add("body", "foobody")
+                               .build();
+               assertTrue(PolicyApiUtils.validateDictionaryJsonFields(jsonObjAttrGoodTemp, dictonaryAction).contains("No Method provided"));
+
+                       //missing method
+               jsonObjAttrGoodTemp = Json.createObjectBuilder().add("attributeName", "success")
+                               .add("type", "REST")
+                               .add("url", "http://foobar.com")
+                               .add("body", "foobody")
+                               .build();
+               assertTrue(PolicyApiUtils.validateDictionaryJsonFields(jsonObjAttrGoodTemp, dictonaryAction).contains("Missing method key in the dictionaryJson parameter"));           
+
+                       //valid method
+               jsonObjAttrGoodTemp = Json.createObjectBuilder().add("attributeName", "success")
+                               .add("type", "REST")
+                               .add("method", "GET")
+                               .add("url", "http://foobar.com")
+                               .add("body", "foobody")
+                               .build();
+               assertTrue(PolicyApiUtils.validateDictionaryJsonFields(jsonObjAttrGoodTemp, dictonaryAction).contains("success"));
+
+               jsonObjAttrGoodTemp = Json.createObjectBuilder().add("attributeName", "success")
+                               .add("type", "REST")
+                               .add("method", "PUT")
+                               .add("url", "http://foobar.com")
+                               .add("body", "foobody")
+                               .build();
+               assertTrue(PolicyApiUtils.validateDictionaryJsonFields(jsonObjAttrGoodTemp, dictonaryAction).contains("success"));
+       
+               jsonObjAttrGoodTemp = Json.createObjectBuilder().add("attributeName", "success")
+                               .add("type", "REST")
+                               .add("method", "POST")
+                               .add("url", "http://foobar.com")
+                               .add("body", "foobody")
+                               .build();
+               assertTrue(PolicyApiUtils.validateDictionaryJsonFields(jsonObjAttrGoodTemp, dictonaryAction).contains("success"));
+       
+               
+                       //invalid method
+               jsonObjAttrGoodTemp = Json.createObjectBuilder().add("attributeName", "success")
+                               .add("type", "REST")
+                               .add("method", "INVALID")
+                               .add("url", "http://foobar.com")
+                               .add("body", "foobody")
+                               .build();
+               assertTrue(PolicyApiUtils.validateDictionaryJsonFields(jsonObjAttrGoodTemp, dictonaryAction).contains("Invalid Method value"));
+                       
+               
+                       /* url parameter variations */
+               jsonObjAttrGoodTemp = jsonObjAttrGood;
+               
+                       //null/empty url
+               jsonObjAttrGoodTemp = Json.createObjectBuilder().add("attributeName", "success")
+                               .add("type", "REST")
+                               .add("method", "GET")
+                               .add("url", "")
+                               .add("body", "foobody")
+                               .build();
+               assertTrue(PolicyApiUtils.validateDictionaryJsonFields(jsonObjAttrGoodTemp, dictonaryAction).contains("No URL provided"));
+
+                       //missing url
+               jsonObjAttrGoodTemp = Json.createObjectBuilder().add("attributeName", "success")
+                               .add("type", "REST")
+                               .add("method", "GET")
+                               .add("body", "foobody")
+                               .build();
+               assertTrue(PolicyApiUtils.validateDictionaryJsonFields(jsonObjAttrGoodTemp, dictonaryAction).contains("Missing url key in the dictionaryJson parameter"));
+                       
+                       /* body parameter variations */
+               jsonObjAttrGoodTemp = jsonObjAttrGood;
+               
+                       //null body
+               jsonObjAttrGoodTemp = Json.createObjectBuilder().add("attributeName", "success")
+                               .add("type", "REST")
+                               .add("method", "GET")
+                               .add("url", "http://foobar.com")
+                               .add("body", "")
+                               .build();
+               assertTrue(PolicyApiUtils.validateDictionaryJsonFields(jsonObjAttrGoodTemp, dictonaryAction).contains("No Body provided"));
+               
+                       //missing body
+               jsonObjAttrGoodTemp = Json.createObjectBuilder().add("attributeName", "success")
+                               .add("type", "REST")
+                               .add("method", "GET")
+                               .add("url", "http://foobar.com")
+                               .build();
+               assertTrue(PolicyApiUtils.validateDictionaryJsonFields(jsonObjAttrGoodTemp, dictonaryAction).contains("Missing body key in the dictionaryJson parameter"));
+                               
+               
+                       /*headers parameter variations*/
+               JsonObject jsonObjOption;
+               JsonObject jsonObjNumber;
+               JsonArray jsonArrayHeaders;
+
+                       //missing number headers                
+               jsonObjOption = Json.createObjectBuilder().add("option","foobar").build();
+               //jsonObjNumber = Json.createObjectBuilder().add("number","foobar").build();
+               
+               jsonArrayHeaders = Json.createArrayBuilder()
+                               .add(jsonObjOption)
+                               //.add(jsonObjNumber)
+                               .build();
+               
+               jsonObjAttrGoodTemp = Json.createObjectBuilder().add("attributeName", "success")
+                               .add("type", "REST")
+                               .add("method", "GET")
+                               .add("url", "http://foobar.com")
+                               .add("body", "foobody")
+                               .add("headers", jsonArrayHeaders)
+                               .build();
+
+               assertTrue(PolicyApiUtils.validateDictionaryJsonFields(jsonObjAttrGoodTemp, dictonaryAction).contains("Missing number key in the headers list of the dictionaryJson parameter."));
+               
+                       //missing options headers               
+               jsonObjOption = Json.createObjectBuilder().add("option","foobar").build();
+               jsonObjNumber = Json.createObjectBuilder().add("number","foobar").build();
+               
+               jsonArrayHeaders = Json.createArrayBuilder()
+                               //.add(jsonObjOption)
+                               .add(jsonObjNumber)
+                               .build();
+               
+               jsonObjAttrGoodTemp = Json.createObjectBuilder().add("attributeName", "success")
+                               .add("type", "REST")
+                               .add("method", "GET")
+                               .add("url", "http://foobar.com")
+                               .add("body", "foobody")
+                               .add("headers", jsonArrayHeaders)
+                               .build();
+
+               assertTrue(PolicyApiUtils.validateDictionaryJsonFields(jsonObjAttrGoodTemp, dictonaryAction).contains("Missing option key in the headers list of the dictionaryJson parameter."));
+
+                       //null option
+               jsonObjOption = Json.createObjectBuilder().add("option","").build();
+               jsonObjNumber = Json.createObjectBuilder().add("number","foobar").build();
+               
+               jsonArrayHeaders = Json.createArrayBuilder()
+                               .add(jsonObjOption)
+                               .add(jsonObjNumber)
+                               .build();
+               
+               jsonObjAttrGoodTemp = Json.createObjectBuilder().add("attributeName", "success")
+                               .add("type", "REST")
+                               .add("method", "GET")
+                               .add("url", "http://foobar.com")
+                               .add("body", "foobody")
+                               .add("headers", jsonArrayHeaders)
+                               .build();
+
+               assertTrue(PolicyApiUtils.validateDictionaryJsonFields(jsonObjAttrGoodTemp, dictonaryAction).contains("Missing required Option value"));
+               
+                       //null number can't be tested
+       
+       }
+       
+       @Test
+       public void testStringToJsonObject() {
+               String jsonString = "{\"foo\":\"bar\"}";
+               JsonObject obj = PolicyApiUtils.stringToJsonObject(jsonString);
+               assertTrue(obj.get("foo").toString().equals("\"bar\""));
+       }
+       
+       @Test
+       public void testIsNumeric() {
+               assertFalse(PolicyApiUtils.isNumeric("notNumeric"));
+               assertTrue(PolicyApiUtils.isNumeric("2"));
+       }
+       
+       
+}
index 9498529..4d549fe 100644 (file)
@@ -1123,7 +1123,11 @@ public class PolicyManagerServlet extends HttpServlet {
                        SimpleBindings peParams = new SimpleBindings();
                        peParams.put("oldPolicySplit_1", oldPolicySplit[1]);
                        peParams.put("oldPolicySplit_0", oldPolicySplit[0]);
-                       queryData = controller.getDataByQuery(policyEntityquery, peParams);
+                       if(PolicyController.isjUnit()){
+                               queryData = controller.getDataByQuery(policyEntityquery, null);
+                       }else{
+                               queryData = controller.getDataByQuery(policyEntityquery, peParams);
+                       }
                        if(!queryData.isEmpty()){
                                entity = (PolicyEntity) queryData.get(0);
                        }
index df1ca6a..40cceea 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP Policy Engine
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -28,6 +28,7 @@ import java.util.Iterator;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Map.Entry;
 import java.util.Set;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
@@ -175,7 +176,7 @@ public class CreateBRMSParamController extends RestrictedBaseController {
                                        if (flag) {
                                                params.append(line);
                                        }
-                                       if (line.contains("declare PapParams")) {
+                                       if (line.contains("declare Params")) {
                                                params.append(line);
                                                flag = true;
                                        }
@@ -183,7 +184,7 @@ public class CreateBRMSParamController extends RestrictedBaseController {
                                                break;
                                        }
                                }
-                               params = new StringBuilder(params.toString().replace("declare PapParams", "").replace("end", "").replaceAll("\\s+", ""));
+                               params = new StringBuilder(params.toString().replace("declare Params", "").replace("end", "").replaceAll("\\s+", ""));
                                String[] components = params.toString().split(":");
                                String caption = "";
                                for (int i = 0; i < components.length; i++) {
@@ -363,6 +364,17 @@ public class CreateBRMSParamController extends RestrictedBaseController {
                                                value = value.replace(brmsTemplateVlaue, "");
                                                policyAdapter.setRuleName(value);
                                        }
+                                       if(line.contains("<%$Values=")) {
+                                           String value = line.substring(line.indexOf("<%$"), line.indexOf("$%>"));
+                                           value = value.replaceAll("<%\\$Values=", "");
+                                           for( String keyValue : value.split(":\\|:")) {
+                                               String[] pair = keyValue.split(":-:");
+                                               if (pair != null && pair.length > 0) {
+                                                       dynamicLayoutMap.put(pair[0], (pair.length > 1) ? pair[1] : "");
+                                               }
+                                           }
+                                           return;
+                                       }
                                        if (line.startsWith("/*")) {
                                                comment = true;
                                                continue;
@@ -402,7 +414,7 @@ public class CreateBRMSParamController extends RestrictedBaseController {
                                        if (flag) {
                                                params.append(line);
                                        }
-                                       if (line.contains("rule") && line.contains(".PapParams\"")) {
+                                       if (line.contains("rule") && line.contains(".Params\"")) {
                                                params.append(line);
                                                flag = true;
                                        }
@@ -410,8 +422,8 @@ public class CreateBRMSParamController extends RestrictedBaseController {
                                                break;
                                        }
                                }
-                               params = new StringBuilder(params.substring(params.indexOf(".PapParams\"")+ 11));
-                               params = new StringBuilder(params.toString().replaceAll("\\s+", "").replace("salience1000whenthenPapParamsparams=newPapParams();","")
+                               params = new StringBuilder(params.substring(params.indexOf(".Params\"")+ 11));
+                               params = new StringBuilder(params.toString().replaceAll("\\s+", "").replace("salience1000whenthenParamsparams=newParams();","")
                         .replace("insert(params);end", "")
                         .replace("params.set", ""));
                                String[] components = params.toString().split("\\);");
@@ -459,30 +471,23 @@ public class CreateBRMSParamController extends RestrictedBaseController {
                        }
 
                        String body;
+                       body = findRule((String) policyData.getRuleName()) + "\n";
+                       StringBuilder generatedMetadata = new StringBuilder();
+                       generatedMetadata.append("/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " +
+                                       brmsTemplateVlaue + policyData.getRuleName() + "%$> \n */ \n");
 
-                       body = "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " +
-                                       brmsTemplateVlaue + policyData.getRuleName() + "%$> \n */ \n";
-                       body = body + findRule((String) policyData.getRuleName()) + "\n";
-                       StringBuilder generatedRule = new StringBuilder();
-                       generatedRule.append("rule \""+ policyData.getDomainDir().replace("\\", ".") +".Config_BRMS_Param_" + policyData.getPolicyName()+".PapParams\" \n\tsalience 1000 \n\twhen\n\tthen\n\t\tPapParams params = new PapParams();");
-
-                       if(policyData.getRuleData().size() > 0){ 
-                               for(Object keyValue: policyData.getRuleData().keySet()){ 
-                                       String key = keyValue.toString().substring(0, 1).toUpperCase() + keyValue.toString().substring(1); 
-                                       if (string.equals(keyValue)) { 
-                                               generatedRule.append("\n\t\tparams.set" 
-                                                               + key + "(\"" 
-                                                               + policyData.getRuleData().get(keyValue).toString() + "\");"); 
-                                       } else { 
-                                               generatedRule.append("\n\t\tparams.set" 
-                                                               + key + "(" 
-                                                               + policyData.getRuleData().get(keyValue).toString() + ");"); 
-                                       } 
-                               } 
+                       if(policyData.getDynamicLayoutMap().size() > 0){
+                               generatedMetadata.append("/* <%$Values=");
+                           for (Entry<?, ?> entry : policyData.getRuleData().entrySet()) {
+                               String uiKey = (String) entry.getKey();
+                               if(!"templateName".equals(uiKey)) {
+                                       generatedMetadata.append(uiKey+":-:"+entry.getValue()+":|:");
+                               }
+                           }
+                           generatedMetadata.append("$%> \n*/ \n");                        
                        }
-                       generatedRule.append("\n\t\tinsert(params);\nend");
-                       policyLogger.info("New rule generated with :" + generatedRule.toString());
-                       body = body + generatedRule.toString();
+                       policyLogger.info("Metadata generated with :" + generatedMetadata.toString());
+                       body = generatedMetadata.toString() + body;
                        // Expand the body. 
                        Map<String,String> copyMap=new HashMap<>();
                        copyMap.putAll((Map<? extends String, ? extends String>) policyData.getRuleData());
index be0a92e..06a2bb9 100644 (file)
@@ -31,7 +31,6 @@ import java.util.List;
 
 import javax.servlet.ServletConfig;
 import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
 
 import org.apache.commons.io.IOUtils;
@@ -53,6 +52,7 @@ import org.onap.policy.rest.jpa.PolicyVersion;
 import org.onap.policy.rest.jpa.UserInfo;
 import org.onap.portalsdk.core.domain.User;
 import org.onap.portalsdk.core.util.SystemProperties;
+import org.springframework.mock.web.MockHttpServletResponse;
 
 public class PolicyManagerServletTest extends Mockito{
        
@@ -64,15 +64,16 @@ public class PolicyManagerServletTest extends Mockito{
        private static List<Object> policyEditorScopes;
        private static List<Object> policyVersion;
        private static CommonClassDao commonClassDao;
+       private ConfigurationDataEntity configurationEntity;
        private HttpServletRequest request;       
-       private HttpServletResponse response; 
+       private MockHttpServletResponse response; 
        
        @Before
        public void setUp() throws Exception{
                logger.info("setUp: Entering");
                
                request = mock(HttpServletRequest.class);       
-        response = mock(HttpServletResponse.class); 
+        response = new MockHttpServletResponse(); 
         
                PolicyController.setjUnit(true);
                UserInfo userinfo = new UserInfo();
@@ -103,7 +104,7 @@ public class PolicyManagerServletTest extends Mockito{
         entity.setPolicyName("Config_SampleTest.1.xml");
         entity.setPolicyData(policyContent);
         entity.setScope("com");
-        ConfigurationDataEntity configurationEntity = new ConfigurationDataEntity();
+        configurationEntity = new ConfigurationDataEntity();
         configurationEntity.setConfigBody("Sample Test");
         configurationEntity.setConfigType("OTHER");
         configurationEntity.setConfigurationName("com.Config_SampleTest1206.1.txt");
@@ -139,6 +140,7 @@ public class PolicyManagerServletTest extends Mockito{
                user.setOrgUserId("Test");
                Mockito.when(mockSession.getAttribute(SystemProperties.getProperty("user_attribute_name"))).thenReturn(user);
                Mockito.when(request.getSession(false)).thenReturn(mockSession);
+               commonClassDao = mock(CommonClassDao.class);
        
        }
        
@@ -608,4 +610,86 @@ public class PolicyManagerServletTest extends Mockito{
                }
         }
        }
+       
+       @Test
+       public void testAddScope(){
+               PolicyManagerServlet servlet = new PolicyManagerServlet(); 
+        PolicyController controller = mock(PolicyController.class);
+        List<BufferedReader> readers = new ArrayList<>();
+        readers.add(new BufferedReader(new StringReader("{params: { mode: 'ADDFOLDER', path: '/', name: 'Test'}}")));
+        readers.add(new BufferedReader(new StringReader("{params: { mode: 'ADDFOLDER', path: '/', name: 'Test*&'}}")));
+        readers.add(new BufferedReader(new StringReader("{params: { mode: 'ADDFOLDER', path: '/Test', subScopename: 'Test1'}}")));
+        for(int i=0; i<readers.size(); i++){
+               try {
+                       when(request.getReader()).thenReturn(readers.get(i));
+                       PolicyManagerServlet.setPolicyController(controller);
+                       servlet.doPost(request, response);
+                       assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("success"));
+               } catch (Exception e1) {
+                       logger.error("Exception Occured"+e1);
+                       fail();
+               }
+        }
+       }
+       
+       @Test
+       public void testClone(){
+               PolicyManagerServlet servlet = new PolicyManagerServlet(); 
+        PolicyController controller = mock(PolicyController.class);
+        List<BufferedReader> readers = new ArrayList<>();
+        when(controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", "com.Config_SampleTest1206.1.txt")).thenReturn(configurationEntity);
+               when(controller.getDataByQuery("FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0", null)).thenReturn(basePolicyData); 
+        readers.add(new BufferedReader(new StringReader("{params: { mode: 'COPY', path: 'com.Config_test.1.xml', newPath: 'com.Config_testClone.1.xml'}}")));
+        for(int i=0; i<readers.size(); i++){
+               try {
+                       when(request.getReader()).thenReturn(readers.get(i));
+                       PolicyManagerServlet.setPolicyController(controller);
+                       servlet.doPost(request, response);
+                       assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("success"));
+               } catch (Exception e1) {
+                       logger.error("Exception Occured"+e1);
+                       fail();
+               }
+        }
+       }
+       
+       @Test
+       public void testRename(){
+               PolicyManagerServlet servlet = new PolicyManagerServlet(); 
+        PolicyController controller = mock(PolicyController.class);
+        List<BufferedReader> readers = new ArrayList<>();
+        when(controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", "com.Config_SampleTest1206.1.txt")).thenReturn(configurationEntity);
+               when(controller.getDataByQuery("FROM PolicyEntity where policyName = :oldPolicySplit_1 and scope = :oldPolicySplit_0", null)).thenReturn(basePolicyData); 
+        readers.add(new BufferedReader(new StringReader("{params: { mode: 'RENAME', path: 'com.Config_test.1.xml', newPath: 'com.Config_testClone.1.xml'}}")));
+        for(int i=0; i<readers.size(); i++){
+               try {
+                       when(request.getReader()).thenReturn(readers.get(i));
+                       PolicyManagerServlet.setPolicyController(controller);
+                       servlet.doPost(request, response);
+                       assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("success"));
+               } catch (Exception e1) {
+                       logger.error("Exception Occured"+e1);
+                       fail();
+               }
+        }
+       }
+       
+       @Test
+       public void testRenameScope(){
+               PolicyManagerServlet servlet = new PolicyManagerServlet(); 
+        PolicyController controller = mock(PolicyController.class);
+        List<BufferedReader> readers = new ArrayList<>();
+        readers.add(new BufferedReader(new StringReader("{params: { mode: 'RENAME', path: 'com', newPath: 'Test'}}")));
+        for(int i=0; i<readers.size(); i++){
+               try {
+                       when(request.getReader()).thenReturn(readers.get(i));
+                       PolicyManagerServlet.setPolicyController(controller);
+                       servlet.doPost(request, response);
+                       assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("success"));
+               } catch (Exception e1) {
+                       logger.error("Exception Occured"+e1);
+                       fail();
+               }
+        }
+       }
 }
index 63f93cb..6ff244e 100644 (file)
@@ -88,7 +88,7 @@ import org.onap.policy.drools.system.PolicyEngine;
 //
 // These parameters are required to build the runtime policy
 //
-declare PapParams
+declare Params
     closedLoopControlName : String
     actor : String
     aaiURL : String
index a3cdb78..6924fc3 100644 (file)
@@ -1,7 +1,7 @@
 package com.sample
 import com.sample.DroolsTest.Message;
 // Declare the Parameters here.
-declare PapParams
+declare Params
     samPoll : int
     value : String
 end
index 0d224ce..b8b077c 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * PolicyEngineAPI
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -22,6 +22,7 @@ package org.onap.policy.api;
 
 import java.util.Collection;
 import java.util.Map;
+import java.util.Properties;
 import java.util.UUID;
 
 import javax.json.JsonObject;
@@ -36,11 +37,20 @@ import org.onap.policy.std.StdPolicyEngine;
  * @version 2.0
  */
 public class PolicyEngine{
-       private String propertyFilePath = null;
        private final StdPolicyEngine stdPolicyEngine;
        private NotificationScheme scheme = null;
        private NotificationHandler handler = null;
        
+        /**
+   * PolicyEngine Constructor with <code>Properties</code> structure
+   * 
+   * @param properties the <code>Properties</code> structure containing the Policy engine parameters 
+   * @throws PolicyEngineException PolicyEngine Exception
+   */
+  public PolicyEngine(final Properties properties) throws PolicyEngineException {
+    this.stdPolicyEngine= new StdPolicyEngine(properties, (String)null);
+  }
+       
        /**
         * PolicyEngine Constructor with <code>String</code> format of propertiesFilePathname
         * 
@@ -48,22 +58,31 @@ public class PolicyEngine{
         * @throws PolicyEngineException PolicyEngine Exception
         */
        public PolicyEngine(final String propertiesFilePathname) throws PolicyEngineException {
-               this.propertyFilePath = propertiesFilePathname ; 
-               this.stdPolicyEngine= new StdPolicyEngine(this.propertyFilePath, (String)null);
+               this.stdPolicyEngine= new StdPolicyEngine(propertiesFilePathname, (String)null);
        }
        
        /**
-        * PolicyEngine Constructor with <code>String</code> format of propertiesFilePathname
+        * PolicyEngine Constructor with <code>Properties</code> structure
         * 
-        * @param propertiesFilePathname the <code>String</code> format of the propertiesFilePathname
+        * @param properties the <code>Properties</code> structure containing the Policy engine parameters 
         * @param clientKey depicts String format of Password/ Client_Key.  
         * @throws PolicyEngineException PolicyEngine Exception
         */
-       public PolicyEngine(final String propertiesFilePathname, final String clientKey) throws PolicyEngineException {
-               this.propertyFilePath = propertiesFilePathname ; 
-               this.stdPolicyEngine= new StdPolicyEngine(this.propertyFilePath, clientKey);
+       public PolicyEngine(final Properties properties, final String clientKey) throws PolicyEngineException {
+               this.stdPolicyEngine= new StdPolicyEngine(properties, clientKey);
        }
        
+        /**
+   * PolicyEngine Constructor with <code>String</code> format of propertiesFilePathname
+   * 
+   * @param propertiesFilePathname the <code>String</code> format of the propertiesFilePathname
+   * @param clientKey depicts String format of Password/ Client_Key.  
+   * @throws PolicyEngineException PolicyEngine Exception
+   */
+  public PolicyEngine(final String propertiesFilePathname, final String clientKey) throws PolicyEngineException {
+    this.stdPolicyEngine= new StdPolicyEngine(propertiesFilePathname, clientKey);
+  }
+       
        /**
         * PolicyEngine Constructor with <code>String</code> format of PropertiesFilePathname and <code>NotificationScheme</code>
         * 
@@ -72,9 +91,8 @@ public class PolicyEngine{
         * @throws PolicyEngineException PolicyEngine Exception
         */
        public PolicyEngine(final String propertiesFilePathname, final NotificationScheme scheme) throws PolicyEngineException{
-               this.propertyFilePath = propertiesFilePathname;
                this.scheme = scheme;
-               this.stdPolicyEngine = new StdPolicyEngine(this.propertyFilePath, this.scheme);
+               this.stdPolicyEngine = new StdPolicyEngine(propertiesFilePathname, this.scheme);
        }
        
        /**
@@ -86,10 +104,9 @@ public class PolicyEngine{
         *  @throws PolicyEngineException PolicyEngine Exception
         */
        public PolicyEngine(final String propertiesFilePathname, final NotificationScheme scheme, final NotificationHandler handler) throws PolicyEngineException {
-               this.propertyFilePath = propertiesFilePathname ;
                this.scheme = scheme;
                this.handler = handler;
-               this.stdPolicyEngine= new StdPolicyEngine(this.propertyFilePath,this.scheme,this.handler);
+               this.stdPolicyEngine= new StdPolicyEngine(propertiesFilePathname,this.scheme,this.handler);
        }
        
        /**
index 5423149..e69f007 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * PolicyEngineAPI
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -82,7 +82,7 @@ public class AutoClientEnd {
                AutoClientEnd.url = url;
                
                if (scheme == null || handler == null ||
-                       ! (scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS) &&
+                       ! (scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS) ||
                                        scheme.equals(NotificationScheme.AUTO_NOTIFICATIONS) ) ||
                        AutoClientEnd.client != null) {
                        return;
index 3d3ecee..2349c2e 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * PolicyEngineAPI
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -175,6 +175,13 @@ public class StdPolicyEngine {
     public StdPolicyEngine(final String propertyFilePath, final String clientKey) throws PolicyEngineException {
         setProperty(propertyFilePath, clientKey);
     }
+    
+    /*
+     * Taking the Property structure even if it null.
+     */
+    public StdPolicyEngine(final Properties properties, final String clientKey) throws PolicyEngineException {
+        setProperty(properties, clientKey);
+    }
 
     /*
      * Taking the Notification Constructor.
@@ -840,14 +847,22 @@ public class StdPolicyEngine {
             throw new PolicyEngineException(
                     XACMLErrorConstants.ERROR_DATA_ISSUE + "Error NO PropertyFile Path provided");
         }
-
         final Properties prop = getProperties(propertyFilePath);
+        setProperty(prop,clientKey);
+    }
+    
+    private void setProperty(final Properties properties, String clientKey) throws PolicyEngineException {
+        if (properties == null) {
+            throw new PolicyEngineException(
+                    XACMLErrorConstants.ERROR_DATA_ISSUE + "NO properties provided, the value is NULL");
+        }
+
         // UEB and DMAAP Settings
-        final String notificationTypeValue = prop.getProperty(NOTIFICATION_TYPE_PROP_NAME);
-        final String serverList = prop.getProperty(NOTIFICATION_SERVERS_PROP_NAME);
-        topic = prop.getProperty(NOTIFICATION_TOPIC_PROP_NAME);
-        apiKey = prop.getProperty(UEB_API_KEY_PROP_NAME);
-        apiSecret = prop.getProperty(UEB_API_SECRET_PROP_NAME);
+        final String notificationTypeValue = properties.getProperty(NOTIFICATION_TYPE_PROP_NAME);
+        final String serverList = properties.getProperty(NOTIFICATION_SERVERS_PROP_NAME);
+        topic = properties.getProperty(NOTIFICATION_TOPIC_PROP_NAME);
+        apiKey = properties.getProperty(UEB_API_KEY_PROP_NAME);
+        apiSecret = properties.getProperty(UEB_API_SECRET_PROP_NAME);
 
         setNotificationType(notificationTypeValue, DEFAULT_NOTIFICATION);
 
@@ -867,9 +882,9 @@ public class StdPolicyEngine {
         }
 
         // Client ID Authorization Settings.
-        final String clientID = prop.getProperty(CLIENT_ID_PROP_NAME);
+        final String clientID = properties.getProperty(CLIENT_ID_PROP_NAME);
         if (clientKey == null) {
-            clientKey = getClientKeyFromProperties(prop);
+            clientKey = getClientKeyFromProperties(properties);
         }
         if (clientID == null || clientKey == null || clientID.isEmpty() || clientKey.isEmpty()) {
             LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS
@@ -880,12 +895,12 @@ public class StdPolicyEngine {
             setClientId(clientID.trim());
             setClientKey(clientKey.trim());
         }
-        setEnvironment(prop);
+        setEnvironment(properties);
         // Initializing the values.
         init();
-        readPdpProperites(prop);
+        readPdpProperites(properties);
         // Get JUNIT property from properties file when running tests
-        checkJunit(prop);
+        checkJunit(properties);
     }
 
     private void readPdpProperites(final Properties prop) throws PolicyEngineException {
index d4c1012..1218f19 100644 (file)
@@ -142,6 +142,16 @@ public class StdPolicyEngineTest {
         assertEquals(Arrays.asList(UEB, DMAAP), policyEngine.getNotificationType());
         assertEquals(Arrays.asList(SERVER_NAME, SERVER_NAME), policyEngine.getNotificationURLList());
     }
+    
+    @Test
+    public void testStdPolicyEngineWithPropertiesInitialize_noException() throws Exception {
+        final StdPolicyEngine policyEngine = new StdPolicyEngine(getDefaultProperties(), (String) null);
+        policyEngine.setScheme(NotificationScheme.MANUAL_NOTIFICATIONS);
+        assertEquals("TEST", StdPolicyEngine.getEnvironment());
+        assertEquals("http://localhost:8092/pdp/", StdPolicyEngine.getPDPURL());
+        assertEquals(Arrays.asList(UEB, DMAAP), policyEngine.getNotificationType());
+        assertEquals(Arrays.asList(SERVER_NAME, SERVER_NAME), policyEngine.getNotificationURLList());
+    }
 
     @Test
     public void testStdPolicyEngineInitializeWithSingleServerName_noException() throws Exception {
@@ -194,7 +204,12 @@ public class StdPolicyEngineTest {
 
     @Test(expected = PolicyEngineException.class)
     public void testStdPolicyEngineInitialize_NullArguments_Exception() throws Exception {
-        new StdPolicyEngine(null, (String) null);
+        new StdPolicyEngine((String)null, (String) null);
+    }
+
+    @Test(expected = PolicyEngineException.class)
+    public void testStdPolicyEngineWithPropertiesInitialize_NullArguments_Exception() throws Exception {
+        new StdPolicyEngine((Properties)null, (String) null);
     }
 
     @Test(expected = PolicyEngineException.class)
index 10cd5b7..5253cf8 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * archetype-closed-loop-demo-rules
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -83,7 +83,7 @@ import org.onap.policy.drools.system.PolicyEngine;
 //
 // These parameters are required to build the runtime policy
 //
-declare PapParams
+declare Params
     closedLoopControlName : String
     actor : String
     aaiURL : String
index 34ed6b8..8445ad7 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * PolicyEngineUtils
  * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -148,7 +148,7 @@ public class PolicyUtilsTest {
        public void testBRMSValidate(){
            String rule = "package com.sample;\n"
                    + "import com.sample.DroolsTest.Message;\n"
-                   + "declare PapParams\n"
+                   + "declare Params\n"
                    + "samPoll : int\n"
                    + "value : String\n"
                    + "end\n"