diff options
Diffstat (limited to 'ONAP-PAP-REST/src')
5 files changed, 175 insertions, 63 deletions
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java index 3ed2ee37d..4de65fd1e 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -86,7 +86,7 @@ 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()); diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/XACMLPAPTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/XACMLPAPTest.java index 2b84ccaf1..ca2b6797d 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/XACMLPAPTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/XACMLPAPTest.java @@ -335,7 +335,7 @@ 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" diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/BRMSPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/BRMSPolicyTest.java index bb537db02..c13d1f1fe 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/BRMSPolicyTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/BRMSPolicyTest.java @@ -46,8 +46,8 @@ 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); } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/MicroServicePolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/MicroServicePolicyTest.java index d16264909..39b21f184 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/MicroServicePolicyTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/MicroServicePolicyTest.java @@ -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 index 000000000..3941593e9 --- /dev/null +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandlerTest.java @@ -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); + } +} |