diff options
author | Guo Ruijing <ruijing.guo@intel.com> | 2017-07-31 08:47:35 +0000 |
---|---|---|
committer | Pamela Dragosh <pdragosh@research.att.com> | 2017-07-31 15:51:10 -0400 |
commit | 073cc188efe9abb4c010cf674e34e2cf46ef1c52 (patch) | |
tree | 155c23fbdf3a838ecb5f4183fc3bb6b09aac41eb /ONAP-PDP-REST/src/test | |
parent | 4ca818fdfb9b807562166800a086b413593d6894 (diff) |
[POLICY-73] replace openecomp for policy-engine
Change-Id: I54072f6bcd388c0e05562614ee89b4ae7ad67004
Signed-off-by: Guo Ruijing <ruijing.guo@intel.com>
Signed-off-by: Pamela Dragosh <pdragosh@research.att.com>
Diffstat (limited to 'ONAP-PDP-REST/src/test')
12 files changed, 3666 insertions, 0 deletions
diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/PapUrlResolverTest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/PapUrlResolverTest.java new file mode 100644 index 000000000..c8716c3bc --- /dev/null +++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/PapUrlResolverTest.java @@ -0,0 +1,224 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pdp.rest; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Properties; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.policy.rest.XACMLRestProperties; + +public class PapUrlResolverTest { + + + @Test + public void testPropertyModifications(){ + DateFormat df = new SimpleDateFormat(); + //first sort order + String urls = "http://one.localhost.com,http://two.localhost.com,http://three.localhost.com,http://four.localhost.com"; + String failed = "-1,-1,-1,-1"; + String succeeded = "-1,-1,-1,-1"; + PapUrlResolver rs = PapUrlResolver.getInstance(urls, failed, succeeded); + Assert.assertEquals(rs.getProperties().getProperty(XACMLRestProperties.PROP_PAP_URLS),urls); + + rs.failed(); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + rs.succeeded(); + Assert.assertFalse(rs.hasMoreUrls()); + Properties prop = rs.getProperties(); + Assert.assertEquals(df.format(new Date())+",-1,-1,-1",prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS)); + Assert.assertEquals("-1,"+df.format(new Date())+",-1,-1",prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS)); + + failed = prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS); + succeeded = prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS); + rs = PapUrlResolver.getInstance(urls, failed, succeeded); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://two.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://three.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://four.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://one.localhost.com", rs.getUrl()); + rs.succeeded(); + rs.getNext(); + Assert.assertFalse(rs.hasMoreUrls()); + prop = rs.getProperties(); + Assert.assertEquals("-1,-1,-1,-1",prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS)); + + failed = prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS); + succeeded = prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS); + rs = PapUrlResolver.getInstance(urls, failed, succeeded); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://one.localhost.com", rs.getUrl()); + rs.succeeded(); + rs.getNext(); + Assert.assertFalse(rs.hasMoreUrls()); + prop = rs.getProperties(); + failed = prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS); + succeeded = prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS); + rs = PapUrlResolver.getInstance(urls, failed, succeeded); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://one.localhost.com", rs.getUrl()); + rs.succeeded(); + rs.getNext(); + Assert.assertFalse(rs.hasMoreUrls()); + prop = rs.getProperties(); + failed = prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS); + succeeded = prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS); + rs = PapUrlResolver.getInstance(urls, failed, succeeded); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://one.localhost.com", rs.getUrl()); + rs.succeeded(); + rs.getNext(); + Assert.assertFalse(rs.hasMoreUrls()); + + + prop = rs.getProperties(); + succeeded = prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS); + } + @SuppressWarnings("unused") + @Test + public void testModifyUrl(){ + String newUrl = PapUrlResolver.modifyUrl("http://mypap1.com/pap?id=987654", "http://mypap2.com:45/pap/"); + int u = 8; + } + + @Test + public void testSorts(){ + long currentTime = new Date().getTime(); + DateFormat df = new SimpleDateFormat(); + //first sort order + String urls = "http://one.localhost.com,http://two.localhost.com,http://three.localhost.com,http://four.localhost.com"; + String failed = df.format(new Date(currentTime-3600000))+",-1,-1,"+df.format(new Date(currentTime-3200000)); + String succeeded = "-1,8/13/15 5:41 PM,8/13/15 4:41 PM,-1"; + PapUrlResolver rs = PapUrlResolver.getInstance(urls, failed, succeeded); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://two.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://three.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://one.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://four.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertFalse(rs.hasMoreUrls()); + + urls = "http://one.localhost.com,http://two.localhost.com,http://three.localhost.com,http://four.localhost.com"; + failed = "-1,-1,-1,-1"; + succeeded = "-1,"+df.format(new Date(currentTime-3600000))+","+df.format(new Date(currentTime-6600000))+",-1"; + rs = PapUrlResolver.getInstance(urls, failed, succeeded); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://one.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://two.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://three.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://four.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertFalse(rs.hasMoreUrls()); + + urls = "http://one.localhost.com,http://two.localhost.com,http://three.localhost.com,http://four.localhost.com"; + failed = "-1,-1,-1,-1"; + succeeded = "-1,-1,-1,-1"; + rs = PapUrlResolver.getInstance(urls, failed, succeeded); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://one.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://two.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://three.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://four.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertFalse(rs.hasMoreUrls()); + + urls = "http://one.localhost.com,http://two.localhost.com,http://three.localhost.com,http://four.localhost.com"; + failed = df.format(new Date(currentTime-3900000))+","+df.format(new Date(currentTime-5600000))+","+df.format(new Date(currentTime-4600000))+","+df.format(new Date(currentTime-3600000)); + succeeded = "-1,-1,-1,-1"; + rs = PapUrlResolver.getInstance(urls, failed, succeeded); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://two.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://three.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://one.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://four.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertFalse(rs.hasMoreUrls()); + + urls = "http://one.localhost.com,http://two.localhost.com,http://three.localhost.com,http://four.localhost.com"; + failed = df.format(new Date(currentTime-(3600000*4)))+",-1,-1,-1"; + succeeded = "-1,-1,-1,-1"; + rs = PapUrlResolver.getInstance(urls, failed, succeeded); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://two.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://three.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://four.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://one.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertFalse(rs.hasMoreUrls()); + + urls = "http://one.localhost.com,http://two.localhost.com,http://three.localhost.com,http://four.localhost.com"; + failed = df.format(new Date(currentTime-(3600000*6)))+",-1,-1,-1"; + succeeded = "-1,-1,-1,-1"; + rs = PapUrlResolver.getInstance(urls, failed, succeeded); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://one.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://two.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://three.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://four.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertFalse(rs.hasMoreUrls()); + } +} diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/XACMLPdpServletTest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/XACMLPdpServletTest.java new file mode 100644 index 000000000..3e3f584a9 --- /dev/null +++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/XACMLPdpServletTest.java @@ -0,0 +1,364 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pdp.rest; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import java.util.Random; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletInputStream; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.policy.common.im.AdministrativeStateException; +import org.onap.policy.common.im.IntegrityMonitor; +import org.onap.policy.common.im.StandbyStatusException; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.mock.web.MockServletConfig; + +import com.mockrunner.mock.web.MockServletInputStream; + +import junit.framework.TestCase; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(IntegrityMonitor.class) // so PowerMock can mock static method of IntegrityMonitor +public class XACMLPdpServletTest extends TestCase{ + private static Logger LOGGER = FlexLogger.getLogger(XACMLPdpServletTest.class); + + private List<String> headers = new ArrayList<>(); + + private HttpServletRequest httpServletRequest; + private HttpServletResponse httpServletResponse; + private ServletOutputStream mockOutput; + private ServletInputStream mockInput; + private ServletConfig servletConfig; + private XACMLPdpServlet pdpServlet; + private IntegrityMonitor im; + + + + @Before + public void setUp(){ + httpServletRequest = Mockito.mock(HttpServletRequest.class); + Mockito.when(httpServletRequest.getMethod()).thenReturn("POST"); + Mockito.when(httpServletRequest.getHeaderNames()).thenReturn(Collections.enumeration(headers)); + Mockito.when(httpServletRequest.getAttributeNames()).thenReturn(Collections.enumeration(headers)); + + + mockOutput = Mockito.mock(ServletOutputStream.class); + + httpServletResponse = Mockito.mock(MockHttpServletResponse.class); + + try { + Mockito.when(httpServletResponse.getOutputStream()).thenReturn(mockOutput); + } catch (IOException e) { + fail(); + } + + servletConfig = Mockito.mock(MockServletConfig.class); + //servletConfig + Mockito.when(servletConfig.getInitParameterNames()).thenReturn(Collections.enumeration(headers)); + pdpServlet = new XACMLPdpServlet(); + + Mockito.when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")).thenReturn("xacml.pdp.properties"); + + System.setProperty("xacml.properties", "xacml.pdp.properties"); + System.setProperty("xacml.rest.pdp.config", "config_testing"); + System.setProperty("xacml.rest.pdp.webapps", "/webapps"); + System.setProperty("xacml.rootPolicies", "test_PolicyEngine.xml"); + System.setProperty("xacml.referencedPolicies", "test_PolicyEngine.xml"); + System.setProperty("test_PolicyEngine.xml.file", "config_testing\\test_PolicyEngine.xml"); + System.setProperty("xacml.rest.pdp.register", "false"); + System.setProperty("com.sun.management.jmxremote.port", "9999"); + + im = Mockito.mock(IntegrityMonitor.class); + // Need PowerMockito for mocking static method getInstance(...) + PowerMockito.mockStatic(IntegrityMonitor.class); + try { + // when IntegrityMonitor.getInstance is called, return the mock object + PowerMockito.when(IntegrityMonitor.getInstance(Mockito.anyString(), Mockito.any(Properties.class))).thenReturn(im); + } catch (Exception e1) { + LOGGER.error("Exception Occured"+e1); + } + + try { + Mockito.doNothing().when(im).startTransaction(); + } catch (StandbyStatusException | AdministrativeStateException e) { + fail(); + } + Mockito.doNothing().when(im).endTransaction(); + } + + public void testInit(){ + LOGGER.info("XACMLPdpServletTest - testInit"); + try { + pdpServlet.init(servletConfig); + assertTrue(true); + } catch (Exception e) { + LOGGER.error("Exception Occured"+e); + fail(); + + } + + } + + public void testDoGetNoTypeError(){ + LOGGER.info("XACMLPdpServletTest - testDoGetNoTypeError"); + try{ + pdpServlet.init(servletConfig); + pdpServlet.doGet(httpServletRequest, httpServletResponse); + Mockito.verify(httpServletResponse).sendError(HttpServletResponse.SC_BAD_REQUEST, "type not 'config' or 'hb'"); + assertTrue(true); + }catch(Exception e){ + System.out.println("Unexpected exception in testDoGetNoTypeError"); + LOGGER.error("Exception Occured"+e); + fail(); + } + } + + public void testDoGetConfigType(){ + LOGGER.info("XACMLPdpServletTest - testDoGetConfigType"); + Mockito.when(httpServletRequest.getParameter("type")).thenReturn("config"); + + try{ + pdpServlet.init(servletConfig); + pdpServlet.doGet(httpServletRequest, httpServletResponse); + Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); + assertTrue(true); + }catch (Exception e){ + System.out.println("Unexpected exception in testDoGetConfigType"); + LOGGER.error("Exception Occured"+e); + fail(); + } + + } + + + public void testDoGetTypeHb(){ + LOGGER.info("XACMLPdpServletTest - testDoGetTypeHb"); + try{ + Mockito.when(httpServletRequest.getParameter("type")).thenReturn("hb"); + pdpServlet.init(servletConfig); + pdpServlet.doGet(httpServletRequest, httpServletResponse); + Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_NO_CONTENT); + assertTrue(true); + }catch(Exception e){ + System.out.println("Unexpected exception in testDoGetTypeHb"); + LOGGER.error("Exception Occured"+e); + fail(); + } + } + public void testDoGetTypeStatus(){ + LOGGER.info("XACMLPdpServletTest - testDoGetTypeStatus"); + try{ + Mockito.when(httpServletRequest.getParameter("type")).thenReturn("Status"); + pdpServlet.init(servletConfig); + pdpServlet.doGet(httpServletRequest, httpServletResponse); + Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); + assertTrue(true); + }catch(Exception e){ + System.out.println("Unexpected exception in testDoGetTypeStatus"); + LOGGER.error("Exception Occured"+e); + fail(); + } + } + + public void testDoPost(){ + LOGGER.info("XACMLPdpServletTest - testDoPost"); + try{ + pdpServlet.init(servletConfig); + pdpServlet.doPost(httpServletRequest, httpServletResponse); + assertTrue(true); + }catch (Exception e){ + System.out.println("Unexpected exception in testDoPost"); + LOGGER.error("Exception Occured"+e); + fail(); + } + } + + public void testDoPostToLong(){ + LOGGER.info("XACMLPdpServletTest - testDoPostToLong"); + try{ + Mockito.when(httpServletRequest.getContentType()).thenReturn("stuff"); + Mockito.when(httpServletRequest.getContentLength()).thenReturn(32768); + + pdpServlet.init(servletConfig); + pdpServlet.doPost(httpServletRequest, httpServletResponse); + assertTrue(true); + }catch (Exception e){ + System.out.println("Unexpected exception in testDoPostToLong"); + LOGGER.error("Exception Occured"+e); + fail(); + } + } + + public void testDoPostContentLengthNegative(){ + LOGGER.info("XACMLPdpServletTest - testDoPostToLong"); + try{ + Mockito.when(httpServletRequest.getContentType()).thenReturn("stuff"); + Mockito.when(httpServletRequest.getContentLength()).thenReturn(-1); + + pdpServlet.init(servletConfig); + pdpServlet.doPost(httpServletRequest, httpServletResponse); + assertTrue(true); + }catch (Exception e){ + System.out.println("Unexpected exception in testDoPostContentLengthNegative"); + LOGGER.error("Exception Occured"+e); + fail(); + } + } + + public void testDoPostContentTypeNonValid(){ + LOGGER.info("XACMLPdpServletTest - testDoPostToLong"); + try{ + Mockito.when(httpServletRequest.getContentType()).thenReturn(";"); + Mockito.when(httpServletRequest.getContentLength()).thenReturn(30768); + + pdpServlet.init(servletConfig); + pdpServlet.doPost(httpServletRequest, httpServletResponse); + assertTrue(true); + }catch (Exception e){ + System.out.println("Unexpected exception in testDoPostContentTypeNonValid"); + LOGGER.error("Exception Occured"+e); + fail(); + } + } + + public void testDoPostContentTypeConfigurationError(){ + LOGGER.info("XACMLPdpServletTest - testDoPostToLong"); + try{ + Mockito.when(httpServletRequest.getContentType()).thenReturn("stuff"); + Mockito.when(httpServletRequest.getContentLength()).thenReturn(30768); + + pdpServlet.init(servletConfig); + pdpServlet.doPost(httpServletRequest, httpServletResponse); + assertTrue(true); + }catch (Exception e){ + System.out.println("Unexpected exception in testDoPostContentTypeConfigurationError"); + LOGGER.error("Exception Occured"+e); + fail(); + } + } + + public void testDoPutCacheEmpty(){ + LOGGER.info("XACMLPdpServletTest - testDoPutCacheEmpty"); + mockInput = Mockito.mock(ServletInputStream.class); + + try{ + Mockito.when(httpServletRequest.getParameter("cache")).thenReturn("cache"); + Mockito.when(httpServletRequest.getContentType()).thenReturn("text/x-java-properties"); + Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput); + pdpServlet.init(servletConfig); + pdpServlet.doPut(httpServletRequest, httpServletResponse); + Mockito.verify(httpServletResponse).sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT must contain at least one property"); + assertTrue(true); + }catch (Exception e){ + System.out.println("Unexpected exception in testDoPutCacheEmpty"); + LOGGER.error("Exception Occured"+e); + fail(); + } + } + + public void testDoPutConfigPolicies(){ + LOGGER.info("XACMLPdpServletTest - testDoPutConfigPolicies"); + byte[] b = new byte[20]; + new Random().nextBytes(b); + + mockInput = new MockServletInputStream(b); + + try{ + Mockito.when(httpServletRequest.getParameter("cache")).thenReturn("policies"); + Mockito.when(httpServletRequest.getContentType()).thenReturn("text/x-java-properties"); + Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput); + pdpServlet.init(servletConfig); + pdpServlet.doPut(httpServletRequest, httpServletResponse); + assertTrue(true); + }catch (Exception e){ + System.out.println("Unexpected exception in testDoPutConfigPolicies"); + LOGGER.error("Exception Occured"+e); + fail(); + } + } + + public void testDoPutToLong(){ + LOGGER.info("XACMLPdpServletTest - testDoPutToLong"); + try{ + Mockito.when(httpServletRequest.getParameter("cache")).thenReturn("policies"); + + Mockito.when(httpServletRequest.getContentType()).thenReturn("text/x-java-properties"); + Mockito.when(httpServletRequest.getContentLength()).thenReturn(1000000000); + + pdpServlet.init(servletConfig); + pdpServlet.doPut(httpServletRequest, httpServletResponse); + Mockito.verify(httpServletResponse).sendError(HttpServletResponse.SC_BAD_REQUEST, "Content-Length larger than server will accept."); + assertTrue(true); + }catch (Exception e){ + System.out.println("Unexpected exception in testDoPutToLong"); + LOGGER.error("Exception Occured"+e); + fail(); + } + } + + public void testDoPutInvalidContentType(){ + LOGGER.info("XACMLPdpServletTest - testDoPutToLong"); + try{ + Mockito.when(httpServletRequest.getParameter("cache")).thenReturn("policies"); + + Mockito.when(httpServletRequest.getContentType()).thenReturn("text/json"); + Mockito.when(httpServletRequest.getContentLength()).thenReturn(32768); + + pdpServlet.init(servletConfig); + pdpServlet.doPut(httpServletRequest, httpServletResponse); + Mockito.verify(httpServletResponse).sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid cache: 'policies' or content-type: 'text/json'"); + assertTrue(true); + }catch (Exception e){ + System.out.println("Unexpected exception in testDoPutInvalidContentType"); + LOGGER.error("Exception Occured"+e); + fail(); + } + } + + public void testDestroy(){ + LOGGER.info("XACMLPdpServletTest - testDestroy"); + + try{ + pdpServlet.init(servletConfig); + pdpServlet.destroy(); + }catch(Exception e){ + System.out.println("Unexpected exception in testDestroy"); + LOGGER.error("Exception Occured"+e); + fail(); + } + } +} diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/services/PDPServicesTest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/services/PDPServicesTest.java new file mode 100644 index 000000000..e77a8517a --- /dev/null +++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/services/PDPServicesTest.java @@ -0,0 +1,194 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.policy.pdp.rest.api.services; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.Map.Entry; + +import javax.json.Json; +import javax.json.JsonArrayBuilder; +import javax.json.JsonObject; +import javax.json.JsonObjectBuilder; + +import org.junit.*; +import org.junit.runner.RunWith; + +import static org.junit.Assert.*; + +import org.onap.policy.api.DecisionRequestParameters; +import org.onap.policy.api.PolicyDecisionException; +import org.onap.policy.pdp.rest.api.models.PDPResponse; +import org.onap.policy.pdp.rest.config.PDPRestConfig; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {PDPRestConfig.class}) +@WebAppConfiguration +public class PDPServicesTest { + /** + * Run the PDPServices() constructor test. + * + * @generatedBy CodePro at 7/20/17 9:26 AM + */ + @Test + public void testPDPServices_1() + throws Exception { + PDPServices result = new PDPServices(); + assertNotNull(result); + // add additional test code here + } + + /** + * Run the Collection<PDPResponse> generateRequest(String,UUID,boolean,boolean) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 7/20/17 9:26 AM + */ + @Test + public void testGenerateRequest_1() + throws Exception { + DecisionRequestParameters pep = new DecisionRequestParameters(); + Map<String,String> eventAttributes = new HashMap<>(); + eventAttributes.put("TEST", "test"); + pep.setONAPComponentName("te123"); + pep.setDecisionAttributes(eventAttributes); + PDPServices fixture = new PDPServices(); + + //Failure Tests. + String jsonString = getModel(pep).toString(); + UUID requestID = UUID.randomUUID(); + + Collection<PDPResponse> result = fixture.generateRequest(jsonString, requestID, false, true); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.pdp.rest.api.services.PDPServices + assertNotNull(result); + + } + + private JsonObject getModel(DecisionRequestParameters pep) throws PolicyDecisionException{ + JsonArrayBuilder resourceArray = Json.createArrayBuilder(); + + Map<String, String> decisionAttributes = pep.getDecisionAttributes(); + for (Entry<String,String> key : decisionAttributes.entrySet()) { + JsonObjectBuilder resourceBuilder = Json.createObjectBuilder(); + if (key.getValue().matches("[0-9]+")) { + + if ((key.getKey().equals("ErrorCode")) || (key.getKey().equals("WorkStep"))) { + + resourceBuilder.add("Value", key.getValue()); + + } else { + + int val = Integer.parseInt(key.getValue()); + resourceBuilder.add("Value", val); + + } + + } else { + resourceBuilder.add("Value", key.getValue()); + } + resourceBuilder.add("AttributeId", key.getKey()); + resourceArray.add(resourceBuilder); + } + return Json.createObjectBuilder() + .add("Request", Json.createObjectBuilder() + .add("AccessSubject", Json.createObjectBuilder() + .add("Attribute", Json.createObjectBuilder() + .add("Value", pep.getONAPComponentName()) + .add("AttributeId", "ONAPName"))) + .add("Resource", Json.createObjectBuilder() + .add("Attribute", resourceArray)) + .add("Action", Json.createObjectBuilder() + .add("Attribute", Json.createObjectBuilder() + .add("Value", "DECIDE") + .add("AttributeId", "urn:oasis:names:tc:xacml:1.0:action:action-id")))) + .build(); + } + + /** + * Run the Collection<PDPResponse> generateRequest(String,UUID,boolean,boolean) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 7/20/17 9:26 AM + */ + @Test(expected = org.onap.policy.api.PolicyException.class) + public void testGenerateRequest_2() + throws Exception { + PDPServices fixture = new PDPServices(); + fixture.generateRequest("", UUID.randomUUID(), true, true); + String jsonString = ""; + UUID requestID = UUID.randomUUID(); + boolean unique = true; + boolean decide = true; + + Collection<PDPResponse> result = fixture.generateRequest(jsonString, requestID, unique, decide); + + // add additional test code here + assertNotNull(result); + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 7/20/17 9:26 AM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 7/20/17 9:26 AM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 7/20/17 9:26 AM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(PDPServicesTest.class); + } +}
\ No newline at end of file diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/NotificationAPITest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/NotificationAPITest.java new file mode 100644 index 000000000..096f7a37a --- /dev/null +++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/NotificationAPITest.java @@ -0,0 +1,87 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.policy.pdp.rest.api.test; + +import static org.awaitility.Awaitility.await; +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.util.concurrent.TimeUnit; + +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.pdp.rest.api.services.NotificationService; +import org.onap.policy.pdp.rest.api.services.NotificationService.NotificationServiceType; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +import com.att.research.xacml.util.XACMLProperties; + +public class NotificationAPITest { + + @Before + public void setup() throws IOException{ + // Fix properties for next test cases. + XACMLProperties.reloadProperties(); + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/pass.xacml.pdp.properties"); + XACMLProperties.getProperties(); + } + + @Test + public void testPropertyFailure() throws IOException{ + // Change properties and fail. + XACMLProperties.reloadProperties(); + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/fail.xacml.pdp.properties"); + XACMLProperties.getProperties(); + NotificationService notificationService = new NotificationService(null,null,null); + assertEquals(HttpStatus.BAD_REQUEST, notificationService.getResponseCode()); + setup(); + } + + @Test + public void testFailureTopicName(){ + NotificationService notificationService = new NotificationService(null,null,null); + assertEquals(HttpStatus.BAD_REQUEST, notificationService.getResponseCode()); + assertEquals(XACMLErrorConstants.ERROR_DATA_ISSUE + "org.onap.policy.api.PolicyException: Notification Topic is null", notificationService.getResult()); + notificationService = new NotificationService(" ",null,null); + assertEquals(HttpStatus.BAD_REQUEST, notificationService.getResponseCode()); + assertEquals(XACMLErrorConstants.ERROR_DATA_ISSUE + "org.onap.policy.api.PolicyException: Notification Topic is not valid. ", notificationService.getResult()); + } + + @Test + public void testFailureServiceType(){ + NotificationService notificationService = new NotificationService("test",null,null); + assertEquals(HttpStatus.BAD_REQUEST, notificationService.getResponseCode()); + } + + @Test + public void threadTest() throws InterruptedException{ + NotificationService notificationSerivce = new NotificationService("test",null,NotificationServiceType.ADD); + assertEquals(HttpStatus.OK, notificationSerivce.getResponseCode()); + // Wait for thread to remove the Topic Entry. + await().atMost(Integer.toUnsignedLong(2500),TimeUnit.MILLISECONDS).until(()-> { + // Trying to remove again should fail + NotificationService nService = new NotificationService("test",null,NotificationServiceType.REMOVE); + return HttpStatus.BAD_REQUEST.equals(nService.getResponseCode()); + }); + // Coverage Tests, Call Notification Service. + NotificationService.sendNotification("test"); + } +} diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/PolicyEngineServicesTest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/PolicyEngineServicesTest.java new file mode 100644 index 000000000..2a76f581c --- /dev/null +++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/PolicyEngineServicesTest.java @@ -0,0 +1,832 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.policy.pdp.rest.api.test; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.policy.api.AttributeType; +import org.onap.policy.api.ConfigRequestParameters; +import org.onap.policy.api.DecisionRequestParameters; +import org.onap.policy.api.DeletePolicyCondition; +import org.onap.policy.api.DeletePolicyParameters; +import org.onap.policy.api.DictionaryParameters; +import org.onap.policy.api.DictionaryType; +import org.onap.policy.api.EventRequestParameters; +import org.onap.policy.api.PolicyClass; +import org.onap.policy.api.PolicyConfigType; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.api.PolicyType; +import org.onap.policy.api.PushPolicyParameters; +import org.onap.policy.pdp.rest.XACMLPdpServlet; +import org.onap.policy.pdp.rest.api.models.ConfigFirewallPolicyAPIRequest; +import org.onap.policy.pdp.rest.api.models.ConfigNameRequest; +import org.onap.policy.pdp.rest.api.models.ConfigPolicyAPIRequest; +import org.onap.policy.pdp.rest.api.services.CreateUpdatePolicyServiceImpl; +import org.onap.policy.pdp.rest.config.PDPRestConfig; +import org.onap.policy.utils.PolicyUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.web.context.WebApplicationContext; + +import com.att.research.xacml.util.XACMLProperties; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {PDPRestConfig.class}) +@WebAppConfiguration +public class PolicyEngineServicesTest { + private static final String CLIENTAUTHHEADER = "ClientAuth"; + private static final String UUIDHEADER = "X-ECOMP-RequestID"; + // This value is as per test resource code. Don't change this. + private static final String CLIENTAUTHVALUE = "Basic cHl0aG9uOnRlc3Q="; + private static final String ERRORCLIENTVALUE = "Basic dGVzdDp0ZXN0MTIz"; + + private MockMvc mockMvc; + private HttpHeaders headers; + + @Autowired + private WebApplicationContext webApplicationContext; + + @Before() + public void setup() throws IOException{ + headers = new HttpHeaders(); + headers.add(CLIENTAUTHHEADER, CLIENTAUTHVALUE); + XACMLProperties.reloadProperties(); + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/pass.xacml.pdp.properties"); + XACMLProperties.getProperties(); + this.mockMvc = webAppContextSetup(webApplicationContext).build(); + } + + @Test + public void getConfigAPIFailureTest() throws Exception{ + ConfigRequestParameters pep = new ConfigRequestParameters(); + pep.setPolicyName(".*"); + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().is(400)); + // Authorization tests. + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "")) + .andExpect(status().isUnauthorized()); + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")) + .andExpect(status().isUnauthorized()); + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, ERRORCLIENTVALUE)) + .andExpect(status().isUnauthorized()); + // Set wrong request. + pep.setPolicyName(null); + pep.setConfigName("test"); + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).headers(headers).header(UUIDHEADER, "123").contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()); + } + + @Test + public void getConfigServiceTest() throws Exception{ + ConfigRequestParameters pep = new ConfigRequestParameters(); + pep.setPolicyName(".*"); + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).headers(headers).header(UUIDHEADER, UUID.randomUUID()).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + // Without policyName and using onapName and other fields. + pep.setPolicyName(null); + pep.setOnapName("test"); + pep.setConfigName("test"); + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).headers(headers).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + // with config attributes. + Map<String, String> configAttributes = new HashMap<>(); + configAttributes.put("test", "test"); + pep.setConfigAttributes(configAttributes); + pep.makeUnique(true); + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).headers(headers).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test + public void getConfigByPolicyNameTest() throws Exception{ + ConfigNameRequest pep = new ConfigNameRequest(); + pep.setPolicyName(".*"); + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().is(400)); + // Authorization tests. + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "")) + .andExpect(status().isUnauthorized()); + mockMvc.perform(post("/getConfigByPolicyName").content(PolicyUtils.objectToJsonString(pep)).headers(headers).header(UUIDHEADER, UUID.randomUUID()).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test + public void listConfigTest() throws Exception{ + ConfigRequestParameters pep = new ConfigRequestParameters(); + pep.setPolicyName(".*"); + mockMvc.perform(post("/listConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().is(400)); + // Authorization tests. + mockMvc.perform(post("/listConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "")) + .andExpect(status().isUnauthorized()); + mockMvc.perform(post("/listConfig").content(PolicyUtils.objectToJsonString(pep)).headers(headers).header(UUIDHEADER, UUID.randomUUID()).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test + public void getMetricsTest() throws Exception{ + //Failure Tests. + mockMvc.perform(get("/getMetrics")).andExpect(status().isBadRequest()); + mockMvc.perform(get("/getMetrics").header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + mockMvc.perform(get("/getMetrics").headers(headers).header(UUIDHEADER, "123")).andExpect(status().isOk()); + mockMvc.perform(get("/getMetrics").headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isOk()); + mockMvc.perform(get("/getMetrics").headers(headers)).andExpect(status().isOk()); + } + + @Test + public void getNotificationAuthFailureTest() throws Exception{ + mockMvc.perform(post("/getNotification").header(CLIENTAUTHHEADER, "").content("test")).andExpect(status().isUnauthorized()); + mockMvc.perform(post("/getNotification").header(CLIENTAUTHHEADER, "Basic test123").content("test")).andExpect(status().isUnauthorized()); + mockMvc.perform(post("/getNotification").header(CLIENTAUTHHEADER, ERRORCLIENTVALUE).content(" ")).andExpect(status().isUnauthorized()); + } + + @Test + public void getNotificationTopicFailureTest() throws Exception{ + mockMvc.perform(post("/getNotification")).andExpect(status().isBadRequest()); + mockMvc.perform(post("/getNotification").headers(headers).content("")).andExpect(status().isBadRequest()); + } + + @Test + public void getNotificationTopicValidFailTest() throws Exception{ + // Check failures. + mockMvc.perform(post("/getNotification").headers(headers).content(" ")).andExpect(status().isBadRequest()); + mockMvc.perform(post("/stopNotification").headers(headers).content(" ")).andExpect(status().isBadRequest()); + mockMvc.perform(post("/sendHeartbeat").headers(headers).content(" ")).andExpect(status().isBadRequest()); + } + + @Test + public void getNotificationTopicValidPassTest() throws Exception{ + // Add a Topic. + mockMvc.perform(post("/getNotification").headers(headers).header(UUIDHEADER, "123").content("test")).andExpect(status().isOk()); + // Try to add same topic should fail. + mockMvc.perform(post("/getNotification").headers(headers).header(UUIDHEADER, UUID.randomUUID()).content("test")).andExpect(status().isBadRequest()); + // do a heart beat. + mockMvc.perform(post("/sendHeartbeat").headers(headers).content("test")).andExpect(status().isOk()); + // remove the added Topic. + mockMvc.perform(post("/stopNotification").headers(headers).content("test")).andExpect(status().isOk()); + // try to remove again should fail. + mockMvc.perform(post("/sendHeartbeat").headers(headers).content("test")).andExpect(status().isBadRequest()); + } + + @Test + public void sendEventTest() throws Exception{ + EventRequestParameters pep = new EventRequestParameters(); + Map<String,String> eventAttributes = new HashMap<>(); + eventAttributes.put("TEST", "test"); + pep.setEventAttributes(eventAttributes); + //Failure Tests. + mockMvc.perform(post("/sendEvent")).andExpect(status().isBadRequest()); + mockMvc.perform(post("/sendEvent").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + mockMvc.perform(post("/sendEvent").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "123")).andExpect(status().isOk()); + pep.setEventAttributes(null); + mockMvc.perform(post("/sendEvent").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setEventAttributes(eventAttributes); + mockMvc.perform(post("/sendEvent").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isOk()); + pep.setEventAttributes(eventAttributes); + pep.setRequestID(UUID.randomUUID()); + mockMvc.perform(post("/sendEvent").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isOk()); + } + + @Test + public void getDecisionTest() throws Exception{ + DecisionRequestParameters pep = new DecisionRequestParameters(); + Map<String,String> eventAttributes = new HashMap<>(); + eventAttributes.put("TEST", "test"); + pep.setONAPComponentName("te123"); + pep.setDecisionAttributes(eventAttributes); + //Failure Tests. + mockMvc.perform(post("/getDecision")).andExpect(status().isBadRequest()); + mockMvc.perform(post("/getDecision").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + mockMvc.perform(post("/getDecision").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "123")).andExpect(status().isOk()); + pep.setDecisionAttributes(null); + pep.setONAPComponentName(null); + mockMvc.perform(post("/getDecision").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setONAPComponentName("testing"); + mockMvc.perform(post("/getDecision").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setDecisionAttributes(eventAttributes); + pep.setRequestID(UUID.randomUUID()); + mockMvc.perform(post("/getDecision").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isOk()); + } + + @Test + public void pushPolicyTest() throws Exception{ + PushPolicyParameters pep = new PushPolicyParameters(); + //Failure Tests. + mockMvc.perform(put("/pushPolicy")).andExpect(status().isBadRequest()); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyName("scopeless"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyName("testing.test"); + pep.setPolicyType("wrong"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("BRMS_PARAM"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("BRMS_RAW"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("MicroService"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("ClosedLoop_PM"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("ClosedLoop_Fault"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("Base"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("Decision"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("Action"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("Firewall"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPdpGroup("default"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "123")).andExpect(status().isBadRequest()); + pep.setRequestID(UUID.randomUUID()); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + } + + @Test + public void deletePolicyTest() throws Exception{ + DeletePolicyParameters pep = new DeletePolicyParameters(); + //Failure Tests. + mockMvc.perform(delete("/deletePolicy")).andExpect(status().isBadRequest()); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyName("testing"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "test123")).andExpect(status().isBadRequest()); + pep.setPolicyName("testscope.name"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyName("testscope.name"); + pep.setPolicyType("wrong"); + pep.setRequestID(UUID.randomUUID()); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("BRMS_PARAM"); + pep.setPolicyComponent("wrong"); + pep.setRequestID(null); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("BRMS_RAW"); + pep.setPolicyComponent("PDP"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyType("MicroService"); + pep.setPolicyComponent("PAP"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyType("ClosedLoop_PM"); + pep.setPolicyComponent("PDP"); + pep.setDeleteCondition(DeletePolicyCondition.ALL); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyType("ClosedLoop_Fault"); + pep.setDeleteCondition(DeletePolicyCondition.ONE); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyType("Base"); + pep.setPolicyComponent("PAP"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyType("Decision"); + pep.setPolicyComponent("PDP"); + pep.setPolicyName("test.xml"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyType("Action"); + pep.setPolicyName("scope.Config_test.xml"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPdpGroup("default"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyComponent("PAP"); + pep.setPolicyType("Firewall"); + pep.setDeleteCondition(null); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyComponent("PAP"); + pep.setDeleteCondition(DeletePolicyCondition.ONE); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyComponent("fail"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyComponent("PDP"); + pep.setPolicyName("testscope.policyName"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyComponent(null); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + } + + @Test + public void createUpdatePolicyTest() throws Exception{ + PolicyParameters pep = new PolicyParameters(); + //Failure Tests. + mockMvc.perform(put("/createPolicy")).andExpect(status().isBadRequest()); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + setCreateUpdateImpl(); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyName("failName"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "test 123")).andExpect(status().isBadRequest()); + pep.setPolicyName("test. name"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyName(" "); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyName("test. "); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyName("te st.name"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyName("test.name"); + pep.setPolicyDescription("testá"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyName("test.name"); + pep.setPolicyDescription("good"); + pep.setTtlDate(new Date()); + pep.setRequestID(UUID.randomUUID()); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + } + + @Test + public void brmsPolicyCreationTests() throws Exception{ + PolicyParameters pep = new PolicyParameters(); + pep.setPolicyName("test.name"); + pep.setPolicyDescription("good"); + pep.setTtlDate(new Date()); + pep.setRequestID(UUID.randomUUID()); + setCreateUpdateImpl(); + // Checks for BRMS Param Policy. + pep.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setRiskLevel("test"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + Map<AttributeType, Map<String,String>> attributes = new HashMap<>(); + Map<String,String> matching = new HashMap<>(); + matching.put("key", "value"); + attributes.put(AttributeType.MATCHING, matching); + pep.setAttributes(attributes); + pep.setRiskLevel("5"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + // Checks for BRMS Raw Policy + pep.setPolicyConfigType(PolicyConfigType.BRMS_RAW); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("test"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setRiskLevel(null); + pep.setConfigBody("package droolsexample\n\n import com.sample.ItemCity;\nimport java.math.BigDecimal;\nrule \"Nagpur Medicine Item\"\n\n when\n item : ItemCity(purchaseCity == ItemCity.City.NAGPUR,\n typeofItem == ItemCity.Type.MEDICINES)\n then\n BigDecimal tax = new BigDecimal(0.0);\n item.setLocalTax(tax.multiply(item.getSellPrice()));\nend"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setRiskLevel("5"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + } + + @Test + public void baseConfigTests() throws Exception{ + PolicyParameters pep = new PolicyParameters(); + pep.setPolicyName("test.name"); + pep.setPolicyDescription("good"); + pep.setTtlDate(new Date()); + pep.setRequestID(UUID.randomUUID()); + setCreateUpdateImpl(); + // Checks for Base config Policy. + pep.setPolicyConfigType(PolicyConfigType.Base); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("testbody"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBodyType(PolicyType.OTHER); + pep.setRiskLevel("test"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setRiskLevel("4"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setOnapName("ec nam-e"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setOnapName("onapName"); + pep.setConfigName("tes config"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigName("configName"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + pep.setConfigBody("{'test':'test}"); + pep.setConfigBodyType(PolicyType.JSON); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + Map<AttributeType, Map<String,String>> attributes = new HashMap<>(); + Map<String,String> matching = new HashMap<>(); + matching.put("key", "value"); + attributes.put(AttributeType.MATCHING, matching); + pep.setAttributes(attributes); + pep.setConfigBody("testBody"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + } + + @Test + public void closedLoopPolicyTests() throws Exception{ + PolicyParameters pep = new PolicyParameters(); + pep.setPolicyName("test.name"); + pep.setPolicyDescription("good"); + pep.setTtlDate(new Date()); + pep.setRequestID(UUID.randomUUID()); + setCreateUpdateImpl(); + // Checks for Closed loop Policy. + pep.setPolicyConfigType(PolicyConfigType.ClosedLoop_Fault); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("te stá"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("testBody"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"key\":\"value\"}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"onapname\":\"\"}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"onapname\":\"test\"}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + pep.setRiskLevel("test"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setRiskLevel("4"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + } + + @Test + public void closedLoopPMTests() throws Exception{ + PolicyParameters pep = new PolicyParameters(); + pep.setPolicyName("test.name"); + pep.setPolicyDescription("good"); + pep.setTtlDate(new Date()); + pep.setRequestID(UUID.randomUUID()); + setCreateUpdateImpl(); + // Checks for Closed loop Policy. + pep.setPolicyConfigType(PolicyConfigType.ClosedLoop_PM); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("te stá"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("testBody"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"key\":\"value\"}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"onapname\":\"\"}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"onapname\":\"test\"}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"onapname\":\"test\", \"serviceTypePolicyName\":\"value\"}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + pep.setRiskLevel("test"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setRiskLevel("4"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + } + + @Test + public void firewallPolicyTests() throws Exception{ + PolicyParameters pep = new PolicyParameters(); + pep.setPolicyName("test.name"); + pep.setPolicyDescription("good"); + pep.setTtlDate(new Date()); + pep.setRequestID(UUID.randomUUID()); + setCreateUpdateImpl(); + // Checks for Closed loop Policy. + pep.setPolicyConfigType(PolicyConfigType.Firewall); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("te st"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"test\":\"test\"}"); + pep.setRiskLevel("test"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setRiskLevel("4"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"configName\":\"test\"}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + } + + @Test + public void microServicePolicyTests() throws Exception{ + PolicyParameters pep = new PolicyParameters(); + pep.setPolicyName("test.name"); + pep.setPolicyDescription("good"); + pep.setTtlDate(new Date()); + pep.setRequestID(UUID.randomUUID()); + setCreateUpdateImpl(); + // Checks for Closed loop Policy. + pep.setPolicyConfigType(PolicyConfigType.MicroService); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("te st"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"test\":\"test\"}"); + pep.setOnapName(" "); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setOnapName("testonap"); + pep.setRiskLevel("fail"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setRiskLevel("4"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + pep.setConfigBody("{\"service\":\"test\",\"uuid\":\"test\",\"location\":\"test\",\"configName\":\"test\",\"description\":\"test\",\"priority\":\"test\",\"version\":\"test\"}"); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + } + + @Test + public void actionDecisionPolicyCreationTests() throws Exception{ + PolicyParameters pep = new PolicyParameters(); + pep.setPolicyName("test.name"); + pep.setPolicyDescription("good"); + pep.setTtlDate(new Date()); + pep.setRequestID(UUID.randomUUID()); + setCreateUpdateImpl(); + // Checks for action Policy. + pep.setPolicyClass(PolicyClass.Action); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + Map<AttributeType, Map<String,String>> attributes = new HashMap<>(); + pep.setAttributes(attributes); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + attributes.put(AttributeType.MATCHING, new HashMap<>()); + pep.setAttributes(attributes); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + Map<String,String> matching = new HashMap<>(); + matching.put("key", "value"); + attributes.put(AttributeType.MATCHING, matching); + pep.setAttributes(attributes); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setActionAttribute("A1"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setActionPerformer("PEX"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setActionPerformer("PEP"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + // Checks for Decision Policy. + pep.setPolicyClass(PolicyClass.Decision); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setOnapName("xyz"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + attributes.remove(AttributeType.MATCHING); + attributes.put(AttributeType.SETTINGS, matching); + pep.setAttributes(attributes); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + attributes.put(AttributeType.MATCHING, matching); + pep.setAttributes(attributes); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + } + + @Test + public void createUpdateDictionaryTests() throws Exception{ + DictionaryParameters pep = new DictionaryParameters(); + //Failure Tests. + mockMvc.perform(put("/createDictionaryItem")).andExpect(status().isBadRequest()); + mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + mockMvc.perform(put("/updateDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + pep.setDictionaryType(DictionaryType.MicroService); + mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setDictionary("test dict"); + pep.setRequestID(UUID.randomUUID()); + mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setDictionaryJson("{\"test\":\"value\"}"); + mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isInternalServerError()); + pep.setDictionaryJson("test123"); + mockMvc.perform(put("/updateDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "123")).andExpect(status().isBadRequest()); + pep.setDictionary("MicroServiceDictionary"); + mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + } + + @Test + public void getDictionaryTests() throws Exception{ + DictionaryParameters pep = new DictionaryParameters(); + //Failure Tests. + mockMvc.perform(post("/getDictionaryItems")).andExpect(status().isBadRequest()); + mockMvc.perform(post("/getDictionaryItems").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + mockMvc.perform(post("/getDictionaryItems").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + pep.setDictionaryType(DictionaryType.Common); + mockMvc.perform(post("/getDictionaryItems").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID().toString())).andExpect(status().isBadRequest()); + pep.setDictionary("OnapName"); + mockMvc.perform(post("/getDictionaryItems").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + pep.setRequestID(UUID.randomUUID()); + mockMvc.perform(post("/getDictionaryItems").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + } + + @Test + public void policyEngineImportTests() throws Exception{ + //Failure Tests. + mockMvc.perform(post("/policyEngineImport")).andExpect(status().isBadRequest()); + } + + @Test + public void oldConfigAPITests() throws Exception{ + ConfigPolicyAPIRequest pep = new ConfigPolicyAPIRequest(); + //Failure Tests. + mockMvc.perform(put("/createConfig")).andExpect(status().isBadRequest()); + mockMvc.perform(put("/createConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + mockMvc.perform(put("/updateConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + mockMvc.perform(put("/createConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + pep.setPolicyScope("test"); + mockMvc.perform(put("/createConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + pep.setPolicyName("name"); + mockMvc.perform(put("/createConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + pep.setConfigType("OTHER"); + mockMvc.perform(put("/createConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + pep.setTtlDate(new Date().toString()); + mockMvc.perform(put("/updateConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + } + + @Test + public void oldFirewallAPITests() throws Exception{ + ConfigFirewallPolicyAPIRequest pep = new ConfigFirewallPolicyAPIRequest(); + //Failure Tests. + mockMvc.perform(put("/createFirewallConfig")).andExpect(status().isBadRequest()); + mockMvc.perform(put("/createFirewallConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + mockMvc.perform(put("/updateFirewallConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + mockMvc.perform(put("/createFirewallConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + pep.setPolicyScope("test"); + mockMvc.perform(put("/createFirewallConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + pep.setPolicyName("name"); + mockMvc.perform(put("/createFirewallConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + pep.setTtlDate(new Date().toString()); + mockMvc.perform(put("/updateFirewallConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + } + + private void setCreateUpdateImpl() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method setter = XACMLPdpServlet.class.getDeclaredMethod("setCreateUpdatePolicyConstructor", String.class); + setter.setAccessible(true); + setter.invoke(new XACMLPdpServlet(), CreateUpdatePolicyServiceImpl.class.getName()); + } + + //Health Check Tests + @Test + public void getCountTest() throws Exception { + mockMvc.perform(get("/count")) + .andExpect(status().isOk()); + } +} diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/getConfigTest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/getConfigTest.java new file mode 100644 index 000000000..2d79b234a --- /dev/null +++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/getConfigTest.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.policy.pdp.rest.api.test; + +import static org.junit.Assert.assertEquals; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.junit.Test; +import org.onap.policy.api.ConfigRequestParameters; +import org.onap.policy.api.PolicyConfigStatus; +import org.onap.policy.pdp.rest.api.models.PolicyConfig; +import org.onap.policy.pdp.rest.api.services.GetConfigService; + +public class getConfigTest { + private static final String TEST = "test"; + + @SuppressWarnings("unchecked") + @Test + public void filterMethodTest() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{ + ConfigRequestParameters configRequestParameters = new ConfigRequestParameters(); + GetConfigService getConfigService= new GetConfigService(configRequestParameters, null); + Method filter = GetConfigService.class.getDeclaredMethod("filterResults", Collection.class,ConfigRequestParameters.class); + filter.setAccessible(true); + List<PolicyConfig> policyConfigs = new LinkedList<>(); + + List<PolicyConfig> filterResults = (List<PolicyConfig>) filter.invoke(getConfigService, policyConfigs,configRequestParameters); + assertEquals(PolicyConfigStatus.CONFIG_NOT_FOUND, filterResults.get(0).getPolicyConfigStatus()); + // Check again with some values + configRequestParameters.setPolicyName(TEST); + configRequestParameters.setOnapName(TEST); + configRequestParameters.setConfigName(TEST); + Map<String,String> configAttributes = new HashMap<>(); + configAttributes.put(TEST, TEST); + configRequestParameters.setConfigAttributes(configAttributes); + PolicyConfig pConfig = new PolicyConfig(); + pConfig.setPolicyName(TEST); + Map<String,String> matching = new HashMap<>(); + matching.put("ONAPName", TEST); + matching.put("ConfigName", TEST); + matching.put("TEST", TEST); + pConfig.setMatchingConditions(matching); + policyConfigs.add(pConfig); + filterResults = (List<PolicyConfig>) filter.invoke(getConfigService, policyConfigs,configRequestParameters); + assertEquals(PolicyConfigStatus.CONFIG_NOT_FOUND, filterResults.get(0).getPolicyConfigStatus()); + } +} diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/getDictionaryTest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/getDictionaryTest.java new file mode 100644 index 000000000..e18f8bb03 --- /dev/null +++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/getDictionaryTest.java @@ -0,0 +1,231 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.policy.pdp.rest.api.test; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.lang.reflect.Method; + +import org.junit.Test; +import org.onap.policy.api.DictionaryParameters; +import org.onap.policy.pdp.rest.api.services.GetDictionaryService; + +public class getDictionaryTest { + + @Test + public void dictionaryJsonTest() throws Exception{ + Method formatDictionary = GetDictionaryService.class.getDeclaredMethod("formatDictionaryJson", String.class); + formatDictionary.setAccessible(true); + String input="{\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\"," + + "\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\"," + + "\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\"}"; + DictionaryParameters dp = new DictionaryParameters(); + dp.setDictionary("test"); + GetDictionaryService gds = new GetDictionaryService(dp, null); + String result = (String) formatDictionary.invoke(gds, input); + assertNull(result); + // + dp.setDictionary("OnapName"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("Attribute"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("Action"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("BRMSParamTemplate"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("VSCLAction"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("VNFType"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("PEPOptions"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("Varbind"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("Service"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("Site"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("Settings"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("DescriptiveScope"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("Enforcer"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("ActionList"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("ProtocolList"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("Zone"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("SecurityZone"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("PrefixList"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("AddressGroup"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("ServiceGroup"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("ServiceList"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("TermList"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("RuleList"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("FirewallRuleList"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("Term"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("MicroServiceLocation"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("MicroServiceConfigName"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("DCAEUUID"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("MicroServiceModels"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("PolicyScopeService"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("PolicyScopeResource"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("PolicyScopeType"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("PolicyScopeClosedLoop"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("GroupPolicyScopeList"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("RiskType"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("SafePolicyWarning"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("MicroServiceDictionary"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + } +} diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/auth/test/FilterTests.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/auth/test/FilterTests.java new file mode 100644 index 000000000..88369850f --- /dev/null +++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/auth/test/FilterTests.java @@ -0,0 +1,199 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.pdp.rest.auth.test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.pdp.rest.restAuth.PDPAuthenticationFilter; + +import com.att.research.xacml.util.XACMLProperties; +import com.mockrunner.mock.web.MockRequestDispatcher; + +public class FilterTests { + + private PDPAuthenticationFilter authenticationFilter = new PDPAuthenticationFilter(); + private final String VALIDHEADERVALUE = "Basic dGVzdHBkcDphbHBoYTQ1Ng=="; + + @Before + public void setUp() throws Exception{ + authenticationFilter.init(null); + XACMLProperties.reloadProperties(); + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/pass.xacml.pdp.properties"); + XACMLProperties.getProperties(); + } + + @Test + public void testDoFilterError() throws IOException, ServletException { + // create the objects to be mocked + HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); + HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); + FilterChain filterChain = mock(FilterChain.class); + // + when(httpServletRequest.getRequestURI()).thenReturn("error"); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + // verify if unauthorized + verify(httpServletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } + + @Test + public void testDoFilterNotification() throws IOException, ServletException { + // create the objects to be mocked + HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); + HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); + FilterChain filterChain = mock(FilterChain.class); + // + when(httpServletRequest.getRequestURI()).thenReturn("notifications"); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + verify(filterChain).doFilter(httpServletRequest,httpServletResponse); + } + + @Test + public void testDoFilterSwagger() throws Exception{ + // create the objects to be mocked + HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); + HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); + FilterChain filterChain = mock(FilterChain.class); + // + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/swagger"); + when(httpServletRequest.getRequestDispatcher("/api/swagger")).thenReturn(new MockRequestDispatcher()); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + verify(httpServletRequest).getRequestDispatcher("/api/swagger"); + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/api-docs/"); + when(httpServletRequest.getRequestDispatcher("/api/api-docs/")).thenReturn(new MockRequestDispatcher()); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + verify(httpServletRequest).getRequestDispatcher("/api/api-docs/"); + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/configuration"); + when(httpServletRequest.getRequestDispatcher("/api/configuration")).thenReturn(new MockRequestDispatcher()); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + verify(httpServletRequest).getRequestDispatcher("/api/configuration"); + } + + @Test + public void newRequestAuthFailTest() throws Exception{ + // create the objects to be mocked + HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); + HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); + FilterChain filterChain = mock(FilterChain.class); + // + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/api/getConfig"); + when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn("error"); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + // verify if unauthorized + verify(httpServletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } + + @Test + public void tokenFailureTest() throws Exception{ + // create the objects to be mocked + HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); + HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); + FilterChain filterChain = mock(FilterChain.class); + // + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/api/getConfig"); + when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn("Basic test123"); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + // verify if unauthorized + verify(httpServletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } + + @Test + public void oldRequestAuthPassTest() throws Exception{ + // create the objects to be mocked + HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); + HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); + FilterChain filterChain = mock(FilterChain.class); + // New request no environment header check + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/api/getConfig"); + when(httpServletRequest.getRequestDispatcher("/api/getConfig")).thenReturn(new MockRequestDispatcher()); + when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn(VALIDHEADERVALUE); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + // verify if authorized + verify(httpServletRequest).getRequestDispatcher("/api/getConfig"); + // + // Old Requests Checks + // + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/getConfig"); + when(httpServletRequest.getRequestDispatcher("/api//getConfig")).thenReturn(new MockRequestDispatcher()); + when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn(VALIDHEADERVALUE); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + // verify if authorized + verify(httpServletRequest).getRequestDispatcher("/api//getConfig"); + } + + @Test + public void newRequestAuthPassTest() throws Exception{ + // create the objects to be mocked + HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); + HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); + FilterChain filterChain = mock(FilterChain.class); + // + // Requests with Valid Environment Header values. + // + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/getConfig"); + when(httpServletRequest.getRequestDispatcher("/api//getConfig")).thenReturn(new MockRequestDispatcher()); + when(httpServletRequest.getHeader(PDPAuthenticationFilter.ENVIRONMENT_HEADER)).thenReturn("DEVL"); + when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn(VALIDHEADERVALUE); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + // verify if authorized + verify(httpServletRequest).getRequestDispatcher("/api//getConfig"); + // New request no environment header check + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/api/getConfig"); + when(httpServletRequest.getRequestDispatcher("/api/getConfig")).thenReturn(new MockRequestDispatcher()); + when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn(VALIDHEADERVALUE); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + // verify if authorized + verify(httpServletRequest).getRequestDispatcher("/api/getConfig"); + // + // + // Requests with InValid Environment Header + // + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/getConfig"); + when(httpServletRequest.getRequestDispatcher("/api//getConfig")).thenReturn(new MockRequestDispatcher()); + when(httpServletRequest.getHeader(PDPAuthenticationFilter.ENVIRONMENT_HEADER)).thenReturn("TEST"); + when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn(VALIDHEADERVALUE); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + // verify if unauthorized + verify(httpServletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } +} diff --git a/ONAP-PDP-REST/src/test/resources/client.properties b/ONAP-PDP-REST/src/test/resources/client.properties new file mode 100644 index 000000000..13aa106cd --- /dev/null +++ b/ONAP-PDP-REST/src/test/resources/client.properties @@ -0,0 +1,2 @@ +#Don't Change this +python=test,MASTER
\ No newline at end of file diff --git a/ONAP-PDP-REST/src/test/resources/fail.xacml.pdp.properties b/ONAP-PDP-REST/src/test/resources/fail.xacml.pdp.properties new file mode 100644 index 000000000..a16b422bf --- /dev/null +++ b/ONAP-PDP-REST/src/test/resources/fail.xacml.pdp.properties @@ -0,0 +1,171 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PDP-REST +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END========================================================= +### + +# Default XACML Properties File for PDP RESTful servlet +# +# Standard API Factories +# +xacml.dataTypeFactory=com.att.research.xacml.std.StdDataTypeFactory +xacml.pdpEngineFactory=com.att.research.xacmlatt.pdp.ATTPDPEngineFactory +xacml.pepEngineFactory=com.att.research.xacml.std.pep.StdEngineFactory +# NOT USED SEE BELOW xacml.pipFinderFactory=org.onap.policy.xacml.std.pip.StdPIPFinderFactory +xacml.traceEngineFactory=com.att.research.xacml.std.trace.LoggingTraceEngineFactory +# +# AT&T PDP Implementation Factories +# +xacml.att.evaluationContextFactory=com.att.research.xacmlatt.pdp.std.StdEvaluationContextFactory +xacml.att.combiningAlgorithmFactory=com.att.research.xacmlatt.pdp.std.StdCombiningAlgorithmFactory +xacml.att.functionDefinitionFactory=org.onap.policy.xacml.custom.OnapFunctionDefinitionFactory +# NOT USED SEE BELOW xacml.att.policyFinderFactory=org.onap.policy.pdp.std.StdPolicyFinderFactory +# creteUpdate Policy Implementation Class details. +createUpdatePolicy.impl.className=org.onap.policy.pdp.rest.api.services.CreateUpdatePolicyServiceImpl +# AAF Implementation class details +aafClient.impl.className=org.onap.policy.utils.AAFPolicyClientImpl +# +# AT&T RESTful PDP Implementation Factories +# +xacml.pipFinderFactory=org.onap.policy.pdp.rest.impl.XACMLPdpPIPFinderFactory +xacml.att.policyFinderFactory=org.onap.policy.pdp.rest.XACMLPdpPolicyFinderFactory +# +# When set to true, this flag tells the StdPolicyFinderFactory to combined all the root policy files into +# into one PolicySet and use the given Policy Algorithm. +# +xacml.att.policyFinderFactory.combineRootPolicies=urn:com:att:xacml:3.0:policy-combining-algorithm:combined-permit-overrides +# +# PDP RESTful API properties +# +# Set this to the address where the XACML-PAP-REST servlet is running +xacml.rest.pap.url=http://localhost:8070/pap/ + +#if multiple paps exist, the xacml.rest.pap.url can be removed and they can be defined like this: +#xacml.rest.pap.urls=http://localhost:9090/pap/,http://localhost:9091/pap/ + +# +# Give the running PDP an ID for the PAP. The url that its running as is a good choice. +# The PAP identifies PDP's using the URL of the PDP. +# +xacml.rest.pdp.id=http://localhost:8082/pdp/ + +# Give the port number used for the PDP + +xacml.jmx.port=0 + + +# Notification Properties +# Notifcation type: websocket, ueb or dmaap... if left blank websocket is the default +NOTIFICATION_TYPE=websocket +NOTIFICATION_SERVERS= +NOTIFICATION_TOPIC= +NOTIFICATION_DELAY=500 +UEB_API_KEY= +UEB_API_SECRET= +DMAAP_AAF_LOGIN=test +DMAAP_AAF_PASSWORD=test + +# +# Set the directory where the PDP holds its Policy Cache and PIP Configuration +# +xacml.rest.pdp.config=config + +xacml.rest.pdp.webapps=/home/users/PolicyEngine/webapps/ConfigPAP/ +# +# Initialize register with PAP servlet +# +xacml.rest.pdp.register=true +# +# Sleep period in seconds between register attempts +# +xacml.rest.pdp.register.sleep=15 +# +# number of attempts to register. -1 means keep trying forever. +# +xacml.rest.pdp.register.retries=-1 +# +# max number of bytes in a POST of a XML/JSON request +# old value #32767 +xacml.rest.pdp.maxcontent=99999999 +# +# Set UserID here +xacml.rest.pdp.userid=testpdp +# Set Password here +xacml.rest.pdp.password=alpha456 + +# id PAP +xacml.rest.pap.userid=testpap +#if multiple paps have different logins, they can be defined like this: +#http\://localhost\:9090/pap/.xacml.rest.pap.userid=testpap + +# pass PAP +xacml.rest.pap.password=alpha123 +#http\://localhost\:9090/pap/.xacml.rest.pap.password=alpha123 + +# Delay for Notifications Don't change this. Value in milliSec. +xacml.rest.notification.delay=30 +# Buffer Size. +REQUEST_BUFFER_SIZE=15 + +#properties for MySql xacml database: PLEASE DO NOT REMOVE... NEEDED FOR APIs +javax.persistence.jdbc.driver=com.mysql.jdbc.Driver +javax.persistence.jdbc.url=jdbc:mysql://localhost:3306/xacml +javax.persistence.jdbc.user=policy_user +javax.persistence.jdbc.password=policy_user + + +#***Properties for IntegrityMonitor integration defined in XACMLRestProperties.java*** + +#The name of the PDP. Must be unique across the system +xacml.rest.pdp.resource.name=site_1.pdp_1 + +#***Properties for IntegrityMonitor integration defined in IntegrityMonitorProperties.java*** + +#Interval between forward progress counter updates in seconds +fp_monitor_interval=30 + +#Number of forward progress counter failures before failover +failed_counter_threshold=3 + +#Interval in seconds between test transactions if there is no other traffic +test_trans_interval=10 + +#Interval in seconds between updates of the forward progress counter in the DB +write_fpc_interval=5 + +#Name of the site +site_name=site_1 + +#Node type +node_type=pdp_xacml + +#Dependency groups are groups of resources upon which a node operational state is dependent upon). +#Each group is a comma-separated list of resource names and groups are separated by a semicolon. +#A group may contain one or more members. Resource names must match the resource names defined +#in the respective servers' properties files +dependency_groups=site_1.pdplp_1;site_1.astragw_1;site_1.brmsgw_1 + +# this can be DEVL, TEST, PROD +ENVIRONMENT=DEVL +xacml.rest.pep.idfile = src/test/resources/client.properties + +#AAF Policy Name space +#Not Mandatory for Open Onap +policy.aaf.namespace = +policy.aaf.resource = +# +DMAAP_AAF_LOGIN = diff --git a/ONAP-PDP-REST/src/test/resources/pass.xacml.pdp.properties b/ONAP-PDP-REST/src/test/resources/pass.xacml.pdp.properties new file mode 100644 index 000000000..c9a111012 --- /dev/null +++ b/ONAP-PDP-REST/src/test/resources/pass.xacml.pdp.properties @@ -0,0 +1,171 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PDP-REST +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# ================================================================================ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============LICENSE_END========================================================= +### + +# Default XACML Properties File for PDP RESTful servlet +# +# Standard API Factories +# +xacml.dataTypeFactory=com.att.research.xacml.std.StdDataTypeFactory +xacml.pdpEngineFactory=com.att.research.xacmlatt.pdp.ATTPDPEngineFactory +xacml.pepEngineFactory=com.att.research.xacml.std.pep.StdEngineFactory +# NOT USED SEE BELOW xacml.pipFinderFactory=org.onap.policy.xacml.std.pip.StdPIPFinderFactory +xacml.traceEngineFactory=com.att.research.xacml.std.trace.LoggingTraceEngineFactory +# +# AT&T PDP Implementation Factories +# +xacml.att.evaluationContextFactory=com.att.research.xacmlatt.pdp.std.StdEvaluationContextFactory +xacml.att.combiningAlgorithmFactory=com.att.research.xacmlatt.pdp.std.StdCombiningAlgorithmFactory +xacml.att.functionDefinitionFactory=org.onap.policy.xacml.custom.OnapFunctionDefinitionFactory +# NOT USED SEE BELOW xacml.att.policyFinderFactory=org.onap.policy.pdp.std.StdPolicyFinderFactory +# creteUpdate Policy Implementation Class details. +createUpdatePolicy.impl.className=org.onap.policy.pdp.rest.api.services.CreateUpdatePolicyServiceImpl +# AAF Implementation class details +aafClient.impl.className=org.onap.policy.utils.AAFPolicyClientImpl +# +# AT&T RESTful PDP Implementation Factories +# +xacml.pipFinderFactory=org.onap.policy.pdp.rest.impl.XACMLPdpPIPFinderFactory +xacml.att.policyFinderFactory=org.onap.policy.pdp.rest.XACMLPdpPolicyFinderFactory +# +# When set to true, this flag tells the StdPolicyFinderFactory to combined all the root policy files into +# into one PolicySet and use the given Policy Algorithm. +# +xacml.att.policyFinderFactory.combineRootPolicies=urn:com:att:xacml:3.0:policy-combining-algorithm:combined-permit-overrides +# +# PDP RESTful API properties +# +# Set this to the address where the XACML-PAP-REST servlet is running +xacml.rest.pap.url=http://localhost:8070/pap/ + +#if multiple paps exist, the xacml.rest.pap.url can be removed and they can be defined like this: +#xacml.rest.pap.urls=http://localhost:9090/pap/,http://localhost:9091/pap/ + +# +# Give the running PDP an ID for the PAP. The url that its running as is a good choice. +# The PAP identifies PDP's using the URL of the PDP. +# +xacml.rest.pdp.id=http://localhost:8082/pdp/ + +# Give the port number used for the PDP + +xacml.jmx.port=0 + + +# Notification Properties +# Notifcation type: websocket, ueb or dmaap... if left blank websocket is the default +NOTIFICATION_TYPE=websocket +NOTIFICATION_SERVERS=test +NOTIFICATION_TOPIC=test +NOTIFICATION_DELAY=500 +UEB_API_KEY= +UEB_API_SECRET= +DMAAP_AAF_LOGIN=test +DMAAP_AAF_PASSWORD=test + +# +# Set the directory where the PDP holds its Policy Cache and PIP Configuration +# +xacml.rest.pdp.config=config + +xacml.rest.pdp.webapps=/home/users/PolicyEngine/webapps/ConfigPAP/ +# +# Initialize register with PAP servlet +# +xacml.rest.pdp.register=true +# +# Sleep period in seconds between register attempts +# +xacml.rest.pdp.register.sleep=15 +# +# number of attempts to register. -1 means keep trying forever. +# +xacml.rest.pdp.register.retries=-1 +# +# max number of bytes in a POST of a XML/JSON request +# old value #32767 +xacml.rest.pdp.maxcontent=99999999 +# +# Set UserID here +xacml.rest.pdp.userid=testpdp +# Set Password here +xacml.rest.pdp.password=alpha456 + +# id PAP +xacml.rest.pap.userid=testpap +#if multiple paps have different logins, they can be defined like this: +#http\://localhost\:9090/pap/.xacml.rest.pap.userid=testpap + +# pass PAP +xacml.rest.pap.password=alpha123 +#http\://localhost\:9090/pap/.xacml.rest.pap.password=alpha123 + +# Delay for Notifications Don't change this. Value in milliSec. +xacml.rest.notification.delay=30 +# Buffer Size. +REQUEST_BUFFER_SIZE=15 + +#properties for MySql xacml database: PLEASE DO NOT REMOVE... NEEDED FOR APIs +javax.persistence.jdbc.driver=com.mysql.jdbc.Driver +javax.persistence.jdbc.url=jdbc:mysql://localhost:3306/xacml +javax.persistence.jdbc.user=policy_user +javax.persistence.jdbc.password=policy_user + + +#***Properties for IntegrityMonitor integration defined in XACMLRestProperties.java*** + +#The name of the PDP. Must be unique across the system +xacml.rest.pdp.resource.name=site_1.pdp_1 + +#***Properties for IntegrityMonitor integration defined in IntegrityMonitorProperties.java*** + +#Interval between forward progress counter updates in seconds +fp_monitor_interval=30 + +#Number of forward progress counter failures before failover +failed_counter_threshold=3 + +#Interval in seconds between test transactions if there is no other traffic +test_trans_interval=10 + +#Interval in seconds between updates of the forward progress counter in the DB +write_fpc_interval=5 + +#Name of the site +site_name=site_1 + +#Node type +node_type=pdp_xacml + +#Dependency groups are groups of resources upon which a node operational state is dependent upon). +#Each group is a comma-separated list of resource names and groups are separated by a semicolon. +#A group may contain one or more members. Resource names must match the resource names defined +#in the respective servers' properties files +dependency_groups=site_1.pdplp_1;site_1.astragw_1;site_1.brmsgw_1 + +# this can be DEVL, TEST, PROD +ENVIRONMENT=DEVL +xacml.rest.pep.idfile = src/test/resources/client.properties + +#AAF Policy Name space +#Not Mandatory for Open Onap +policy.aaf.namespace = +policy.aaf.resource = +# +DMAAP_AAF_LOGIN = diff --git a/ONAP-PDP-REST/src/test/resources/test.drl b/ONAP-PDP-REST/src/test/resources/test.drl new file mode 100644 index 000000000..7accc63ae --- /dev/null +++ b/ONAP-PDP-REST/src/test/resources/test.drl @@ -0,0 +1,1121 @@ +/*- + * ============LICENSE_START======================================================= + * archetype-closed-loop-demo-rules + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop; + +import java.util.List; +import java.util.LinkedList; +import java.util.Map; +import java.util.HashMap; +import java.util.UUID; + +import org.onap.policy.controlloop.VirtualControlLoopEvent; +import org.onap.policy.controlloop.ControlLoopEventStatus; +import org.onap.policy.controlloop.VirtualControlLoopNotification; +import org.onap.policy.controlloop.ControlLoopNotificationType; +import org.onap.policy.controlloop.ControlLoopOperation; +import org.onap.policy.controlloop.ControlLoopOperationWrapper; +import org.onap.policy.template.demo.ControlLoopException; + +import org.onap.policy.aai.AAINQF199.AAINQF199CloudRegion; +import org.onap.policy.aai.AAINQF199.AAINQF199ExtraProperties; +import org.onap.policy.aai.AAINQF199.AAINQF199ExtraProperty; +import org.onap.policy.aai.AAINQF199.AAINQF199GenericVNF; +import org.onap.policy.aai.AAINQF199.AAINQF199InstanceFilters; +import org.onap.policy.aai.AAINQF199.AAINQF199InventoryResponseItem; +import org.onap.policy.aai.AAINQF199.AAINQF199InventoryResponseItems; +import org.onap.policy.aai.AAINQF199.AAINQF199Manager; +import org.onap.policy.aai.AAINQF199.AAINQF199NamedQuery; +import org.onap.policy.aai.AAINQF199.AAINQF199QueryParameters; +import org.onap.policy.aai.AAINQF199.AAINQF199Request; +import org.onap.policy.aai.AAINQF199.AAINQF199RequestWrapper; +import org.onap.policy.aai.AAINQF199.AAINQF199Response; +import org.onap.policy.aai.AAINQF199.AAINQF199ResponseWrapper; +import org.onap.policy.aai.AAINQF199.AAINQF199ServiceInstance; +import org.onap.policy.aai.AAINQF199.AAINQF199Tenant; +import org.onap.policy.aai.AAINQF199.AAINQF199VfModule; +import org.onap.policy.aai.AAINQF199.AAINQF199VServer; +import org.onap.policy.aai.util.Serialization; + +import org.onap.policy.appc.CommonHeader; +import org.onap.policy.appc.Request; +import org.onap.policy.appc.Response; +import org.onap.policy.appc.ResponseCode; +import org.onap.policy.appc.ResponseStatus; +import org.onap.policy.appc.ResponseValue; + +import org.onap.policy.template.demo.EventManager; +import org.onap.policy.vnf.trafficgenerator.PGRequest; +import org.onap.policy.vnf.trafficgenerator.PGStream; +import org.onap.policy.vnf.trafficgenerator.PGStreams; + +import org.onap.policy.mso.MSOManager; +import org.onap.policy.mso.MSORequest; +import org.onap.policy.mso.MSORequestStatus; +import org.onap.policy.mso.MSORequestDetails; +import org.onap.policy.mso.MSOModelInfo; +import org.onap.policy.mso.MSOCloudConfiguration; +import org.onap.policy.mso.MSORequestInfo; +import org.onap.policy.mso.MSORequestParameters; +import org.onap.policy.mso.MSORelatedInstanceListElement; +import org.onap.policy.mso.MSORelatedInstance; +import org.onap.policy.mso.MSOResponse; + +import org.onap.policy.drools.system.PolicyEngine; + +// +// These parameters are required to build the runtime policy +// +declare Params + closedLoopControlName : String + actor : String + aaiURL : String + aaiUsername : String + aaiPassword : String + msoURL : String + msoUsername : String + msoPassword : String + aaiNamedQueryUUID : String + aaiPatternMatch : int + notificationTopic : String + appcTopic : String +end + +/* +* +* Called once and only once to insert the parameters into working memory for this Closed Loop policy. +* (Comment SETUP rule out for the first ONAP opensource release since policy BRMS_GW already puts a Params fact in there) +* +* +*rule "${policyName}.SETUP" +* when +* then +* System.out.println("rule SETUP is triggered."); +* Params params = new Params(); +* params.setClosedLoopControlName("${closedLoopControlName}"); +* params.setActor("${actor}"); +* params.setAaiURL("${aaiURL}"); +* params.setAaiUsername("${aaiUsername}"); +* params.setAaiPassword("${aaiPassword}"); +* params.setMsoURL("${msoURL}"); +* params.setMsoUsername("${msoUsername}"); +* params.setMsoPassword("${msoPassword}"); +* params.setAaiNamedQueryUUID("${aaiNamedQueryUUID}"); +* params.setAaiPatternMatch(${aaiPatternMatch}); +* params.setNotificationTopic("${notificationTopic}"); +* params.setAppcTopic("${appcTopic}"); +* // +* // This stays in memory as long as the rule is alive and running +* // +* insert(params); +*end +*/ +/* +* +* This rule responds to DCAE Events +* +*/ +rule "${policyName}.EVENT" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + not ( EventManager( closedLoopControlName == $event.closedLoopControlName )) + then + System.out.println("rule EVENT is triggered."); + try { + // + // Check the requestID in the event to make sure it is not null before we create the EventManager. + // The EventManager will do extra syntax checking as well check if the closed loop is disabled/ + // + if ($event.requestID == null) { + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.REJECTED; + notification.from = "policy"; + notification.message = "Missing requestID from DCAE event"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Can't deliver notification: " + notification); + } + // + // Retract it from memory + // + retract($event); + System.out.println("Event with requestID=null has been retracted."); + } else { + // + // Create an EventManager + // + EventManager manager = new EventManager($params.getClosedLoopControlName(), $event.requestID, $event.target); + // + // Determine if EventManager can actively process the event (i.e. syntax) + // + VirtualControlLoopNotification notification = manager.activate($event); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // Are we actively pursuing this event? + // + if (notification.notification == ControlLoopNotificationType.ACTIVE) { + // + // Insert Event Manager into memory, this will now kick off processing. + // + insert(manager); + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Can't deliver notification: " + notification); + } + } else { + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Can't deliver notification: " + notification); + } + // + // Retract it from memory + // + retract($event); + } + // + // Now that the manager is inserted into Drools working memory, we'll wait for + // another rule to fire in order to continue processing. This way we can also + // then screen for additional ONSET and ABATED events for this same RequestIDs + // and for different RequestIDs but with the same closedLoopControlName and target. + // + } + // + } catch (Exception e) { + e.printStackTrace(); + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.REJECTED; + notification.message = "Exception occurred " + e.getMessage(); + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e1) { + System.out.println("Can't deliver notification: " + notification); + e1.printStackTrace(); + } + // + // Retract the event + // + retract($event); + } +end + +/* +* +* This rule happens when we got a valid ONSET, closed loop is enabled and an Event Manager +* is created. We can start the operations for this closed loop. +* +*/ +rule "${policyName}.EVENT.MANAGER" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : EventManager( closedLoopControlName == $event.closedLoopControlName, controlLoopResult == null) + then + System.out.println("rule EVENT.MANAGER is triggered."); + // + // Check which event this is. + // + EventManager.NEW_EVENT_STATUS eventStatus = $manager.onNewEvent($event); + // + // We only want the initial ONSET event in memory, + // all the other events need to be retracted to support + // cleanup and avoid the other rules being fired for this event. + // + if (eventStatus != EventManager.NEW_EVENT_STATUS.FIRST_ONSET) { + System.out.println("Retracting "+eventStatus+" Event."); + retract($event); + return; + } + // + // Now the event in memory is first onset event + // + try { + // + // Pull the known AAI field from the Event + // + // generic-vnf is needed for vFirewall case + // vserver-name is needed for vLoadBalancer case + // + String genericVNF = $event.AAI.get("generic-vnf.vnf-id"); + String vserver = $event.AAI.get("vserver.vserver-name"); + // + // Check if we are implementing a simple pattern match. + // + if ($params.getAaiPatternMatch() == 1) { + // + // Yes + // + //Basic naming characteristics: + //VF Name (9 char)+VM name (13 char total)+VFC (19 char total) + //Example: + //VF Name (9 characters): cscf0001v + //VM Name(13 characters): cscf0001vm001 + //VFC name(19 characters): cscf0001vm001cfg001 + // + // zdfw1fwl01fwl02 or zdfw1fwl01fwl01 + // replaced with + // zdfw1fwl01pgn02 or zdfw1fwl01pgn01 + // + int index = genericVNF.lastIndexOf("fwl"); + if (index == -1) { + System.err.println("The generic-vnf.vnf-id from DCAE Event is not valid."); + } else { + genericVNF = genericVNF.substring(0, index) + "pgn" + genericVNF.substring(index+"fwl".length()); + } + // + // Construct an APPC request + // + ControlLoopOperation operation = new ControlLoopOperation(); + operation.actor = $params.getActor(); + operation.operation = "ModifyConfig"; + operation.target = $event.target; + // + // Create operationWrapper + // + ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation); + // + // insert operationWrapper into memory + // + insert(operationWrapper); + // + Request request = new Request(); + request.CommonHeader = new CommonHeader(); + request.CommonHeader.RequestID = $event.requestID; + request.Action = operation.operation; + request.Payload = new HashMap<String, Object>(); + // + // Fill in the payload + // + request.Payload.put("generic-vnf.vnf-id", genericVNF); + // + PGRequest pgRequest = new PGRequest(); + pgRequest.pgStreams = new PGStreams(); + + PGStream pgStream; + for(int i = 0; i < 5; i++){ + pgStream = new PGStream(); + pgStream.streamId = "fw_udp"+(i+1); + pgStream.isEnabled = "true"; + pgRequest.pgStreams.pgStream.add(pgStream); + } + request.Payload.put("pg-streams", pgRequest.pgStreams); + + if (request != null) { + // + // Insert request into memory + // + insert(request); + // + // Tell interested parties we are performing this Operation + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.OPERATION; + // message and history ?? + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // Now send the operation request + // + if (request instanceof Request) { + try { + System.out.println("APPC request sent:"); + System.out.println(Serialization.gsonPretty.toJson(request)); + PolicyEngine.manager.deliver($params.getAppcTopic(), request); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Can't deliver request: " + request); + } + } + } else { + // + // what happens if it is null + // + } + // + } else { + // + // create AAI named-query request with UUID started with "F199" + // + AAINQF199Request aainqf199request = new AAINQF199Request(); + AAINQF199QueryParameters aainqf199queryparam = new AAINQF199QueryParameters(); + AAINQF199NamedQuery aainqf199namedquery = new AAINQF199NamedQuery(); + AAINQF199InstanceFilters aainqf199instancefilter = new AAINQF199InstanceFilters(); + // + // queryParameters + // + aainqf199namedquery.namedQueryUUID = UUID.fromString($params.getAaiNamedQueryUUID()); + aainqf199queryparam.namedQuery = aainqf199namedquery; + aainqf199request.queryParameters = aainqf199queryparam; + // + // instanceFilters + // + Map aainqf199instancefiltermap = new HashMap(); + Map aainqf199instancefiltermapitem = new HashMap(); + aainqf199instancefiltermapitem.put("vserver-name", vserver); + aainqf199instancefiltermap.put("vserver", aainqf199instancefiltermapitem); + aainqf199instancefilter.instanceFilter.add(aainqf199instancefiltermap); + aainqf199request.instanceFilters = aainqf199instancefilter; + // + // print aainqf199request for debug + // + System.out.println("AAI Request sent:"); + System.out.println(Serialization.gsonPretty.toJson(aainqf199request)); + // + // Create AAINQF199RequestWrapper + // + AAINQF199RequestWrapper aainqf199RequestWrapper = new AAINQF199RequestWrapper($event.requestID, aainqf199request); + // + // insert aainqf199request into memory + // + insert(aainqf199RequestWrapper); + } + // + } catch (Exception e) { + e.printStackTrace(); + } +end + +/* +* +* This rule happens when we got a valid ONSET, closed loop is enabled, an Event Manager +* is created, AAI Manager and AAI Request are ready in memory. We can start sending query to AAI and then wait for response. +* +*/ +rule "${policyName}.EVENT.MANAGER.AAINQF199REQUEST" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : EventManager( closedLoopControlName == $event.closedLoopControlName ) + $aainqf199RequestWrapper : AAINQF199RequestWrapper(requestID == $event.requestID) + then + System.out.println("rule EVENT.MANAGER.AAINQF199REQUEST is triggered."); + // + // send the request + // + AAINQF199Response aainqf199response = AAINQF199Manager.postQuery($params.getAaiURL(), $params.getAaiUsername(), $params.getAaiPassword(), + $aainqf199RequestWrapper.aainqf199request, $event.requestID); + // + // Check AAI response + // + if (aainqf199response == null) { + System.err.println("Failed to get AAI response"); + // + // Fail and retract everything + // + retract($event); + retract($manager); + retract($aainqf199RequestWrapper); + } else { + // + // Create AAINQF199ResponseWrapper + // + AAINQF199ResponseWrapper aainqf199ResponseWrapper = new AAINQF199ResponseWrapper($event.requestID, aainqf199response); + // + // insert aainqf199ResponseWrapper to memeory + // + insert(aainqf199ResponseWrapper); + } +end + +/* +* +* This rule happens when we got a valid AAI response. We can start sending request to APPC or MSO now. +* +*/ +rule "${policyName}.EVENT.MANAGER.AAINQF199RESPONSE" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : EventManager( closedLoopControlName == $event.closedLoopControlName ) + $aainqf199RequestWrapper : AAINQF199RequestWrapper(requestID == $event.requestID) + $aainqf199ResponseWrapper : AAINQF199ResponseWrapper(requestID == $event.requestID) + then + System.out.println("rule EVENT.MANAGER.AAINQF199RESPONSE is triggered."); + // + // Extract related fields out of AAINQF199RESPONSE + // + String vnfItemVnfId, vnfItemVnfType, vnfItemPersonaModelId, vnfItemPersonaModelVersion, vnfItemModelName, + vnfItemModelVersion, vnfItemModelNameVersionId, serviceItemServiceInstanceId, serviceItemPersonaModelId, + serviceItemModelName, serviceItemModelType, serviceItemModelVersion, serviceItemModelNameVersionId, + vfModuleItemVfModuleName, vfModuleItemPersonaModelId, vfModuleItemPersonaModelVersion, vfModuleItemModelName, + vfModuleItemModelNameVersionId, tenantItemTenantId, cloudRegionItemCloudRegionId; + try { + // + // vnfItem + // + vnfItemVnfId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.vnfID; + vnfItemVnfType = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.vnfType; + vnfItemVnfType = vnfItemVnfType.substring(vnfItemVnfType.lastIndexOf("/")+1); + vnfItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.personaModelId; + vnfItemPersonaModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.personaModelVersion; + vnfItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(0).propertyValue; + vnfItemModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(2).propertyValue; + vnfItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(4).propertyValue; + // + // serviceItem + // + serviceItemServiceInstanceId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.serviceInstanceID; + serviceItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.personaModelId; + serviceItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(0).propertyValue; + serviceItemModelType = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(1).propertyValue; + serviceItemModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.personaModelVersion; + serviceItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(4).propertyValue; + // + // Find the index for base vf module and non-base vf module + // + int baseIndex = -1; + int nonBaseIndex = -1; + List<AAINQF199InventoryResponseItem> inventoryItems = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems; + for (AAINQF199InventoryResponseItem m : inventoryItems) { + if (m.vfModule != null && m.vfModule.isBaseVfModule == true) { + baseIndex = inventoryItems.indexOf(m); + } else if (m.vfModule != null && m.vfModule.isBaseVfModule == false && m.vfModule.orchestrationStatus == null) { + nonBaseIndex = inventoryItems.indexOf(m); + } + // + if (baseIndex != -1 && nonBaseIndex != -1) { + break; + } + } + // + // Report the error if either base vf module or non-base vf module is not found + // + if (baseIndex == -1 || nonBaseIndex == -1) { + System.err.println("Either base or non-base vf module is not found from AAI response."); + retract($aainqf199RequestWrapper); + retract($aainqf199ResponseWrapper); + retract($manager); + retract($event); + return; + } + // + // This comes from the base module + // + vfModuleItemVfModuleName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(baseIndex).vfModule.vfModuleName; + vfModuleItemVfModuleName = vfModuleItemVfModuleName.replace("Vfmodule", "vDNS"); + // + // vfModuleItem - NOT the base module + // + vfModuleItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).vfModule.personaModelId; + vfModuleItemPersonaModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).vfModule.personaModelVersion; + vfModuleItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).extraProperties.extraProperty.get(0).propertyValue; + vfModuleItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).extraProperties.extraProperty.get(4).propertyValue; + // + // tenantItem + // + tenantItemTenantId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(1).tenant.tenantId; + // + // cloudRegionItem + // + cloudRegionItemCloudRegionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(1).items.inventoryResponseItems.get(0).cloudRegion.cloudRegionId; + // + } catch (Exception e) { + e.printStackTrace(); + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.REJECTED; + notification.message = "Exception occurred " + e.getMessage(); + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e1) { + System.out.println("Can't deliver notification: " + notification); + e1.printStackTrace(); + } + // + notification.notification = ControlLoopNotificationType.FINAL_FAILURE; + notification.message = "Invalid named-query response from AAI"; + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e1) { + System.out.println("Can't deliver notification: " + notification); + e1.printStackTrace(); + } + // + // Retract everything + // + retract($aainqf199RequestWrapper); + retract($aainqf199ResponseWrapper); + retract($manager); + retract($event); + return; + } + // + // Extracted fields should not be null + // + if ((vnfItemVnfId == null) || (vnfItemVnfType == null) || + (vnfItemPersonaModelId == null) || (vnfItemModelName == null) || + (vnfItemModelVersion == null) || (vnfItemModelNameVersionId == null) || + (serviceItemServiceInstanceId == null) || (serviceItemModelName == null) || + (serviceItemModelType == null) || (serviceItemModelVersion == null) || + (serviceItemModelNameVersionId == null) || (vfModuleItemVfModuleName == null) || + (vfModuleItemPersonaModelId == null) || (vfModuleItemPersonaModelVersion == null) || + (vfModuleItemModelName == null) || (vfModuleItemModelNameVersionId == null) || + (tenantItemTenantId == null) || (cloudRegionItemCloudRegionId == null)) { + // + System.err.println("some fields are missing from AAI response."); + // + // Fail and retract everything + // + retract($aainqf199RequestWrapper); + retract($aainqf199ResponseWrapper); + retract($manager); + retract($event); + return; + } + // + // We don't need them any more + // + retract($aainqf199ResponseWrapper); + retract($aainqf199RequestWrapper); + // + // check the actor of this closed loop + // + switch ($params.getActor()) { + case "APPC": + { + // + // Construct an APPC request + // + ControlLoopOperation operation = new ControlLoopOperation(); + operation.actor = $params.getActor(); + operation.operation = "ModifyConfig"; + operation.target = $event.target; + // + // Create operationWrapper + // + ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation); + // + // insert operationWrapper into memory + // + insert(operationWrapper); + // + Request request = new Request(); + request.CommonHeader = new CommonHeader(); + request.CommonHeader.RequestID = $event.requestID; + request.Action = operation.operation; + request.Payload = new HashMap<String, Object>(); + // + // Fill in the payload + // Hardcode genericVNF for now since AAI has not been ready for vFirewall demo case + // + String genericVNF = "zdfw1fwl01pgn02"; + request.Payload.put("generic-vnf.vnf-id", genericVNF); + // + PGRequest pgRequest = new PGRequest(); + pgRequest.pgStreams = new PGStreams(); + + PGStream pgStream; + for(int i = 0; i < 5; i++){ + pgStream = new PGStream(); + pgStream.streamId = "fw_udp"+(i+1); + pgStream.isEnabled = "true"; + pgRequest.pgStreams.pgStream.add(pgStream); + } + request.Payload.put("pg-streams", pgRequest.pgStreams); + + if (request != null) { + // + // Insert request into memory + // + insert(request); + // + // Tell interested parties we are performing this Operation + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.OPERATION; + // message and history ?? + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // Now send the operation request + // + if (request instanceof Request) { + try { + System.out.println("APPC request sent:"); + System.out.println(Serialization.gsonPretty.toJson(request)); + PolicyEngine.manager.deliver($params.getAppcTopic(), request); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Can't deliver request: " + request); + } + } + } else { + // + // what happens if it is null + // + } + } + break; + case "MSO": + { + // + // Construct an operation + // + ControlLoopOperation operation = new ControlLoopOperation(); + operation.actor = $params.getActor(); + operation.operation = "createModuleInstance"; + operation.target = $event.target; + // + // Create operationWrapper + // + ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation); + // + // Construct an MSO request + // + MSORequest request = new MSORequest(); + request.requestDetails = new MSORequestDetails(); + request.requestDetails.modelInfo = new MSOModelInfo(); + request.requestDetails.cloudConfiguration = new MSOCloudConfiguration(); + request.requestDetails.requestInfo = new MSORequestInfo(); + request.requestDetails.requestParameters = new MSORequestParameters(); + request.requestDetails.requestParameters.userParams = null; + // + // cloudConfiguration + // + request.requestDetails.cloudConfiguration.lcpCloudRegionId = cloudRegionItemCloudRegionId; + request.requestDetails.cloudConfiguration.tenantId = tenantItemTenantId; + // + // modelInfo + // + request.requestDetails.modelInfo.modelType = "vfModule"; + request.requestDetails.modelInfo.modelInvariantId = vfModuleItemPersonaModelId; + request.requestDetails.modelInfo.modelNameVersionId = vfModuleItemModelNameVersionId; + request.requestDetails.modelInfo.modelName = vfModuleItemModelName; + request.requestDetails.modelInfo.modelVersion = vfModuleItemPersonaModelVersion; + // + // requestInfo + // + request.requestDetails.requestInfo.instanceName = vfModuleItemVfModuleName; + request.requestDetails.requestInfo.source = "POLICY"; + request.requestDetails.requestInfo.suppressRollback = false; + // + // relatedInstanceList + // + MSORelatedInstanceListElement relatedInstanceListElement1 = new MSORelatedInstanceListElement(); + MSORelatedInstanceListElement relatedInstanceListElement2 = new MSORelatedInstanceListElement(); + relatedInstanceListElement1.relatedInstance = new MSORelatedInstance(); + relatedInstanceListElement2.relatedInstance = new MSORelatedInstance(); + // + relatedInstanceListElement1.relatedInstance.instanceId = serviceItemServiceInstanceId; + relatedInstanceListElement1.relatedInstance.modelInfo = new MSOModelInfo(); + relatedInstanceListElement1.relatedInstance.modelInfo.modelType = "service"; + relatedInstanceListElement1.relatedInstance.modelInfo.modelInvariantId = serviceItemPersonaModelId; + relatedInstanceListElement1.relatedInstance.modelInfo.modelNameVersionId = serviceItemModelNameVersionId; + relatedInstanceListElement1.relatedInstance.modelInfo.modelName = serviceItemModelName; + relatedInstanceListElement1.relatedInstance.modelInfo.modelVersion = serviceItemModelVersion; + // + relatedInstanceListElement2.relatedInstance.instanceId = vnfItemVnfId; + relatedInstanceListElement2.relatedInstance.modelInfo = new MSOModelInfo(); + relatedInstanceListElement2.relatedInstance.modelInfo.modelType = "vnf"; + relatedInstanceListElement2.relatedInstance.modelInfo.modelInvariantId = vnfItemPersonaModelId; + relatedInstanceListElement2.relatedInstance.modelInfo.modelNameVersionId = vnfItemModelNameVersionId; + relatedInstanceListElement2.relatedInstance.modelInfo.modelName = vnfItemModelName; + relatedInstanceListElement2.relatedInstance.modelInfo.modelVersion = vnfItemModelVersion; + relatedInstanceListElement2.relatedInstance.modelInfo.modelCustomizationName = vnfItemVnfType; + // + request.requestDetails.relatedInstanceList.add(relatedInstanceListElement1); + request.requestDetails.relatedInstanceList.add(relatedInstanceListElement2); + // + // print MSO request for debug + // + System.out.println("MSO request sent:"); + System.out.println(Serialization.gsonPretty.toJson(request)); + // + // + // + if (request != null) { + // + // Tell interested parties we are performing this Operation + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.OPERATION; + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // Concatenate serviceItemServiceInstanceId and vnfItemVnfId to msoURL + // + String MSOUrl = $params.getMsoURL() + "/serviceInstances/v2/" + serviceItemServiceInstanceId + "/vnfs/" + vnfItemVnfId + "/vfModules"; + // + // Call MSO + // + MSOResponse response = MSOManager.createModuleInstance(MSOUrl, $params.getMsoURL(), $params.getMsoUsername(), $params.getMsoPassword(), request); + // + if (response != null) { + // + // Assign requestId + // + request.requestId = $event.requestID.toString(); + response.request.requestId = $event.requestID.toString(); + // + // Insert facts + // + insert(operationWrapper); + insert(request); + insert(response); + } else { + // + // MSO request not even accepted + // + notification.message = operationWrapper.operation.toMessage(); + operationWrapper.operation.message = operationWrapper.operation.toMessage(); + operationWrapper.operation.outcome = "FAILURE_EXCEPTION"; + $manager.setControlLoopResult("FAILURE_EXCEPTION"); + notification.history.add(operationWrapper.operation); + notification.notification = ControlLoopNotificationType.OPERATION_FAILURE; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + notification.notification = ControlLoopNotificationType.FINAL_FAILURE; + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // Retract everything + // + retract($event); + retract($manager); + } + } else { + System.err.println("constructed MSO request is invalid."); + } + } + break; + } +end + +/* +* +* This rule responds to APPC Response Events +* +*/ +rule "${policyName}.APPC.RESPONSE" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : EventManager( closedLoopControlName == $event.closedLoopControlName ) + $operationWrapper : ControlLoopOperationWrapper( requestID == $event.requestID ) + $request : Request( getCommonHeader().RequestID == $event.requestID ) + $response : Response( getCommonHeader().RequestID == $event.requestID ) + then + System.out.println("rule APPC.RESPONSE is triggered."); + if ($response.Status == null) { + $operationWrapper.operation.outcome = "FAILURE_EXCEPTION"; + $manager.setControlLoopResult("FAILURE_EXCEPTION"); + } + // + // Get the Response Code + // + ResponseCode code = ResponseCode.toResponseCode($response.Status.Code); + if (code == null) { + $operationWrapper.operation.outcome = "FAILURE_EXCEPTION"; + $manager.setControlLoopResult("FAILURE_EXCEPTION"); + } + // + // Construct notification + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + notification.message = $operationWrapper.operation.toMessage(); + $operationWrapper.operation.message = $operationWrapper.operation.toMessage(); + // + // Ok, let's figure out what APP-C's response is + // + switch (code) { + case ACCEPT: + $operationWrapper.operation.outcome = "PROCESSING"; + break; + case ERROR: + case REJECT: + $operationWrapper.operation.outcome = "FAILURE_EXCEPTION"; + $manager.setControlLoopResult("FAILURE_EXCEPTION"); + break; + case SUCCESS: + $operationWrapper.operation.outcome = "SUCCESS"; + $manager.setControlLoopResult("SUCCESS"); + break; + case FAILURE: + $operationWrapper.operation.outcome = "FAILURE"; + $manager.setControlLoopResult("FAILURE"); + break; + } + if ($operationWrapper.operation.outcome.equals("SUCCESS")) { + notification.history.add($operationWrapper.operation); + notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + notification.notification = ControlLoopNotificationType.FINAL_SUCCESS; + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + + // + // We are going to retract these objects from memory + // + System.out.println("Retracting everything"); + retract($operationWrapper); + retract($request); + retract($response); + retract($event); + retract($manager); + } else if ($operationWrapper.operation.outcome.equals("PROCESSING")) { + retract($response); + } else { + notification.history.add($operationWrapper.operation); + notification.notification = ControlLoopNotificationType.OPERATION_FAILURE; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + notification.notification = ControlLoopNotificationType.FINAL_FAILURE; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // We are going to retract these objects from memory + // + System.out.println("Retracting everything"); + retract($operationWrapper); + retract($request); + retract($response); + retract($event); + retract($manager); + } + +end + +/* +* +* This rule is used to clean up APPC response +* +*/ +rule "${policyName}.APPC.RESPONSE.CLEANUP" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $response : Response($id : getCommonHeader().RequestID ) + not ( VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), requestID == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) ) + then + System.out.println("rule APPC.RESPONSE.CLEANUP is triggered."); + retract($response); +end + +/* +* +* This rule responds to MSO Response Events +* +*/ +rule "${policyName}.MSO.RESPONSE" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : EventManager( closedLoopControlName == $event.closedLoopControlName ) + $operationWrapper : ControlLoopOperationWrapper( requestID == $event.requestID ) + $request : MSORequest( requestId == $event.requestID.toString() ) + $response : MSOResponse( request.requestId == $event.requestID.toString() ) + then + System.out.println("rule MSO.RESPONSE is triggered."); + // + // Construct notification + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + notification.message = $operationWrapper.operation.toMessage(); + $operationWrapper.operation.message = $operationWrapper.operation.toMessage(); + // + // The operation can either be succeeded or failed + // + if($response.request.requestStatus.requestState.equals("Completed")) { + $operationWrapper.operation.outcome = "SUCCESS"; + $manager.setControlLoopResult("SUCCESS"); + notification.history.add($operationWrapper.operation); + notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + notification.notification = ControlLoopNotificationType.FINAL_SUCCESS; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // We are going to retract these objects from memory + // + System.out.println("Retracting everything"); + retract($operationWrapper); + retract($request); + retract($response); + retract($event); + retract($manager); + } else { + $operationWrapper.operation.outcome = "FAILURE"; + $manager.setControlLoopResult("FAILURE"); + notification.history.add($operationWrapper.operation); + notification.notification = ControlLoopNotificationType.OPERATION_FAILURE; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + notification.notification = ControlLoopNotificationType.FINAL_FAILURE; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // We are going to retract these objects from memory + // + System.out.println("Retracting everything"); + retract($operationWrapper); + retract($request); + retract($response); + retract($event); + retract($manager); + } + +end |