From 62475a30ef2d425fe04df35ef2dac53c7ab5306a Mon Sep 17 00:00:00 2001 From: Parshad Patel Date: Fri, 16 Nov 2018 20:59:14 +0900 Subject: Rename test classes in apex-pdp Make test classes name consistence by putting 'Test' at end Issue-ID: POLICY-1263 Change-Id: I0179388d84826e698276a1995dd8173a40b5fd2b Signed-off-by: Parshad Patel --- .../policy/apex/examples/aadm/AadmDbWriteTest.java | 64 +++ .../policy/apex/examples/aadm/AadmModelTest.java | 85 ++++ .../policy/apex/examples/aadm/AadmUseCaseTest.java | 459 +++++++++++++++++++++ .../policy/apex/examples/aadm/TestAadmDbWrite.java | 64 --- .../policy/apex/examples/aadm/TestAadmModel.java | 85 ---- .../policy/apex/examples/aadm/TestAadmUseCase.java | 459 --------------------- .../adaptive/AnomalyDetectionDbWriteTest.java | 63 +++ .../adaptive/AnomalyDetectionModelTest.java | 85 ++++ .../adaptive/AnomalyDetectionTslUseCaseTest.java | 233 +++++++++++ .../examples/adaptive/AutoLearnDbWriteTest.java | 64 +++ .../apex/examples/adaptive/AutoLearnModelTest.java | 85 ++++ .../examples/adaptive/AutoLearnTslUseCaseTest.java | 256 ++++++++++++ .../adaptive/TestAnomalyDetectionDbWrite.java | 63 --- .../adaptive/TestAnomalyDetectionModel.java | 85 ---- .../adaptive/TestAnomalyDetectionTslUseCase.java | 233 ----------- .../examples/adaptive/TestAutoLearnDbWrite.java | 64 --- .../apex/examples/adaptive/TestAutoLearnModel.java | 85 ---- .../examples/adaptive/TestAutoLearnTslUseCase.java | 256 ------------ .../apex/examples/myfirstpolicy/MfpLogicTest.java | 183 ++++++++ .../examples/myfirstpolicy/MfpModelCliTest.java | 96 +++++ .../apex/examples/myfirstpolicy/MfpModelTest.java | 106 +++++ .../examples/myfirstpolicy/MfpUseCaseTest.java | 383 +++++++++++++++++ .../apex/examples/myfirstpolicy/TestMfpLogic.java | 183 -------- .../apex/examples/myfirstpolicy/TestMfpModel.java | 106 ----- .../examples/myfirstpolicy/TestMfpModelCli.java | 96 ----- .../examples/myfirstpolicy/TestMfpUseCase.java | 383 ----------------- .../apex/domains/onap/vcpe/AaiAndGuardSim.java | 2 +- .../domains/onap/vcpe/AaiAndGuardSimEndpoint.java | 183 -------- .../onap/vcpe/AaiAndGuardSimEndpointTest.java | 183 ++++++++ 29 files changed, 2346 insertions(+), 2346 deletions(-) create mode 100644 examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/AadmDbWriteTest.java create mode 100644 examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/AadmModelTest.java create mode 100644 examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/AadmUseCaseTest.java delete mode 100644 examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmDbWrite.java delete mode 100644 examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmModel.java delete mode 100644 examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmUseCase.java create mode 100644 examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/AnomalyDetectionDbWriteTest.java create mode 100644 examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/AnomalyDetectionModelTest.java create mode 100644 examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/AnomalyDetectionTslUseCaseTest.java create mode 100644 examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/AutoLearnDbWriteTest.java create mode 100644 examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/AutoLearnModelTest.java create mode 100644 examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/AutoLearnTslUseCaseTest.java delete mode 100644 examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAnomalyDetectionDbWrite.java delete mode 100644 examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAnomalyDetectionModel.java delete mode 100644 examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAnomalyDetectionTslUseCase.java delete mode 100644 examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAutoLearnDbWrite.java delete mode 100644 examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAutoLearnModel.java delete mode 100644 examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAutoLearnTslUseCase.java create mode 100644 examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/MfpLogicTest.java create mode 100644 examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/MfpModelCliTest.java create mode 100644 examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/MfpModelTest.java create mode 100644 examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/MfpUseCaseTest.java delete mode 100644 examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpLogic.java delete mode 100644 examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpModel.java delete mode 100644 examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpModelCli.java delete mode 100644 examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpUseCase.java delete mode 100644 examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AaiAndGuardSimEndpoint.java create mode 100644 examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AaiAndGuardSimEndpointTest.java (limited to 'examples') diff --git a/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/AadmDbWriteTest.java b/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/AadmDbWriteTest.java new file mode 100644 index 000000000..1cc379938 --- /dev/null +++ b/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/AadmDbWriteTest.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.examples.aadm; + +import java.io.File; +import java.sql.Connection; +import java.sql.DriverManager; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.dao.DaoParameters; +import org.onap.policy.apex.model.basicmodel.test.TestApexModel; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; + +public class AadmDbWriteTest { + private Connection connection; + TestApexModel testApexModel; + + /** + * Sets up embedded Derby database and the Apex AADM model for the tests. + * @throws Exception exception to be thrown while setting up the database connection + */ + @Before + public void setup() throws Exception { + Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); + connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); + + testApexModel = new TestApexModel(AxPolicyModel.class, new TestAadmModelCreator()); + } + + @After + public void teardown() throws Exception { + connection.close(); + new File("derby.log").delete(); + } + + @Test + public void testModelWriteReadJpa() throws Exception { + final DaoParameters DaoParameters = new DaoParameters(); + DaoParameters.setPluginClass("org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao"); + DaoParameters.setPersistenceUnit("AADMModelTest"); + + testApexModel.testApexModelWriteReadJpa(DaoParameters); + } +} diff --git a/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/AadmModelTest.java b/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/AadmModelTest.java new file mode 100644 index 000000000..b0aa23949 --- /dev/null +++ b/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/AadmModelTest.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.examples.aadm; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.sql.Connection; +import java.sql.DriverManager; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.dao.DaoParameters; +import org.onap.policy.apex.model.basicmodel.test.TestApexModel; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; + +public class AadmModelTest { + private Connection connection; + TestApexModel testApexModel; + + /** + * Sets up embedded Derby database and the AADM model for the tests. + * @throws Exception exception to be thrown while setting up the database connection + */ + @Before + public void setup() throws Exception { + Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); + connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); + + testApexModel = new TestApexModel(AxPolicyModel.class, new TestAadmModelCreator()); + } + + @After + public void teardown() throws Exception { + connection.close(); + new File("derby.log").delete(); + } + + @Test + public void testModelValid() throws Exception { + final AxValidationResult result = testApexModel.testApexModelValid(); + assertTrue(result.toString().equals(VALID_MODEL_STRING)); + } + + @Test + public void testModelWriteReadXml() throws Exception { + testApexModel.testApexModelWriteReadXml(); + } + + @Test + public void testModelWriteReadJson() throws Exception { + testApexModel.testApexModelWriteReadJson(); + } + + @Test + public void testModelWriteReadJpa() throws Exception { + final DaoParameters DaoParameters = new DaoParameters(); + DaoParameters.setPluginClass("org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao"); + DaoParameters.setPersistenceUnit("AADMModelTest"); + + testApexModel.testApexModelWriteReadJpa(DaoParameters); + } + + private static final String VALID_MODEL_STRING = "***validation of model successful***"; +} diff --git a/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/AadmUseCaseTest.java b/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/AadmUseCaseTest.java new file mode 100644 index 000000000..fbab071b6 --- /dev/null +++ b/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/AadmUseCaseTest.java @@ -0,0 +1,459 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.examples.aadm; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.context.ContextAlbum; +import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; +import org.onap.policy.apex.context.parameters.ContextParameterConstants; +import org.onap.policy.apex.context.parameters.ContextParameters; +import org.onap.policy.apex.context.parameters.SchemaParameters; +import org.onap.policy.apex.core.engine.EngineParameters; +import org.onap.policy.apex.core.engine.engine.impl.ApexEngineFactory; +import org.onap.policy.apex.core.engine.engine.impl.ApexEngineImpl; +import org.onap.policy.apex.core.engine.event.EnEvent; +import org.onap.policy.apex.examples.aadm.concepts.ENodeBStatus; +import org.onap.policy.apex.examples.aadm.model.AadmDomainModelFactory; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.eventmodel.concepts.AxEvent; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; +import org.onap.policy.common.parameters.ParameterService; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +// TODO: Auto-generated Javadoc +/** + * This class tests AADM use case. + * @author Sergey Sachkov (sergey.sachkov@ericsson.com) + * + */ +public class AadmUseCaseTest { + private static final XLogger logger = XLoggerFactory.getXLogger(AadmUseCaseTest.class); + + private SchemaParameters schemaParameters; + private ContextParameters contextParameters; + private EngineParameters engineParameters; + + /** + * Test AADM use case setup. + */ + @Before + public void beforeTest() { + schemaParameters = new SchemaParameters(); + + schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); + schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); + + ParameterService.register(schemaParameters); + + contextParameters = new ContextParameters(); + + contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); + contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); + contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); + contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); + + ParameterService.register(contextParameters); + ParameterService.register(contextParameters.getDistributorParameters()); + ParameterService.register(contextParameters.getLockManagerParameters()); + ParameterService.register(contextParameters.getPersistorParameters()); + + engineParameters = new EngineParameters(); + engineParameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); + ParameterService.register(engineParameters); + } + + /** + * After test. + */ + @After + public void afterTest() { + ParameterService.deregister(engineParameters); + + ParameterService.deregister(contextParameters.getDistributorParameters()); + ParameterService.deregister(contextParameters.getLockManagerParameters()); + ParameterService.deregister(contextParameters.getPersistorParameters()); + ParameterService.deregister(contextParameters); + + ParameterService.deregister(schemaParameters); + } + + /** + * Test aadm case. + * + * @throws ApexException the apex exception + * @throws InterruptedException the interrupted exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testAadmCase() throws ApexException, InterruptedException, IOException { + final AxPolicyModel apexPolicyModel = new AadmDomainModelFactory().getAadmPolicyModel(); + assertNotNull(apexPolicyModel); + final AxArtifactKey key = new AxArtifactKey("AADMApexEngine", "0.0.1"); + + final ApexEngineImpl apexEngine = (ApexEngineImpl) new ApexEngineFactory().createApexEngine(key); + final TestApexActionListener listener = new TestApexActionListener("Test"); + apexEngine.addEventListener("listener", listener); + apexEngine.updateModel(apexPolicyModel); + apexEngine.start(); + + final AxEvent axEvent = getTriggerEvent(apexPolicyModel); + assertNotNull(axEvent); + + // getting number of connections send it to policy, expecting probe action + logger.info("Sending too many connections trigger "); + EnEvent event = apexEngine.createEvent(axEvent.getKey()); + event.put("IMSI", new Long(123456)); + event.put("IMSI_IP", "101.111.121.131"); + event.put("ENODEB_ID", new Long(123)); + event.put("SERVICE_REQUEST_COUNT", 99); + event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 101.0); + event.put("UE_IP_ADDRESS", "101.111.121.131"); + event.put("NUM_SUBSCRIBERS", 101); + event.put("ACTTASK", ""); + event.put("APPLICATION", ""); + event.put("ATTACH_COUNT", 0); + event.put("AVG_SUBSCRIBER_ATTACH", 0D); + event.put("DoS", false); + event.put("NW_IP", ""); + event.put("PROBE_ON", false); + event.put("SGW_IP_ADDRESS", ""); + event.put("TCP_ON", false); + event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 0D); + event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); + event.put("http_host_class", ""); + event.put("protocol_group", ""); + apexEngine.handleEvent(event); + EnEvent result = listener.getResult(); + assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); + assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); + // no DOS_IN_eNodeB set so return probe action + assertTrue(result.get("ACTTASK").equals("probe")); + assertTrue((boolean) result.get("TCP_ON")); + assertTrue((boolean) result.get("PROBE_ON")); + logger.info("Receiving action event with {} action", result.get("ACTTASK")); + + final ContextAlbum eNodeBStatusAlbum = apexEngine.getInternalContext().get("ENodeBStatusAlbum"); + final ENodeBStatus eNodeBStatus = (ENodeBStatus) eNodeBStatusAlbum.get("123"); + eNodeBStatus.setDosCount(101); + eNodeBStatusAlbum.put(eNodeBStatus.getENodeB(), eNodeBStatus); + + logger.info("Sending too many connections trigger "); + event = apexEngine.createEvent(axEvent.getKey()); + event.put("IMSI", new Long(123456)); + event.put("IMSI_IP", "101.111.121.131"); + event.put("ENODEB_ID", new Long(123)); + event.put("SERVICE_REQUEST_COUNT", 101); + event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 99.0); + event.put("UE_IP_ADDRESS", "101.111.121.131"); + event.put("NUM_SUBSCRIBERS", 101); + event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 101.0); + event.put("ACTTASK", ""); + event.put("APPLICATION", ""); + event.put("ATTACH_COUNT", 0); + event.put("AVG_SUBSCRIBER_ATTACH", 0D); + event.put("DoS", false); + event.put("NW_IP", ""); + event.put("PROBE_ON", false); + event.put("SGW_IP_ADDRESS", ""); + event.put("TCP_ON", false); + event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); + event.put("http_host_class", ""); + event.put("protocol_group", ""); + + apexEngine.handleEvent(event); + result = listener.getResult(); + assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); + assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); + // DOS_IN_eNodeB set to be more than throughput so return act action + assertTrue(result.get("ACTTASK").equals("act")); + // only one imsi was sent to process, so stop probe and tcp + assertTrue(!(boolean) result.get("TCP_ON")); + assertTrue(!(boolean) result.get("PROBE_ON")); + assertEquals(100, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDosCount()); + logger.info("Receiving action event with {} action", result.get("ACTTASK")); + + ((ENodeBStatus) eNodeBStatusAlbum.get("123")).setDosCount(99); + + // getting number of connections send it to policy, expecting probe action + logger.info("Sending too many connections trigger "); + event = apexEngine.createEvent(axEvent.getKey()); + event.put("IMSI", new Long(123456)); + event.put("IMSI_IP", "101.111.121.131"); + event.put("ENODEB_ID", new Long(123)); + event.put("SERVICE_REQUEST_COUNT", 99); + event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 101.0); + event.put("UE_IP_ADDRESS", "101.111.121.131"); + event.put("NUM_SUBSCRIBERS", 99); + event.put("ACTTASK", ""); + event.put("APPLICATION", ""); + event.put("ATTACH_COUNT", 0); + event.put("AVG_SUBSCRIBER_ATTACH", 0D); + event.put("DoS", false); + event.put("NW_IP", ""); + event.put("PROBE_ON", false); + event.put("SGW_IP_ADDRESS", ""); + event.put("TCP_ON", false); + event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 0D); + event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); + event.put("http_host_class", ""); + event.put("protocol_group", ""); + + apexEngine.handleEvent(event); + result = listener.getResult(); + assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); + assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); + assertTrue(result.get("ACTTASK").equals("probe")); + assertTrue((boolean) result.get("TCP_ON")); + assertTrue((boolean) result.get("PROBE_ON")); + assertEquals(99, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDosCount()); + + ((ENodeBStatus) eNodeBStatusAlbum.get("123")).setDosCount(99); + + // tcp correlation return positive dos + logger.info("Receiving action event with {} action", result.get("ACTTASK")); + event = apexEngine.createEvent(axEvent.getKey()); + event.put("IMSI", new Long(123456)); + event.put("IMSI_IP", "101.111.121.131"); + event.put("ENODEB_ID", new Long(123)); + event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 101.0); + event.put("ACTTASK", ""); + event.put("APPLICATION", ""); + event.put("ATTACH_COUNT", 0); + event.put("AVG_SUBSCRIBER_ATTACH", 0D); + event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 0.0); + event.put("DoS", false); + event.put("NUM_SUBSCRIBERS", 0); + event.put("NW_IP", ""); + event.put("PROBE_ON", false); + event.put("SERVICE_REQUEST_COUNT", 0); + event.put("SGW_IP_ADDRESS", ""); + event.put("TCP_ON", false); + event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); + event.put("UE_IP_ADDRESS", ""); + event.put("http_host_class", ""); + event.put("protocol_group", ""); + + apexEngine.handleEvent(event); + result = listener.getResult(); + assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); + assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); + assertTrue(result.get("ACTTASK").equals("act")); + assertTrue(!(boolean) result.get("TCP_ON")); + assertTrue(!(boolean) result.get("PROBE_ON")); + assertEquals(98, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDosCount()); + logger.info("Receiving action event with {} action", result.get("ACTTASK")); + + ((ENodeBStatus) eNodeBStatusAlbum.get("123")).setDosCount(101); + + // user moving enodeB + logger.info("Sending too many connections trigger "); + event = apexEngine.createEvent(axEvent.getKey()); + event.put("IMSI", new Long(123456)); + event.put("IMSI_IP", "101.111.121.131"); + event.put("ENODEB_ID", new Long(123)); + event.put("SERVICE_REQUEST_COUNT", 99); + event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 101.0); + event.put("UE_IP_ADDRESS", "101.111.121.131"); + event.put("NUM_SUBSCRIBERS", 101); + event.put("ACTTASK", ""); + event.put("APPLICATION", ""); + event.put("ATTACH_COUNT", 0); + event.put("AVG_SUBSCRIBER_ATTACH", 0D); + event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 0.0); + event.put("DoS", false); + event.put("NW_IP", ""); + event.put("PROBE_ON", false); + event.put("SGW_IP_ADDRESS", ""); + event.put("TCP_ON", false); + event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 0D); + event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); + event.put("http_host_class", ""); + event.put("protocol_group", ""); + + apexEngine.handleEvent(event); + result = listener.getResult(); + assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); + assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); + assertTrue(result.get("ACTTASK").equals("act")); + assertTrue(!(boolean) result.get("TCP_ON")); + assertTrue(!(boolean) result.get("PROBE_ON")); + assertEquals(100, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDosCount()); + logger.info("Receiving action event with {} action", result.get("ACTTASK")); + + logger.info("Sending too many connections trigger "); + event = apexEngine.createEvent(axEvent.getKey()); + event.put("IMSI", new Long(123456)); + event.put("ENODEB_ID", new Long(124)); + event.put("SERVICE_REQUEST_COUNT", 99); + event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 101.0); + event.put("UE_IP_ADDRESS", "101.111.121.131"); + event.put("NUM_SUBSCRIBERS", 101); + event.put("ACTTASK", ""); + event.put("APPLICATION", ""); + event.put("ATTACH_COUNT", 0); + event.put("AVG_SUBSCRIBER_ATTACH", 0D); + event.put("DoS", false); + event.put("IMSI_IP", ""); + event.put("NW_IP", ""); + event.put("PROBE_ON", false); + event.put("SGW_IP_ADDRESS", ""); + event.put("TCP_ON", false); + event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 0D); + event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); + event.put("http_host_class", ""); + event.put("protocol_group", ""); + + apexEngine.handleEvent(event); + result = listener.getResult(); + assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); + assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); + assertTrue(result.get("ACTTASK").equals("probe")); + assertTrue((boolean) result.get("TCP_ON")); + assertTrue((boolean) result.get("PROBE_ON")); + assertEquals(99, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDosCount()); + assertEquals(1, ((ENodeBStatus) eNodeBStatusAlbum.get("124")).getDosCount()); + logger.info("Receiving action event with {} action", result.get("ACTTASK")); + // End of user moving enodeB + + ((ENodeBStatus) eNodeBStatusAlbum.get("123")).setDosCount(101); + + // user becomes non anomalous + logger.info("Sending too many connections trigger "); + event = apexEngine.createEvent(axEvent.getKey()); + event.put("IMSI", new Long(123456)); + event.put("IMSI_IP", "101.111.121.131"); + event.put("ENODEB_ID", new Long(123)); + event.put("SERVICE_REQUEST_COUNT", 99); + event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 101.0); + event.put("UE_IP_ADDRESS", "101.111.121.131"); + event.put("NUM_SUBSCRIBERS", 101); + event.put("ACTTASK", ""); + event.put("APPLICATION", ""); + event.put("ATTACH_COUNT", 0); + event.put("AVG_SUBSCRIBER_ATTACH", 0D); + event.put("DoS", false); + event.put("NW_IP", ""); + event.put("PROBE_ON", false); + event.put("SGW_IP_ADDRESS", ""); + event.put("TCP_ON", false); + event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 0D); + event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); + event.put("http_host_class", ""); + event.put("protocol_group", ""); + + apexEngine.handleEvent(event); + result = listener.getResult(); + assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); + assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); + assertTrue(result.get("ACTTASK").equals("probe")); + assertTrue((boolean) result.get("TCP_ON")); + assertTrue((boolean) result.get("PROBE_ON")); + assertEquals(102, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDosCount()); + logger.info("Receiving action event with {} action", result.get("ACTTASK")); + + logger.info("Sending too many connections trigger "); + event = apexEngine.createEvent(axEvent.getKey()); + event.put("IMSI", new Long(123456)); + event.put("ENODEB_ID", new Long(123)); + event.put("SERVICE_REQUEST_COUNT", 99); + event.put("UE_IP_ADDRESS", "101.111.121.131"); + event.put("ACTTASK", ""); + event.put("APPLICATION", ""); + event.put("ATTACH_COUNT", 0); + event.put("AVG_SUBSCRIBER_ATTACH", 0D); + event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 0.0); + event.put("DoS", false); + event.put("IMSI_IP", ""); + event.put("NUM_SUBSCRIBERS", 0); + event.put("NW_IP", ""); + event.put("PROBE_ON", false); + event.put("SGW_IP_ADDRESS", ""); + event.put("TCP_ON", false); + event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 0D); + event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); + event.put("http_host_class", ""); + event.put("protocol_group", ""); + + apexEngine.handleEvent(event); + result = listener.getResult(); + assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); + assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); + assertTrue(result.get("ACTTASK").equals("probe")); + assertTrue((boolean) result.get("TCP_ON")); + assertTrue((boolean) result.get("PROBE_ON")); + assertEquals(102, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDosCount()); + logger.info("Receiving action event with {} action", result.get("ACTTASK")); + // End of user becomes non anomalous + apexEngine.handleEvent(result); + result = listener.getResult(); + assertTrue(result.getName().startsWith("SAPCBlacklistSubscriberEvent")); + assertTrue(result.get("PROFILE").equals("ServiceA")); + assertTrue(result.get("BLACKLIST_ON").equals(true)); + + event = apexEngine.createEvent(new AxArtifactKey("PeriodicEvent", "0.0.1")); + event.put("PERIODIC_EVENT_COUNT", (long) 100); + event.put("PERIODIC_DELAY", (long) 1000); + event.put("PERIODIC_FIRST_TIME", System.currentTimeMillis()); + event.put("PERIODIC_CURRENT_TIME", System.currentTimeMillis()); + event.put("PERIODIC_LAST_TIME", System.currentTimeMillis()); + apexEngine.handleEvent(event); + result = listener.getResult(); + assertTrue(result.getName().startsWith("SAPCBlacklistSubscriberEvent")); + assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); + assertEquals(0L, result.get("IMSI")); + assertTrue(result.get("PROFILE").equals("ServiceA")); + assertTrue(result.get("BLACKLIST_ON").equals(false)); + + apexEngine.stop(); + } + + /** + * Test vpn cleardown. + */ + @After + public void testAadmCleardown() {} + + /** + * Gets the trigger event. + * + * @param apexPolicyModel the apex policy model + * @return the trigger event + */ + private AxEvent getTriggerEvent(final AxPolicyModel apexPolicyModel) { + for (final AxEvent axEvent : apexPolicyModel.getEvents().getEventMap().values()) { + if (axEvent.getKey().getId().equals("AADMEvent:0.0.1")) { + return axEvent; + } + } + return null; + } +} diff --git a/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmDbWrite.java b/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmDbWrite.java deleted file mode 100644 index bbcbaab03..000000000 --- a/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmDbWrite.java +++ /dev/null @@ -1,64 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.examples.aadm; - -import java.io.File; -import java.sql.Connection; -import java.sql.DriverManager; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.model.basicmodel.dao.DaoParameters; -import org.onap.policy.apex.model.basicmodel.test.TestApexModel; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; - -public class TestAadmDbWrite { - private Connection connection; - TestApexModel testApexModel; - - /** - * Sets up embedded Derby database and the Apex AADM model for the tests. - * @throws Exception exception to be thrown while setting up the database connection - */ - @Before - public void setup() throws Exception { - Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); - connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); - - testApexModel = new TestApexModel(AxPolicyModel.class, new TestAadmModelCreator()); - } - - @After - public void teardown() throws Exception { - connection.close(); - new File("derby.log").delete(); - } - - @Test - public void testModelWriteReadJpa() throws Exception { - final DaoParameters DaoParameters = new DaoParameters(); - DaoParameters.setPluginClass("org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao"); - DaoParameters.setPersistenceUnit("AADMModelTest"); - - testApexModel.testApexModelWriteReadJpa(DaoParameters); - } -} diff --git a/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmModel.java b/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmModel.java deleted file mode 100644 index 1ac1e9829..000000000 --- a/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmModel.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.examples.aadm; - -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.sql.Connection; -import java.sql.DriverManager; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; -import org.onap.policy.apex.model.basicmodel.dao.DaoParameters; -import org.onap.policy.apex.model.basicmodel.test.TestApexModel; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; - -public class TestAadmModel { - private Connection connection; - TestApexModel testApexModel; - - /** - * Sets up embedded Derby database and the AADM model for the tests. - * @throws Exception exception to be thrown while setting up the database connection - */ - @Before - public void setup() throws Exception { - Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); - connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); - - testApexModel = new TestApexModel(AxPolicyModel.class, new TestAadmModelCreator()); - } - - @After - public void teardown() throws Exception { - connection.close(); - new File("derby.log").delete(); - } - - @Test - public void testModelValid() throws Exception { - final AxValidationResult result = testApexModel.testApexModelValid(); - assertTrue(result.toString().equals(VALID_MODEL_STRING)); - } - - @Test - public void testModelWriteReadXml() throws Exception { - testApexModel.testApexModelWriteReadXml(); - } - - @Test - public void testModelWriteReadJson() throws Exception { - testApexModel.testApexModelWriteReadJson(); - } - - @Test - public void testModelWriteReadJpa() throws Exception { - final DaoParameters DaoParameters = new DaoParameters(); - DaoParameters.setPluginClass("org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao"); - DaoParameters.setPersistenceUnit("AADMModelTest"); - - testApexModel.testApexModelWriteReadJpa(DaoParameters); - } - - private static final String VALID_MODEL_STRING = "***validation of model successful***"; -} diff --git a/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmUseCase.java b/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmUseCase.java deleted file mode 100644 index 579bf3484..000000000 --- a/examples/examples-aadm/src/test/java/org/onap/policy/apex/examples/aadm/TestAadmUseCase.java +++ /dev/null @@ -1,459 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.examples.aadm; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.context.ContextAlbum; -import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; -import org.onap.policy.apex.context.parameters.ContextParameterConstants; -import org.onap.policy.apex.context.parameters.ContextParameters; -import org.onap.policy.apex.context.parameters.SchemaParameters; -import org.onap.policy.apex.core.engine.EngineParameters; -import org.onap.policy.apex.core.engine.engine.impl.ApexEngineFactory; -import org.onap.policy.apex.core.engine.engine.impl.ApexEngineImpl; -import org.onap.policy.apex.core.engine.event.EnEvent; -import org.onap.policy.apex.examples.aadm.concepts.ENodeBStatus; -import org.onap.policy.apex.examples.aadm.model.AadmDomainModelFactory; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.policy.apex.model.eventmodel.concepts.AxEvent; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; -import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; -import org.onap.policy.common.parameters.ParameterService; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -// TODO: Auto-generated Javadoc -/** - * This class tests AADM use case. - * @author Sergey Sachkov (sergey.sachkov@ericsson.com) - * - */ -public class TestAadmUseCase { - private static final XLogger logger = XLoggerFactory.getXLogger(TestAadmUseCase.class); - - private SchemaParameters schemaParameters; - private ContextParameters contextParameters; - private EngineParameters engineParameters; - - /** - * Test AADM use case setup. - */ - @Before - public void beforeTest() { - schemaParameters = new SchemaParameters(); - - schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); - schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); - - ParameterService.register(schemaParameters); - - contextParameters = new ContextParameters(); - - contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); - contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); - contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); - contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); - - ParameterService.register(contextParameters); - ParameterService.register(contextParameters.getDistributorParameters()); - ParameterService.register(contextParameters.getLockManagerParameters()); - ParameterService.register(contextParameters.getPersistorParameters()); - - engineParameters = new EngineParameters(); - engineParameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); - ParameterService.register(engineParameters); - } - - /** - * After test. - */ - @After - public void afterTest() { - ParameterService.deregister(engineParameters); - - ParameterService.deregister(contextParameters.getDistributorParameters()); - ParameterService.deregister(contextParameters.getLockManagerParameters()); - ParameterService.deregister(contextParameters.getPersistorParameters()); - ParameterService.deregister(contextParameters); - - ParameterService.deregister(schemaParameters); - } - - /** - * Test aadm case. - * - * @throws ApexException the apex exception - * @throws InterruptedException the interrupted exception - * @throws IOException Signals that an I/O exception has occurred. - */ - @Test - public void testAadmCase() throws ApexException, InterruptedException, IOException { - final AxPolicyModel apexPolicyModel = new AadmDomainModelFactory().getAadmPolicyModel(); - assertNotNull(apexPolicyModel); - final AxArtifactKey key = new AxArtifactKey("AADMApexEngine", "0.0.1"); - - final ApexEngineImpl apexEngine = (ApexEngineImpl) new ApexEngineFactory().createApexEngine(key); - final TestApexActionListener listener = new TestApexActionListener("Test"); - apexEngine.addEventListener("listener", listener); - apexEngine.updateModel(apexPolicyModel); - apexEngine.start(); - - final AxEvent axEvent = getTriggerEvent(apexPolicyModel); - assertNotNull(axEvent); - - // getting number of connections send it to policy, expecting probe action - logger.info("Sending too many connections trigger "); - EnEvent event = apexEngine.createEvent(axEvent.getKey()); - event.put("IMSI", new Long(123456)); - event.put("IMSI_IP", "101.111.121.131"); - event.put("ENODEB_ID", new Long(123)); - event.put("SERVICE_REQUEST_COUNT", 99); - event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 101.0); - event.put("UE_IP_ADDRESS", "101.111.121.131"); - event.put("NUM_SUBSCRIBERS", 101); - event.put("ACTTASK", ""); - event.put("APPLICATION", ""); - event.put("ATTACH_COUNT", 0); - event.put("AVG_SUBSCRIBER_ATTACH", 0D); - event.put("DoS", false); - event.put("NW_IP", ""); - event.put("PROBE_ON", false); - event.put("SGW_IP_ADDRESS", ""); - event.put("TCP_ON", false); - event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 0D); - event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); - event.put("http_host_class", ""); - event.put("protocol_group", ""); - apexEngine.handleEvent(event); - EnEvent result = listener.getResult(); - assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); - assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); - // no DOS_IN_eNodeB set so return probe action - assertTrue(result.get("ACTTASK").equals("probe")); - assertTrue((boolean) result.get("TCP_ON")); - assertTrue((boolean) result.get("PROBE_ON")); - logger.info("Receiving action event with {} action", result.get("ACTTASK")); - - final ContextAlbum eNodeBStatusAlbum = apexEngine.getInternalContext().get("ENodeBStatusAlbum"); - final ENodeBStatus eNodeBStatus = (ENodeBStatus) eNodeBStatusAlbum.get("123"); - eNodeBStatus.setDosCount(101); - eNodeBStatusAlbum.put(eNodeBStatus.getENodeB(), eNodeBStatus); - - logger.info("Sending too many connections trigger "); - event = apexEngine.createEvent(axEvent.getKey()); - event.put("IMSI", new Long(123456)); - event.put("IMSI_IP", "101.111.121.131"); - event.put("ENODEB_ID", new Long(123)); - event.put("SERVICE_REQUEST_COUNT", 101); - event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 99.0); - event.put("UE_IP_ADDRESS", "101.111.121.131"); - event.put("NUM_SUBSCRIBERS", 101); - event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 101.0); - event.put("ACTTASK", ""); - event.put("APPLICATION", ""); - event.put("ATTACH_COUNT", 0); - event.put("AVG_SUBSCRIBER_ATTACH", 0D); - event.put("DoS", false); - event.put("NW_IP", ""); - event.put("PROBE_ON", false); - event.put("SGW_IP_ADDRESS", ""); - event.put("TCP_ON", false); - event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); - event.put("http_host_class", ""); - event.put("protocol_group", ""); - - apexEngine.handleEvent(event); - result = listener.getResult(); - assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); - assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); - // DOS_IN_eNodeB set to be more than throughput so return act action - assertTrue(result.get("ACTTASK").equals("act")); - // only one imsi was sent to process, so stop probe and tcp - assertTrue(!(boolean) result.get("TCP_ON")); - assertTrue(!(boolean) result.get("PROBE_ON")); - assertEquals(100, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDosCount()); - logger.info("Receiving action event with {} action", result.get("ACTTASK")); - - ((ENodeBStatus) eNodeBStatusAlbum.get("123")).setDosCount(99); - - // getting number of connections send it to policy, expecting probe action - logger.info("Sending too many connections trigger "); - event = apexEngine.createEvent(axEvent.getKey()); - event.put("IMSI", new Long(123456)); - event.put("IMSI_IP", "101.111.121.131"); - event.put("ENODEB_ID", new Long(123)); - event.put("SERVICE_REQUEST_COUNT", 99); - event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 101.0); - event.put("UE_IP_ADDRESS", "101.111.121.131"); - event.put("NUM_SUBSCRIBERS", 99); - event.put("ACTTASK", ""); - event.put("APPLICATION", ""); - event.put("ATTACH_COUNT", 0); - event.put("AVG_SUBSCRIBER_ATTACH", 0D); - event.put("DoS", false); - event.put("NW_IP", ""); - event.put("PROBE_ON", false); - event.put("SGW_IP_ADDRESS", ""); - event.put("TCP_ON", false); - event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 0D); - event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); - event.put("http_host_class", ""); - event.put("protocol_group", ""); - - apexEngine.handleEvent(event); - result = listener.getResult(); - assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); - assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); - assertTrue(result.get("ACTTASK").equals("probe")); - assertTrue((boolean) result.get("TCP_ON")); - assertTrue((boolean) result.get("PROBE_ON")); - assertEquals(99, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDosCount()); - - ((ENodeBStatus) eNodeBStatusAlbum.get("123")).setDosCount(99); - - // tcp correlation return positive dos - logger.info("Receiving action event with {} action", result.get("ACTTASK")); - event = apexEngine.createEvent(axEvent.getKey()); - event.put("IMSI", new Long(123456)); - event.put("IMSI_IP", "101.111.121.131"); - event.put("ENODEB_ID", new Long(123)); - event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 101.0); - event.put("ACTTASK", ""); - event.put("APPLICATION", ""); - event.put("ATTACH_COUNT", 0); - event.put("AVG_SUBSCRIBER_ATTACH", 0D); - event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 0.0); - event.put("DoS", false); - event.put("NUM_SUBSCRIBERS", 0); - event.put("NW_IP", ""); - event.put("PROBE_ON", false); - event.put("SERVICE_REQUEST_COUNT", 0); - event.put("SGW_IP_ADDRESS", ""); - event.put("TCP_ON", false); - event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); - event.put("UE_IP_ADDRESS", ""); - event.put("http_host_class", ""); - event.put("protocol_group", ""); - - apexEngine.handleEvent(event); - result = listener.getResult(); - assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); - assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); - assertTrue(result.get("ACTTASK").equals("act")); - assertTrue(!(boolean) result.get("TCP_ON")); - assertTrue(!(boolean) result.get("PROBE_ON")); - assertEquals(98, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDosCount()); - logger.info("Receiving action event with {} action", result.get("ACTTASK")); - - ((ENodeBStatus) eNodeBStatusAlbum.get("123")).setDosCount(101); - - // user moving enodeB - logger.info("Sending too many connections trigger "); - event = apexEngine.createEvent(axEvent.getKey()); - event.put("IMSI", new Long(123456)); - event.put("IMSI_IP", "101.111.121.131"); - event.put("ENODEB_ID", new Long(123)); - event.put("SERVICE_REQUEST_COUNT", 99); - event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 101.0); - event.put("UE_IP_ADDRESS", "101.111.121.131"); - event.put("NUM_SUBSCRIBERS", 101); - event.put("ACTTASK", ""); - event.put("APPLICATION", ""); - event.put("ATTACH_COUNT", 0); - event.put("AVG_SUBSCRIBER_ATTACH", 0D); - event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 0.0); - event.put("DoS", false); - event.put("NW_IP", ""); - event.put("PROBE_ON", false); - event.put("SGW_IP_ADDRESS", ""); - event.put("TCP_ON", false); - event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 0D); - event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); - event.put("http_host_class", ""); - event.put("protocol_group", ""); - - apexEngine.handleEvent(event); - result = listener.getResult(); - assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); - assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); - assertTrue(result.get("ACTTASK").equals("act")); - assertTrue(!(boolean) result.get("TCP_ON")); - assertTrue(!(boolean) result.get("PROBE_ON")); - assertEquals(100, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDosCount()); - logger.info("Receiving action event with {} action", result.get("ACTTASK")); - - logger.info("Sending too many connections trigger "); - event = apexEngine.createEvent(axEvent.getKey()); - event.put("IMSI", new Long(123456)); - event.put("ENODEB_ID", new Long(124)); - event.put("SERVICE_REQUEST_COUNT", 99); - event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 101.0); - event.put("UE_IP_ADDRESS", "101.111.121.131"); - event.put("NUM_SUBSCRIBERS", 101); - event.put("ACTTASK", ""); - event.put("APPLICATION", ""); - event.put("ATTACH_COUNT", 0); - event.put("AVG_SUBSCRIBER_ATTACH", 0D); - event.put("DoS", false); - event.put("IMSI_IP", ""); - event.put("NW_IP", ""); - event.put("PROBE_ON", false); - event.put("SGW_IP_ADDRESS", ""); - event.put("TCP_ON", false); - event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 0D); - event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); - event.put("http_host_class", ""); - event.put("protocol_group", ""); - - apexEngine.handleEvent(event); - result = listener.getResult(); - assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); - assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); - assertTrue(result.get("ACTTASK").equals("probe")); - assertTrue((boolean) result.get("TCP_ON")); - assertTrue((boolean) result.get("PROBE_ON")); - assertEquals(99, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDosCount()); - assertEquals(1, ((ENodeBStatus) eNodeBStatusAlbum.get("124")).getDosCount()); - logger.info("Receiving action event with {} action", result.get("ACTTASK")); - // End of user moving enodeB - - ((ENodeBStatus) eNodeBStatusAlbum.get("123")).setDosCount(101); - - // user becomes non anomalous - logger.info("Sending too many connections trigger "); - event = apexEngine.createEvent(axEvent.getKey()); - event.put("IMSI", new Long(123456)); - event.put("IMSI_IP", "101.111.121.131"); - event.put("ENODEB_ID", new Long(123)); - event.put("SERVICE_REQUEST_COUNT", 99); - event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 101.0); - event.put("UE_IP_ADDRESS", "101.111.121.131"); - event.put("NUM_SUBSCRIBERS", 101); - event.put("ACTTASK", ""); - event.put("APPLICATION", ""); - event.put("ATTACH_COUNT", 0); - event.put("AVG_SUBSCRIBER_ATTACH", 0D); - event.put("DoS", false); - event.put("NW_IP", ""); - event.put("PROBE_ON", false); - event.put("SGW_IP_ADDRESS", ""); - event.put("TCP_ON", false); - event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 0D); - event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); - event.put("http_host_class", ""); - event.put("protocol_group", ""); - - apexEngine.handleEvent(event); - result = listener.getResult(); - assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); - assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); - assertTrue(result.get("ACTTASK").equals("probe")); - assertTrue((boolean) result.get("TCP_ON")); - assertTrue((boolean) result.get("PROBE_ON")); - assertEquals(102, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDosCount()); - logger.info("Receiving action event with {} action", result.get("ACTTASK")); - - logger.info("Sending too many connections trigger "); - event = apexEngine.createEvent(axEvent.getKey()); - event.put("IMSI", new Long(123456)); - event.put("ENODEB_ID", new Long(123)); - event.put("SERVICE_REQUEST_COUNT", 99); - event.put("UE_IP_ADDRESS", "101.111.121.131"); - event.put("ACTTASK", ""); - event.put("APPLICATION", ""); - event.put("ATTACH_COUNT", 0); - event.put("AVG_SUBSCRIBER_ATTACH", 0D); - event.put("AVG_SUBSCRIBER_SERVICE_REQUEST", 0.0); - event.put("DoS", false); - event.put("IMSI_IP", ""); - event.put("NUM_SUBSCRIBERS", 0); - event.put("NW_IP", ""); - event.put("PROBE_ON", false); - event.put("SGW_IP_ADDRESS", ""); - event.put("TCP_ON", false); - event.put("TCP_UE_SIDE_AVG_THROUGHPUT", 0D); - event.put("TCP_UE_SIDE_MEDIAN_RTT_TX_TO_RX", 0L); - event.put("http_host_class", ""); - event.put("protocol_group", ""); - - apexEngine.handleEvent(event); - result = listener.getResult(); - assertTrue(result.getName().startsWith("XSTREAM_AADM_ACT_EVENT")); - assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); - assertTrue(result.get("ACTTASK").equals("probe")); - assertTrue((boolean) result.get("TCP_ON")); - assertTrue((boolean) result.get("PROBE_ON")); - assertEquals(102, ((ENodeBStatus) eNodeBStatusAlbum.get("123")).getDosCount()); - logger.info("Receiving action event with {} action", result.get("ACTTASK")); - // End of user becomes non anomalous - apexEngine.handleEvent(result); - result = listener.getResult(); - assertTrue(result.getName().startsWith("SAPCBlacklistSubscriberEvent")); - assertTrue(result.get("PROFILE").equals("ServiceA")); - assertTrue(result.get("BLACKLIST_ON").equals(true)); - - event = apexEngine.createEvent(new AxArtifactKey("PeriodicEvent", "0.0.1")); - event.put("PERIODIC_EVENT_COUNT", (long) 100); - event.put("PERIODIC_DELAY", (long) 1000); - event.put("PERIODIC_FIRST_TIME", System.currentTimeMillis()); - event.put("PERIODIC_CURRENT_TIME", System.currentTimeMillis()); - event.put("PERIODIC_LAST_TIME", System.currentTimeMillis()); - apexEngine.handleEvent(event); - result = listener.getResult(); - assertTrue(result.getName().startsWith("SAPCBlacklistSubscriberEvent")); - assertEquals("ExecutionIDs are different", event.getExecutionId(), result.getExecutionId()); - assertEquals(0L, result.get("IMSI")); - assertTrue(result.get("PROFILE").equals("ServiceA")); - assertTrue(result.get("BLACKLIST_ON").equals(false)); - - apexEngine.stop(); - } - - /** - * Test vpn cleardown. - */ - @After - public void testAadmCleardown() {} - - /** - * Gets the trigger event. - * - * @param apexPolicyModel the apex policy model - * @return the trigger event - */ - private AxEvent getTriggerEvent(final AxPolicyModel apexPolicyModel) { - for (final AxEvent axEvent : apexPolicyModel.getEvents().getEventMap().values()) { - if (axEvent.getKey().getId().equals("AADMEvent:0.0.1")) { - return axEvent; - } - } - return null; - } -} diff --git a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/AnomalyDetectionDbWriteTest.java b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/AnomalyDetectionDbWriteTest.java new file mode 100644 index 000000000..885704497 --- /dev/null +++ b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/AnomalyDetectionDbWriteTest.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.examples.adaptive; + +import java.io.File; +import java.sql.Connection; +import java.sql.DriverManager; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.dao.DaoParameters; +import org.onap.policy.apex.model.basicmodel.test.TestApexModel; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; + +public class AnomalyDetectionDbWriteTest { + private Connection connection; + TestApexModel testApexModel; + + /** + * Sets up embedded Derby database and the Apex anomaly detection model for the tests. + * @throws Exception exception to be thrown while setting up the database connection + */ + @Before + public void setup() throws Exception { + Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); + connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); + + testApexModel = new TestApexModel<>(AxPolicyModel.class, new TestAnomalyDetectionModelCreator()); + } + + @After + public void teardown() throws Exception { + connection.close(); + new File("derby.log").delete(); + } + + @Test + public void testModelWriteReadJpa() throws Exception { + final DaoParameters DaoParameters = new DaoParameters(); + DaoParameters.setPluginClass("org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao"); + DaoParameters.setPersistenceUnit("AdaptiveModelsTest"); + testApexModel.testApexModelWriteReadJpa(DaoParameters); + } +} diff --git a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/AnomalyDetectionModelTest.java b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/AnomalyDetectionModelTest.java new file mode 100644 index 000000000..552ca2f37 --- /dev/null +++ b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/AnomalyDetectionModelTest.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.examples.adaptive; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.sql.Connection; +import java.sql.DriverManager; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.dao.DaoParameters; +import org.onap.policy.apex.model.basicmodel.test.TestApexModel; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; + +public class AnomalyDetectionModelTest { + private Connection connection; + TestApexModel testApexModel; + + /** + * Sets up embedded Derby database and the Apex anomaly detection model for the tests. + * @throws Exception exception to be thrown while setting up the database connection + */ + @Before + public void setup() throws Exception { + Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); + connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); + + testApexModel = new TestApexModel<>(AxPolicyModel.class, new TestAnomalyDetectionModelCreator()); + } + + @After + public void teardown() throws Exception { + connection.close(); + new File("derby.log").delete(); + } + + @Test + public void testModelValid() throws Exception { + final AxValidationResult result = testApexModel.testApexModelValid(); + assertTrue(result.toString().equals(VALID_MODEL_STRING)); + } + + @Test + public void testModelWriteReadXml() throws Exception { + testApexModel.testApexModelWriteReadXml(); + } + + @Test + public void testModelWriteReadJson() throws Exception { + testApexModel.testApexModelWriteReadJson(); + } + + @Test + public void testModelWriteReadJpa() throws Exception { + final DaoParameters DaoParameters = new DaoParameters(); + DaoParameters.setPluginClass("org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao"); + DaoParameters.setPersistenceUnit("AdaptiveModelsTest"); + + testApexModel.testApexModelWriteReadJpa(DaoParameters); + } + + private static final String VALID_MODEL_STRING = "***validation of model successful***"; +} diff --git a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/AnomalyDetectionTslUseCaseTest.java b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/AnomalyDetectionTslUseCaseTest.java new file mode 100644 index 000000000..40df82cdb --- /dev/null +++ b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/AnomalyDetectionTslUseCaseTest.java @@ -0,0 +1,233 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.examples.adaptive; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.Random; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; +import org.onap.policy.apex.context.parameters.ContextParameterConstants; +import org.onap.policy.apex.context.parameters.ContextParameters; +import org.onap.policy.apex.context.parameters.SchemaParameters; +import org.onap.policy.apex.core.engine.EngineParameters; +import org.onap.policy.apex.core.engine.engine.ApexEngine; +import org.onap.policy.apex.core.engine.engine.impl.ApexEngineFactory; +import org.onap.policy.apex.core.engine.event.EnEvent; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.examples.adaptive.model.AdaptiveDomainModelFactory; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.onap.policy.apex.plugins.executor.java.JavaExecutorParameters; +import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; +import org.onap.policy.common.parameters.ParameterService; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +/** + * This policy passes, and recieves a Double event context filed called "EVCDouble".
+ * The policy tries to detect anomalies in the pattern of values for EVCDouble
+ * See the 2 test cases below (1 short, 1 long) + * + * @author John Keeney (John.Keeney@ericsson.com) + */ +public class AnomalyDetectionTslUseCaseTest { + private static final XLogger LOGGER = XLoggerFactory.getXLogger(AnomalyDetectionTslUseCaseTest.class); + + private static final int MAXITERATIONS = 3660; + private static final Random RAND = new Random(System.currentTimeMillis()); + + private SchemaParameters schemaParameters; + private ContextParameters contextParameters; + private EngineParameters engineParameters; + + /** + * Before test. + */ + @Before + public void beforeTest() { + schemaParameters = new SchemaParameters(); + + schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); + schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); + + ParameterService.register(schemaParameters); + + contextParameters = new ContextParameters(); + + contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); + contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); + contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); + contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); + + ParameterService.register(contextParameters); + ParameterService.register(contextParameters.getDistributorParameters()); + ParameterService.register(contextParameters.getLockManagerParameters()); + ParameterService.register(contextParameters.getPersistorParameters()); + + engineParameters = new EngineParameters(); + engineParameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); + engineParameters.getExecutorParameterMap().put("JAVA", new JavaExecutorParameters()); + ParameterService.register(engineParameters); + } + + /** + * After test. + */ + @After + public void afterTest() { + ParameterService.deregister(engineParameters); + + ParameterService.deregister(contextParameters.getDistributorParameters()); + ParameterService.deregister(contextParameters.getLockManagerParameters()); + ParameterService.deregister(contextParameters.getPersistorParameters()); + ParameterService.deregister(contextParameters); + + ParameterService.deregister(schemaParameters); + } + + /** + * Test anomaly detection tsl. + * + * @throws ApexException the apex exception + * @throws InterruptedException the interrupted exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + // once through the long running test below + public void testAnomalyDetectionTsl() throws ApexException, InterruptedException, IOException { + final AxPolicyModel apexPolicyModel = new AdaptiveDomainModelFactory().getAnomalyDetectionPolicyModel(); + assertNotNull(apexPolicyModel); + + final AxValidationResult validationResult = new AxValidationResult(); + apexPolicyModel.validate(validationResult); + assertTrue(validationResult.isValid()); + + final AxArtifactKey key = new AxArtifactKey("AnomalyTSLApexEngine", "0.0.1"); + + final ApexEngine apexEngine1 = new ApexEngineFactory().createApexEngine(key); + + final TestApexActionListener listener1 = new TestApexActionListener("TestListener1"); + apexEngine1.addEventListener("listener", listener1); + apexEngine1.updateModel(apexPolicyModel); + apexEngine1.start(); + final EnEvent triggerEvent = + apexEngine1.createEvent(new AxArtifactKey("AnomalyDetectionTriggerEvent", "0.0.1")); + final double rval = RAND.nextGaussian(); + triggerEvent.put("Iteration", 0); + triggerEvent.put("MonitoredValue", rval); + LOGGER.info("Triggering policy in Engine 1 with " + triggerEvent); + apexEngine1.handleEvent(triggerEvent); + final EnEvent result = listener1.getResult(); + LOGGER.info("Receiving action event {} ", result); + assertEquals("ExecutionIDs are different", triggerEvent.getExecutionId(), result.getExecutionId()); + triggerEvent.clear(); + result.clear(); + ThreadUtilities.sleep(1); + apexEngine1.stop(); + } + + /** + * This policy passes, and recieves a Double event context filed called "EVCDouble"
+ * The policy tries to detect anomalies in the pattern of values for EVCDouble
+ * This test case generates a SineWave-like pattern for the parameter, repeating every 360 iterations. (These Period + * should probably be set using TaskParameters!) Every 361st value is a random number!, so should be identified as + * an Anomaly. The policy has 3 Decide Tasks, and the Decide TaskSelectionLogic picks one depending on the + * 'Anomaliness' of the input data.
+ * To plot the results grep debug results for the string "************", paste into excel and delete non-relevant + * columns
+ * + * @throws ApexException the apex exception + * @throws InterruptedException the interrupted exception + * @throws IOException Signals that an I/O exception has occurred. + */ + // Test is disabled by default. uncomment below, or execute using the main() method + // @Test + // EG Dos command: apex-core.engine> mvn + // -Dtest=org.onap.policy.apex.core.engine.ml.TestAnomalyDetectionTslUseCase test | findstr /L /C:"Apex [main] DEBUG + // c.e.a.e.TaskSelectionExecutionLogging - + // TestAnomalyDetectionTSL_Policy0000DecideStateTaskSelectionLogic.getTask():" + public void testAnomalyDetectionTslmain() throws ApexException, InterruptedException, IOException { + + final AxPolicyModel apexPolicyModel = new AdaptiveDomainModelFactory().getAnomalyDetectionPolicyModel(); + assertNotNull(apexPolicyModel); + + final AxValidationResult validationResult = new AxValidationResult(); + apexPolicyModel.validate(validationResult); + assertTrue(validationResult.isValid()); + + final AxArtifactKey key = new AxArtifactKey("AnomalyTSLApexEngine", "0.0.1"); + final EngineParameters parameters = new EngineParameters(); + parameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); + parameters.getExecutorParameterMap().put("JAVA", new JavaExecutorParameters()); + + final ApexEngine apexEngine1 = new ApexEngineFactory().createApexEngine(key); + + final TestApexActionListener listener1 = new TestApexActionListener("TestListener1"); + apexEngine1.addEventListener("listener1", listener1); + apexEngine1.updateModel(apexPolicyModel); + apexEngine1.start(); + + final EnEvent triggerEvent = + apexEngine1.createEvent(new AxArtifactKey("AnomalyDetectionTriggerEvent", "0.0.1")); + assertNotNull(triggerEvent); + + for (int iteration = 0; iteration < MAXITERATIONS; iteration++) { + // Trigger the policy in engine 1 + + double value = (Math.sin(Math.toRadians(iteration))) + (RAND.nextGaussian() / 25.0); + // lets make every 361st number a random value to perhaps flag as an anomaly + if (((iteration + 45) % 361) == 0) { + value = (RAND.nextGaussian() * 2.0); + } + triggerEvent.put("Iteration", iteration); + triggerEvent.put("MonitoredValue", value); + LOGGER.info("Iteration " + iteration + ":\tTriggering policy in Engine 1 with " + triggerEvent); + apexEngine1.handleEvent(triggerEvent); + final EnEvent result = listener1.getResult(); + LOGGER.info("Iteration " + iteration + ":\tReceiving action event {} ", result); + triggerEvent.clear(); + result.clear(); + } + apexEngine1.stop(); + ThreadUtilities.sleep(1000); + } + + /** + * The main method. + * + * @param args the arguments + * @throws ApexException the apex exception + * @throws InterruptedException the interrupted exception + * @throws IOException Signals that an I/O exception has occurred. + */ + public static void main(final String[] args) throws ApexException, InterruptedException, IOException { + new AnomalyDetectionTslUseCaseTest().testAnomalyDetectionTslmain(); + } +} diff --git a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/AutoLearnDbWriteTest.java b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/AutoLearnDbWriteTest.java new file mode 100644 index 000000000..828a56133 --- /dev/null +++ b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/AutoLearnDbWriteTest.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.examples.adaptive; + +import java.io.File; +import java.sql.Connection; +import java.sql.DriverManager; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.dao.DaoParameters; +import org.onap.policy.apex.model.basicmodel.test.TestApexModel; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; + +public class AutoLearnDbWriteTest { + private Connection connection; + TestApexModel testApexModel; + + /** + * Sets up embedded Derby database and the Apex AutoLearn model for the tests. + * @throws Exception exception to be thrown while setting up the database connection + */ + @Before + public void setup() throws Exception { + Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); + connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); + + testApexModel = new TestApexModel<>(AxPolicyModel.class, new TestAutoLearnModelCreator()); + } + + @After + public void teardown() throws Exception { + connection.close(); + new File("derby.log").delete(); + } + + @Test + public void testModelWriteReadJpa() throws Exception { + final DaoParameters DaoParameters = new DaoParameters(); + DaoParameters.setPluginClass("org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao"); + DaoParameters.setPersistenceUnit("AdaptiveModelsTest"); + + testApexModel.testApexModelWriteReadJpa(DaoParameters); + } +} diff --git a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/AutoLearnModelTest.java b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/AutoLearnModelTest.java new file mode 100644 index 000000000..f4cddc580 --- /dev/null +++ b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/AutoLearnModelTest.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.examples.adaptive; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.sql.Connection; +import java.sql.DriverManager; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.dao.DaoParameters; +import org.onap.policy.apex.model.basicmodel.test.TestApexModel; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; + +public class AutoLearnModelTest { + private Connection connection; + TestApexModel testApexModel; + + /** + * Sets up embedded Derby database and the Apex AutoLearn model for the tests. + * @throws Exception exception to be thrown while setting up the database connection + */ + @Before + public void setup() throws Exception { + Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); + connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); + + testApexModel = new TestApexModel<>(AxPolicyModel.class, new TestAutoLearnModelCreator()); + } + + @After + public void teardown() throws Exception { + connection.close(); + new File("derby.log").delete(); + } + + @Test + public void testModelValid() throws Exception { + final AxValidationResult result = testApexModel.testApexModelValid(); + assertTrue(result.toString().equals(VALID_MODEL_STRING)); + } + + @Test + public void testModelWriteReadXml() throws Exception { + testApexModel.testApexModelWriteReadXml(); + } + + @Test + public void testModelWriteReadJson() throws Exception { + testApexModel.testApexModelWriteReadJson(); + } + + @Test + public void testModelWriteReadJpa() throws Exception { + final DaoParameters DaoParameters = new DaoParameters(); + DaoParameters.setPluginClass("org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao"); + DaoParameters.setPersistenceUnit("AdaptiveModelsTest"); + + testApexModel.testApexModelWriteReadJpa(DaoParameters); + } + + private static final String VALID_MODEL_STRING = "***validation of model successful***"; +} diff --git a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/AutoLearnTslUseCaseTest.java b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/AutoLearnTslUseCaseTest.java new file mode 100644 index 000000000..bf6c08f16 --- /dev/null +++ b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/AutoLearnTslUseCaseTest.java @@ -0,0 +1,256 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.examples.adaptive; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.Random; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; +import org.onap.policy.apex.context.parameters.ContextParameterConstants; +import org.onap.policy.apex.context.parameters.ContextParameters; +import org.onap.policy.apex.context.parameters.SchemaParameters; +import org.onap.policy.apex.core.engine.EngineParameters; +import org.onap.policy.apex.core.engine.engine.ApexEngine; +import org.onap.policy.apex.core.engine.engine.impl.ApexEngineFactory; +import org.onap.policy.apex.core.engine.event.EnEvent; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; +import org.onap.policy.apex.examples.adaptive.model.AdaptiveDomainModelFactory; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.onap.policy.apex.plugins.executor.java.JavaExecutorParameters; +import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; +import org.onap.policy.common.parameters.ParameterService; +import org.slf4j.ext.XLogger; +import org.slf4j.ext.XLoggerFactory; + +// TODO: Auto-generated Javadoc +/** + * Test Auto learning in TSL. + * + * @author John Keeney (John.Keeney@ericsson.com) + */ +public class AutoLearnTslUseCaseTest { + private static final XLogger LOGGER = XLoggerFactory.getXLogger(AutoLearnTslUseCaseTest.class); + + private static final int MAXITERATIONS = 1000; + private static final Random rand = new Random(System.currentTimeMillis()); + + private SchemaParameters schemaParameters; + private ContextParameters contextParameters; + private EngineParameters engineParameters; + + /** + * Before test. + */ + @Before + public void beforeTest() { + schemaParameters = new SchemaParameters(); + + schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); + schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); + + ParameterService.register(schemaParameters); + + contextParameters = new ContextParameters(); + + contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); + contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); + contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); + contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); + + ParameterService.register(contextParameters); + ParameterService.register(contextParameters.getDistributorParameters()); + ParameterService.register(contextParameters.getLockManagerParameters()); + ParameterService.register(contextParameters.getPersistorParameters()); + + engineParameters = new EngineParameters(); + engineParameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); + engineParameters.getExecutorParameterMap().put("JAVA", new JavaExecutorParameters()); + ParameterService.register(engineParameters); + } + + /** + * After test. + */ + @After + public void afterTest() { + ParameterService.deregister(engineParameters); + + ParameterService.deregister(contextParameters.getDistributorParameters()); + ParameterService.deregister(contextParameters.getLockManagerParameters()); + ParameterService.deregister(contextParameters.getPersistorParameters()); + ParameterService.deregister(contextParameters); + + ParameterService.deregister(schemaParameters); + } + + /** + * Test auto learn tsl. + * + * @throws ApexException the apex exception + * @throws InterruptedException the interrupted exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + // once through the long running test below + public void testAutoLearnTsl() throws ApexException, InterruptedException, IOException { + final AxPolicyModel apexPolicyModel = new AdaptiveDomainModelFactory().getAutoLearnPolicyModel(); + assertNotNull(apexPolicyModel); + + final AxValidationResult validationResult = new AxValidationResult(); + apexPolicyModel.validate(validationResult); + assertTrue(validationResult.isValid()); + + final AxArtifactKey key = new AxArtifactKey("AADMApexEngine", "0.0.1"); + + final ApexEngine apexEngine1 = new ApexEngineFactory().createApexEngine(key); + + final TestApexActionListener listener1 = new TestApexActionListener("TestListener1"); + apexEngine1.addEventListener("listener", listener1); + apexEngine1.updateModel(apexPolicyModel); + apexEngine1.start(); + final EnEvent triggerEvent = apexEngine1.createEvent(new AxArtifactKey("AutoLearnTriggerEvent", "0.0.1")); + final double rval = rand.nextGaussian(); + triggerEvent.put("MonitoredValue", rval); + triggerEvent.put("LastMonitoredValue", 0D); + LOGGER.info("Triggering policy in Engine 1 with " + triggerEvent); + apexEngine1.handleEvent(triggerEvent); + final EnEvent result = listener1.getResult(); + LOGGER.info("Receiving action event {} ", result); + assertEquals("ExecutionIDs are different", triggerEvent.getExecutionId(), result.getExecutionId()); + triggerEvent.clear(); + result.clear(); + ThreadUtilities.sleep(10); + apexEngine1.stop(); + } + + /** + * This policy passes, and receives a Double event context filed called "EVCDouble"
+ * The policy tries to keep the value at 50, with a Min -100, Max 100 (These should probably be set using + * TaskParameters!)
+ * The policy has 7 Decide Tasks that manipulate the value of this field in unknown ways.
+ * The Decide TSL learns the effect of each task, and then selects the appropriate task to get the value back to + * 50
+ * After the value settles close to 50 for a while, the test Rests the value to to random number and then + * continues
+ * To plot the results grep stdout debug results for the string "*******", paste into excel and delete non-relevant + * columns
+ * + * @throws ApexException the apex exception + * @throws InterruptedException the interrupted exception + * @throws IOException Signals that an I/O exception has occurred. + */ + // @Test + public void testAutoLearnTslMain() throws ApexException, InterruptedException, IOException { + + final double dwant = 50.0; + final double toleranceTileJump = 3.0; + + final AxPolicyModel apexPolicyModel = new AdaptiveDomainModelFactory().getAutoLearnPolicyModel(); + assertNotNull(apexPolicyModel); + + final AxValidationResult validationResult = new AxValidationResult(); + apexPolicyModel.validate(validationResult); + assertTrue(validationResult.isValid()); + + final AxArtifactKey key = new AxArtifactKey("AADMApexEngine", "0.0.1"); + final EngineParameters parameters = new EngineParameters(); + parameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); + parameters.getExecutorParameterMap().put("JAVA", new JavaExecutorParameters()); + + final ApexEngine apexEngine1 = new ApexEngineFactory().createApexEngine(key); + + final TestApexActionListener listener1 = new TestApexActionListener("TestListener1"); + apexEngine1.addEventListener("listener1", listener1); + apexEngine1.updateModel(apexPolicyModel); + apexEngine1.start(); + + final EnEvent triggerEvent = apexEngine1.createEvent(new AxArtifactKey("AutoLearnTriggerEvent", "0.0.1")); + assertNotNull(triggerEvent); + final double dmin = -100; + final double dmax = 100; + + double rval = (((rand.nextGaussian() + 1) / 2) * (dmax - dmin)) + dmin; + triggerEvent.put("MonitoredValue", rval); + triggerEvent.put("LastMonitoredValue", 0); + + double avval = 0; + double distance; + double avcount = 0; + + for (int iteration = 0; iteration < MAXITERATIONS; iteration++) { + // Trigger the policy in engine 1 + LOGGER.info("Triggering policy in Engine 1 with " + triggerEvent); + apexEngine1.handleEvent(triggerEvent); + final EnEvent result = listener1.getResult(); + LOGGER.info("Receiving action event {} ", result); + triggerEvent.clear(); + + double val = (Double) result.get("MonitoredValue"); + final double prevval = (Double) result.get("LastMonitoredValue"); + + triggerEvent.put("MonitoredValue", prevval); + triggerEvent.put("LastMonitoredValue", val); + + avcount = Math.min((avcount + 1), 20); // maintain average of only the last 20 values + avval = ((avval * (avcount - 1)) + val) / (avcount); + + distance = Math.abs(dwant - avval); + if (distance < toleranceTileJump) { + rval = (((rand.nextGaussian() + 1) / 2) * (dmax - dmin)) + dmin; + val = rval; + triggerEvent.put("MonitoredValue", val); + LOGGER.info("Iteration " + iteration + ": Average " + avval + " has become closer (" + distance + + ") than " + toleranceTileJump + " to " + dwant + " so reseting val:\t\t\t\t\t\t\t\t" + val); + avval = 0; + avcount = 0; + } + LOGGER.info("Iteration " + iteration + ": \tpreval\t" + prevval + "\tval\t" + val + "\tavval\t" + avval); + + result.clear(); + ThreadUtilities.sleep(10); + } + + apexEngine1.stop(); + ThreadUtilities.sleep(1000); + } + + /** + * The main method. + * + * @param args the arguments + * @throws ApexException the apex exception + * @throws InterruptedException the interrupted exception + * @throws IOException Signals that an I/O exception has occurred. + */ + public static void main(final String[] args) throws ApexException, InterruptedException, IOException { + new AutoLearnTslUseCaseTest().testAutoLearnTslMain(); + } +} diff --git a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAnomalyDetectionDbWrite.java b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAnomalyDetectionDbWrite.java deleted file mode 100644 index 8f54bf12f..000000000 --- a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAnomalyDetectionDbWrite.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.examples.adaptive; - -import java.io.File; -import java.sql.Connection; -import java.sql.DriverManager; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.model.basicmodel.dao.DaoParameters; -import org.onap.policy.apex.model.basicmodel.test.TestApexModel; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; - -public class TestAnomalyDetectionDbWrite { - private Connection connection; - TestApexModel testApexModel; - - /** - * Sets up embedded Derby database and the Apex anomaly detection model for the tests. - * @throws Exception exception to be thrown while setting up the database connection - */ - @Before - public void setup() throws Exception { - Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); - connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); - - testApexModel = new TestApexModel<>(AxPolicyModel.class, new TestAnomalyDetectionModelCreator()); - } - - @After - public void teardown() throws Exception { - connection.close(); - new File("derby.log").delete(); - } - - @Test - public void testModelWriteReadJpa() throws Exception { - final DaoParameters DaoParameters = new DaoParameters(); - DaoParameters.setPluginClass("org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao"); - DaoParameters.setPersistenceUnit("AdaptiveModelsTest"); - testApexModel.testApexModelWriteReadJpa(DaoParameters); - } -} diff --git a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAnomalyDetectionModel.java b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAnomalyDetectionModel.java deleted file mode 100644 index 9e631ef2e..000000000 --- a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAnomalyDetectionModel.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.examples.adaptive; - -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.sql.Connection; -import java.sql.DriverManager; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; -import org.onap.policy.apex.model.basicmodel.dao.DaoParameters; -import org.onap.policy.apex.model.basicmodel.test.TestApexModel; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; - -public class TestAnomalyDetectionModel { - private Connection connection; - TestApexModel testApexModel; - - /** - * Sets up embedded Derby database and the Apex anomaly detection model for the tests. - * @throws Exception exception to be thrown while setting up the database connection - */ - @Before - public void setup() throws Exception { - Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); - connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); - - testApexModel = new TestApexModel<>(AxPolicyModel.class, new TestAnomalyDetectionModelCreator()); - } - - @After - public void teardown() throws Exception { - connection.close(); - new File("derby.log").delete(); - } - - @Test - public void testModelValid() throws Exception { - final AxValidationResult result = testApexModel.testApexModelValid(); - assertTrue(result.toString().equals(VALID_MODEL_STRING)); - } - - @Test - public void testModelWriteReadXml() throws Exception { - testApexModel.testApexModelWriteReadXml(); - } - - @Test - public void testModelWriteReadJson() throws Exception { - testApexModel.testApexModelWriteReadJson(); - } - - @Test - public void testModelWriteReadJpa() throws Exception { - final DaoParameters DaoParameters = new DaoParameters(); - DaoParameters.setPluginClass("org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao"); - DaoParameters.setPersistenceUnit("AdaptiveModelsTest"); - - testApexModel.testApexModelWriteReadJpa(DaoParameters); - } - - private static final String VALID_MODEL_STRING = "***validation of model successful***"; -} diff --git a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAnomalyDetectionTslUseCase.java b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAnomalyDetectionTslUseCase.java deleted file mode 100644 index c29a3cb6e..000000000 --- a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAnomalyDetectionTslUseCase.java +++ /dev/null @@ -1,233 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.examples.adaptive; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.util.Random; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; -import org.onap.policy.apex.context.parameters.ContextParameterConstants; -import org.onap.policy.apex.context.parameters.ContextParameters; -import org.onap.policy.apex.context.parameters.SchemaParameters; -import org.onap.policy.apex.core.engine.EngineParameters; -import org.onap.policy.apex.core.engine.engine.ApexEngine; -import org.onap.policy.apex.core.engine.engine.impl.ApexEngineFactory; -import org.onap.policy.apex.core.engine.event.EnEvent; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.examples.adaptive.model.AdaptiveDomainModelFactory; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; -import org.onap.policy.apex.plugins.executor.java.JavaExecutorParameters; -import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; -import org.onap.policy.common.parameters.ParameterService; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -/** - * This policy passes, and recieves a Double event context filed called "EVCDouble".
- * The policy tries to detect anomalies in the pattern of values for EVCDouble
- * See the 2 test cases below (1 short, 1 long) - * - * @author John Keeney (John.Keeney@ericsson.com) - */ -public class TestAnomalyDetectionTslUseCase { - private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestAnomalyDetectionTslUseCase.class); - - private static final int MAXITERATIONS = 3660; - private static final Random RAND = new Random(System.currentTimeMillis()); - - private SchemaParameters schemaParameters; - private ContextParameters contextParameters; - private EngineParameters engineParameters; - - /** - * Before test. - */ - @Before - public void beforeTest() { - schemaParameters = new SchemaParameters(); - - schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); - schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); - - ParameterService.register(schemaParameters); - - contextParameters = new ContextParameters(); - - contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); - contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); - contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); - contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); - - ParameterService.register(contextParameters); - ParameterService.register(contextParameters.getDistributorParameters()); - ParameterService.register(contextParameters.getLockManagerParameters()); - ParameterService.register(contextParameters.getPersistorParameters()); - - engineParameters = new EngineParameters(); - engineParameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); - engineParameters.getExecutorParameterMap().put("JAVA", new JavaExecutorParameters()); - ParameterService.register(engineParameters); - } - - /** - * After test. - */ - @After - public void afterTest() { - ParameterService.deregister(engineParameters); - - ParameterService.deregister(contextParameters.getDistributorParameters()); - ParameterService.deregister(contextParameters.getLockManagerParameters()); - ParameterService.deregister(contextParameters.getPersistorParameters()); - ParameterService.deregister(contextParameters); - - ParameterService.deregister(schemaParameters); - } - - /** - * Test anomaly detection tsl. - * - * @throws ApexException the apex exception - * @throws InterruptedException the interrupted exception - * @throws IOException Signals that an I/O exception has occurred. - */ - @Test - // once through the long running test below - public void testAnomalyDetectionTsl() throws ApexException, InterruptedException, IOException { - final AxPolicyModel apexPolicyModel = new AdaptiveDomainModelFactory().getAnomalyDetectionPolicyModel(); - assertNotNull(apexPolicyModel); - - final AxValidationResult validationResult = new AxValidationResult(); - apexPolicyModel.validate(validationResult); - assertTrue(validationResult.isValid()); - - final AxArtifactKey key = new AxArtifactKey("AnomalyTSLApexEngine", "0.0.1"); - - final ApexEngine apexEngine1 = new ApexEngineFactory().createApexEngine(key); - - final TestApexActionListener listener1 = new TestApexActionListener("TestListener1"); - apexEngine1.addEventListener("listener", listener1); - apexEngine1.updateModel(apexPolicyModel); - apexEngine1.start(); - final EnEvent triggerEvent = - apexEngine1.createEvent(new AxArtifactKey("AnomalyDetectionTriggerEvent", "0.0.1")); - final double rval = RAND.nextGaussian(); - triggerEvent.put("Iteration", 0); - triggerEvent.put("MonitoredValue", rval); - LOGGER.info("Triggering policy in Engine 1 with " + triggerEvent); - apexEngine1.handleEvent(triggerEvent); - final EnEvent result = listener1.getResult(); - LOGGER.info("Receiving action event {} ", result); - assertEquals("ExecutionIDs are different", triggerEvent.getExecutionId(), result.getExecutionId()); - triggerEvent.clear(); - result.clear(); - ThreadUtilities.sleep(1); - apexEngine1.stop(); - } - - /** - * This policy passes, and recieves a Double event context filed called "EVCDouble"
- * The policy tries to detect anomalies in the pattern of values for EVCDouble
- * This test case generates a SineWave-like pattern for the parameter, repeating every 360 iterations. (These Period - * should probably be set using TaskParameters!) Every 361st value is a random number!, so should be identified as - * an Anomaly. The policy has 3 Decide Tasks, and the Decide TaskSelectionLogic picks one depending on the - * 'Anomaliness' of the input data.
- * To plot the results grep debug results for the string "************", paste into excel and delete non-relevant - * columns
- * - * @throws ApexException the apex exception - * @throws InterruptedException the interrupted exception - * @throws IOException Signals that an I/O exception has occurred. - */ - // Test is disabled by default. uncomment below, or execute using the main() method - // @Test - // EG Dos command: apex-core.engine> mvn - // -Dtest=org.onap.policy.apex.core.engine.ml.TestAnomalyDetectionTslUseCase test | findstr /L /C:"Apex [main] DEBUG - // c.e.a.e.TaskSelectionExecutionLogging - - // TestAnomalyDetectionTSL_Policy0000DecideStateTaskSelectionLogic.getTask():" - public void testAnomalyDetectionTslmain() throws ApexException, InterruptedException, IOException { - - final AxPolicyModel apexPolicyModel = new AdaptiveDomainModelFactory().getAnomalyDetectionPolicyModel(); - assertNotNull(apexPolicyModel); - - final AxValidationResult validationResult = new AxValidationResult(); - apexPolicyModel.validate(validationResult); - assertTrue(validationResult.isValid()); - - final AxArtifactKey key = new AxArtifactKey("AnomalyTSLApexEngine", "0.0.1"); - final EngineParameters parameters = new EngineParameters(); - parameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); - parameters.getExecutorParameterMap().put("JAVA", new JavaExecutorParameters()); - - final ApexEngine apexEngine1 = new ApexEngineFactory().createApexEngine(key); - - final TestApexActionListener listener1 = new TestApexActionListener("TestListener1"); - apexEngine1.addEventListener("listener1", listener1); - apexEngine1.updateModel(apexPolicyModel); - apexEngine1.start(); - - final EnEvent triggerEvent = - apexEngine1.createEvent(new AxArtifactKey("AnomalyDetectionTriggerEvent", "0.0.1")); - assertNotNull(triggerEvent); - - for (int iteration = 0; iteration < MAXITERATIONS; iteration++) { - // Trigger the policy in engine 1 - - double value = (Math.sin(Math.toRadians(iteration))) + (RAND.nextGaussian() / 25.0); - // lets make every 361st number a random value to perhaps flag as an anomaly - if (((iteration + 45) % 361) == 0) { - value = (RAND.nextGaussian() * 2.0); - } - triggerEvent.put("Iteration", iteration); - triggerEvent.put("MonitoredValue", value); - LOGGER.info("Iteration " + iteration + ":\tTriggering policy in Engine 1 with " + triggerEvent); - apexEngine1.handleEvent(triggerEvent); - final EnEvent result = listener1.getResult(); - LOGGER.info("Iteration " + iteration + ":\tReceiving action event {} ", result); - triggerEvent.clear(); - result.clear(); - } - apexEngine1.stop(); - ThreadUtilities.sleep(1000); - } - - /** - * The main method. - * - * @param args the arguments - * @throws ApexException the apex exception - * @throws InterruptedException the interrupted exception - * @throws IOException Signals that an I/O exception has occurred. - */ - public static void main(final String[] args) throws ApexException, InterruptedException, IOException { - new TestAnomalyDetectionTslUseCase().testAnomalyDetectionTslmain(); - } -} diff --git a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAutoLearnDbWrite.java b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAutoLearnDbWrite.java deleted file mode 100644 index d4c1ab193..000000000 --- a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAutoLearnDbWrite.java +++ /dev/null @@ -1,64 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.examples.adaptive; - -import java.io.File; -import java.sql.Connection; -import java.sql.DriverManager; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.model.basicmodel.dao.DaoParameters; -import org.onap.policy.apex.model.basicmodel.test.TestApexModel; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; - -public class TestAutoLearnDbWrite { - private Connection connection; - TestApexModel testApexModel; - - /** - * Sets up embedded Derby database and the Apex AutoLearn model for the tests. - * @throws Exception exception to be thrown while setting up the database connection - */ - @Before - public void setup() throws Exception { - Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); - connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); - - testApexModel = new TestApexModel<>(AxPolicyModel.class, new TestAutoLearnModelCreator()); - } - - @After - public void teardown() throws Exception { - connection.close(); - new File("derby.log").delete(); - } - - @Test - public void testModelWriteReadJpa() throws Exception { - final DaoParameters DaoParameters = new DaoParameters(); - DaoParameters.setPluginClass("org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao"); - DaoParameters.setPersistenceUnit("AdaptiveModelsTest"); - - testApexModel.testApexModelWriteReadJpa(DaoParameters); - } -} diff --git a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAutoLearnModel.java b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAutoLearnModel.java deleted file mode 100644 index 9bf7ce57a..000000000 --- a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAutoLearnModel.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.examples.adaptive; - -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.sql.Connection; -import java.sql.DriverManager; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; -import org.onap.policy.apex.model.basicmodel.dao.DaoParameters; -import org.onap.policy.apex.model.basicmodel.test.TestApexModel; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; - -public class TestAutoLearnModel { - private Connection connection; - TestApexModel testApexModel; - - /** - * Sets up embedded Derby database and the Apex AutoLearn model for the tests. - * @throws Exception exception to be thrown while setting up the database connection - */ - @Before - public void setup() throws Exception { - Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); - connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); - - testApexModel = new TestApexModel<>(AxPolicyModel.class, new TestAutoLearnModelCreator()); - } - - @After - public void teardown() throws Exception { - connection.close(); - new File("derby.log").delete(); - } - - @Test - public void testModelValid() throws Exception { - final AxValidationResult result = testApexModel.testApexModelValid(); - assertTrue(result.toString().equals(VALID_MODEL_STRING)); - } - - @Test - public void testModelWriteReadXml() throws Exception { - testApexModel.testApexModelWriteReadXml(); - } - - @Test - public void testModelWriteReadJson() throws Exception { - testApexModel.testApexModelWriteReadJson(); - } - - @Test - public void testModelWriteReadJpa() throws Exception { - final DaoParameters DaoParameters = new DaoParameters(); - DaoParameters.setPluginClass("org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao"); - DaoParameters.setPersistenceUnit("AdaptiveModelsTest"); - - testApexModel.testApexModelWriteReadJpa(DaoParameters); - } - - private static final String VALID_MODEL_STRING = "***validation of model successful***"; -} diff --git a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAutoLearnTslUseCase.java b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAutoLearnTslUseCase.java deleted file mode 100644 index 10d69a457..000000000 --- a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAutoLearnTslUseCase.java +++ /dev/null @@ -1,256 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.examples.adaptive; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.util.Random; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; -import org.onap.policy.apex.context.parameters.ContextParameterConstants; -import org.onap.policy.apex.context.parameters.ContextParameters; -import org.onap.policy.apex.context.parameters.SchemaParameters; -import org.onap.policy.apex.core.engine.EngineParameters; -import org.onap.policy.apex.core.engine.engine.ApexEngine; -import org.onap.policy.apex.core.engine.engine.impl.ApexEngineFactory; -import org.onap.policy.apex.core.engine.event.EnEvent; -import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; -import org.onap.policy.apex.examples.adaptive.model.AdaptiveDomainModelFactory; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; -import org.onap.policy.apex.plugins.executor.java.JavaExecutorParameters; -import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; -import org.onap.policy.common.parameters.ParameterService; -import org.slf4j.ext.XLogger; -import org.slf4j.ext.XLoggerFactory; - -// TODO: Auto-generated Javadoc -/** - * Test Auto learning in TSL. - * - * @author John Keeney (John.Keeney@ericsson.com) - */ -public class TestAutoLearnTslUseCase { - private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestAutoLearnTslUseCase.class); - - private static final int MAXITERATIONS = 1000; - private static final Random rand = new Random(System.currentTimeMillis()); - - private SchemaParameters schemaParameters; - private ContextParameters contextParameters; - private EngineParameters engineParameters; - - /** - * Before test. - */ - @Before - public void beforeTest() { - schemaParameters = new SchemaParameters(); - - schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); - schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); - - ParameterService.register(schemaParameters); - - contextParameters = new ContextParameters(); - - contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); - contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); - contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); - contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); - - ParameterService.register(contextParameters); - ParameterService.register(contextParameters.getDistributorParameters()); - ParameterService.register(contextParameters.getLockManagerParameters()); - ParameterService.register(contextParameters.getPersistorParameters()); - - engineParameters = new EngineParameters(); - engineParameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); - engineParameters.getExecutorParameterMap().put("JAVA", new JavaExecutorParameters()); - ParameterService.register(engineParameters); - } - - /** - * After test. - */ - @After - public void afterTest() { - ParameterService.deregister(engineParameters); - - ParameterService.deregister(contextParameters.getDistributorParameters()); - ParameterService.deregister(contextParameters.getLockManagerParameters()); - ParameterService.deregister(contextParameters.getPersistorParameters()); - ParameterService.deregister(contextParameters); - - ParameterService.deregister(schemaParameters); - } - - /** - * Test auto learn tsl. - * - * @throws ApexException the apex exception - * @throws InterruptedException the interrupted exception - * @throws IOException Signals that an I/O exception has occurred. - */ - @Test - // once through the long running test below - public void testAutoLearnTsl() throws ApexException, InterruptedException, IOException { - final AxPolicyModel apexPolicyModel = new AdaptiveDomainModelFactory().getAutoLearnPolicyModel(); - assertNotNull(apexPolicyModel); - - final AxValidationResult validationResult = new AxValidationResult(); - apexPolicyModel.validate(validationResult); - assertTrue(validationResult.isValid()); - - final AxArtifactKey key = new AxArtifactKey("AADMApexEngine", "0.0.1"); - - final ApexEngine apexEngine1 = new ApexEngineFactory().createApexEngine(key); - - final TestApexActionListener listener1 = new TestApexActionListener("TestListener1"); - apexEngine1.addEventListener("listener", listener1); - apexEngine1.updateModel(apexPolicyModel); - apexEngine1.start(); - final EnEvent triggerEvent = apexEngine1.createEvent(new AxArtifactKey("AutoLearnTriggerEvent", "0.0.1")); - final double rval = rand.nextGaussian(); - triggerEvent.put("MonitoredValue", rval); - triggerEvent.put("LastMonitoredValue", 0D); - LOGGER.info("Triggering policy in Engine 1 with " + triggerEvent); - apexEngine1.handleEvent(triggerEvent); - final EnEvent result = listener1.getResult(); - LOGGER.info("Receiving action event {} ", result); - assertEquals("ExecutionIDs are different", triggerEvent.getExecutionId(), result.getExecutionId()); - triggerEvent.clear(); - result.clear(); - ThreadUtilities.sleep(10); - apexEngine1.stop(); - } - - /** - * This policy passes, and receives a Double event context filed called "EVCDouble"
- * The policy tries to keep the value at 50, with a Min -100, Max 100 (These should probably be set using - * TaskParameters!)
- * The policy has 7 Decide Tasks that manipulate the value of this field in unknown ways.
- * The Decide TSL learns the effect of each task, and then selects the appropriate task to get the value back to - * 50
- * After the value settles close to 50 for a while, the test Rests the value to to random number and then - * continues
- * To plot the results grep stdout debug results for the string "*******", paste into excel and delete non-relevant - * columns
- * - * @throws ApexException the apex exception - * @throws InterruptedException the interrupted exception - * @throws IOException Signals that an I/O exception has occurred. - */ - // @Test - public void testAutoLearnTslMain() throws ApexException, InterruptedException, IOException { - - final double dwant = 50.0; - final double toleranceTileJump = 3.0; - - final AxPolicyModel apexPolicyModel = new AdaptiveDomainModelFactory().getAutoLearnPolicyModel(); - assertNotNull(apexPolicyModel); - - final AxValidationResult validationResult = new AxValidationResult(); - apexPolicyModel.validate(validationResult); - assertTrue(validationResult.isValid()); - - final AxArtifactKey key = new AxArtifactKey("AADMApexEngine", "0.0.1"); - final EngineParameters parameters = new EngineParameters(); - parameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); - parameters.getExecutorParameterMap().put("JAVA", new JavaExecutorParameters()); - - final ApexEngine apexEngine1 = new ApexEngineFactory().createApexEngine(key); - - final TestApexActionListener listener1 = new TestApexActionListener("TestListener1"); - apexEngine1.addEventListener("listener1", listener1); - apexEngine1.updateModel(apexPolicyModel); - apexEngine1.start(); - - final EnEvent triggerEvent = apexEngine1.createEvent(new AxArtifactKey("AutoLearnTriggerEvent", "0.0.1")); - assertNotNull(triggerEvent); - final double dmin = -100; - final double dmax = 100; - - double rval = (((rand.nextGaussian() + 1) / 2) * (dmax - dmin)) + dmin; - triggerEvent.put("MonitoredValue", rval); - triggerEvent.put("LastMonitoredValue", 0); - - double avval = 0; - double distance; - double avcount = 0; - - for (int iteration = 0; iteration < MAXITERATIONS; iteration++) { - // Trigger the policy in engine 1 - LOGGER.info("Triggering policy in Engine 1 with " + triggerEvent); - apexEngine1.handleEvent(triggerEvent); - final EnEvent result = listener1.getResult(); - LOGGER.info("Receiving action event {} ", result); - triggerEvent.clear(); - - double val = (Double) result.get("MonitoredValue"); - final double prevval = (Double) result.get("LastMonitoredValue"); - - triggerEvent.put("MonitoredValue", prevval); - triggerEvent.put("LastMonitoredValue", val); - - avcount = Math.min((avcount + 1), 20); // maintain average of only the last 20 values - avval = ((avval * (avcount - 1)) + val) / (avcount); - - distance = Math.abs(dwant - avval); - if (distance < toleranceTileJump) { - rval = (((rand.nextGaussian() + 1) / 2) * (dmax - dmin)) + dmin; - val = rval; - triggerEvent.put("MonitoredValue", val); - LOGGER.info("Iteration " + iteration + ": Average " + avval + " has become closer (" + distance - + ") than " + toleranceTileJump + " to " + dwant + " so reseting val:\t\t\t\t\t\t\t\t" + val); - avval = 0; - avcount = 0; - } - LOGGER.info("Iteration " + iteration + ": \tpreval\t" + prevval + "\tval\t" + val + "\tavval\t" + avval); - - result.clear(); - ThreadUtilities.sleep(10); - } - - apexEngine1.stop(); - ThreadUtilities.sleep(1000); - } - - /** - * The main method. - * - * @param args the arguments - * @throws ApexException the apex exception - * @throws InterruptedException the interrupted exception - * @throws IOException Signals that an I/O exception has occurred. - */ - public static void main(final String[] args) throws ApexException, InterruptedException, IOException { - new TestAutoLearnTslUseCase().testAutoLearnTslMain(); - } -} diff --git a/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/MfpLogicTest.java b/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/MfpLogicTest.java new file mode 100644 index 000000000..f19e2c8c3 --- /dev/null +++ b/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/MfpLogicTest.java @@ -0,0 +1,183 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.examples.myfirstpolicy; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Map.Entry; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.apex.examples.myfirstpolicy.model.MfpDomainModelFactory; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicy; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.onap.policy.apex.model.policymodel.concepts.AxState; +import org.onap.policy.apex.model.policymodel.concepts.AxTask; +import org.onap.policy.common.utils.resources.ResourceUtils; + +/** + * The Class TestMfpLogic. + */ +public class MfpLogicTest { + + private static final Map LOGICEXTENSIONS = new LinkedHashMap<>(); + + /** + * Test setup. + */ + @BeforeClass + public static void testMfpUseCaseSetup() { + LOGICEXTENSIONS.put("MVEL", "mvel"); + LOGICEXTENSIONS.put("JAVASCRIPT", "js"); + } + + /** + * Check logic for MyFirstPolicy#1. + */ + @Test + public void testMfp1TaskLogic() { + final AxPolicyModel apexPolicyModel = new MfpDomainModelFactory().getMfp1PolicyModel(); + assertNotNull(apexPolicyModel); + + final Map logics = new LinkedHashMap<>(); + logics.putAll(getTslLogics(apexPolicyModel)); + logics.putAll(getTaskLogics(apexPolicyModel)); + + for (final Entry logicvalue : logics.entrySet()) { + final String filename = "examples/models/MyFirstPolicy/1/" + logicvalue.getKey(); + final String logic = logicvalue.getValue(); + final String expectedlogic = ResourceUtils.getResourceAsString(filename); + assertNotNull("File " + filename + " was not found. It should contain logic for PolicyModel " + + apexPolicyModel.getKey(), expectedlogic); + assertEquals( + "The task in " + filename + " is not the same as the relevant logic in PolicyModel " + + apexPolicyModel.getKey(), + expectedlogic.replaceAll("\\s", ""), logic.replaceAll("\\s", "")); + } + } + + + /** + * Check logic for MyFirstPolicyAlt#1. + */ + @Test + public void testMfp1AltTaskLogic() { + final AxPolicyModel apexPolicyModel = new MfpDomainModelFactory().getMfp1AltPolicyModel(); + assertNotNull(apexPolicyModel); + + final Map logics = new LinkedHashMap<>(); + logics.putAll(getTslLogics(apexPolicyModel)); + logics.putAll(getTaskLogics(apexPolicyModel)); + + for (final Entry logicvalue : logics.entrySet()) { + final String filename = "examples/models/MyFirstPolicy/1/" + logicvalue.getKey(); + final String logic = logicvalue.getValue(); + final String expectedlogic = ResourceUtils.getResourceAsString(filename); + assertNotNull("File " + filename + " was not found. It should contain logic for PolicyModel " + + apexPolicyModel.getKey(), expectedlogic); + assertEquals( + "The task in " + filename + " is not the same as the relevant logic in PolicyModel " + + apexPolicyModel.getKey(), + expectedlogic.replaceAll("\\s", ""), logic.replaceAll("\\s", "")); + } + } + + /** + * Check logic for MyFirstPolicy2. + */ + @Test + public void testMfp2TaskLogic() { + final AxPolicyModel apexPolicyModel = new MfpDomainModelFactory().getMfp2PolicyModel(); + assertNotNull(apexPolicyModel); + + final Map logics = new LinkedHashMap<>(); + logics.putAll(getTslLogics(apexPolicyModel)); + logics.putAll(getTaskLogics(apexPolicyModel)); + + for (final Entry logicvalue : logics.entrySet()) { + final String filename = "examples/models/MyFirstPolicy/2/" + logicvalue.getKey(); + final String logic = logicvalue.getValue(); + final String expectedlogic = ResourceUtils.getResourceAsString(filename); + assertNotNull("File " + filename + " was not found. It should contain logic for PolicyModel " + + apexPolicyModel.getKey(), expectedlogic); + assertEquals( + "The task in " + filename + " is not the same as the relevant logic in PolicyModel " + + apexPolicyModel.getKey(), + expectedlogic.replaceAll("\\s", ""), logic.replaceAll("\\s", "")); + } + } + + /** + * Gets the TSL logics. + * + * @param apexPolicyModel the apex policy model + * @return the TSL logics + */ + private Map getTslLogics(final AxPolicyModel apexPolicyModel) { + final Map ret = new LinkedHashMap<>(); + for (final Entry policyentry : apexPolicyModel.getPolicies().getPolicyMap() + .entrySet()) { + for (final Entry statesentry : policyentry.getValue().getStateMap().entrySet()) { + final AxState state = statesentry.getValue(); + final String tsllogic = state.getTaskSelectionLogic().getLogic(); + final String tsllogicflavour = state.getTaskSelectionLogic().getLogicFlavour(); + if (tsllogic != null && tsllogic.trim().length() > 0) { + assertNotNull( + "Logic Type \"" + tsllogicflavour + "\" in state " + statesentry.getKey() + " in policy " + + policyentry.getKey() + " is not supported in this test", + LOGICEXTENSIONS.get(tsllogicflavour.toUpperCase())); + final String filename = policyentry.getKey().getName() + "_" + statesentry.getKey() + "TSL." + + LOGICEXTENSIONS.get(tsllogicflavour.toUpperCase()); + ret.put(filename, tsllogic); + } + } + } + return ret; + } + + /** + * Gets the task logics. + * + * @param apexPolicyModel the apex policy model + * @return the task logics + */ + private Map getTaskLogics(final AxPolicyModel apexPolicyModel) { + final Map ret = new LinkedHashMap<>(); + for (final Entry taskentry : apexPolicyModel.getTasks().getTaskMap().entrySet()) { + final AxTask task = taskentry.getValue(); + final String tasklogic = task.getTaskLogic().getLogic(); + final String tasklogicflavour = task.getTaskLogic().getLogicFlavour(); + assertTrue("No/Blank logic found in task " + taskentry.getKey(), + (tasklogic != null && tasklogic.trim().length() > 0)); + assertNotNull("Logic Type \"" + tasklogicflavour + "\" in task " + taskentry.getKey() + + " is not supported in this test", LOGICEXTENSIONS.get(tasklogicflavour.toUpperCase())); + final String filename = + taskentry.getKey().getName() + "." + LOGICEXTENSIONS.get(tasklogicflavour.toUpperCase()); + ret.put(filename, tasklogic); + } + return ret; + } +} diff --git a/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/MfpModelCliTest.java b/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/MfpModelCliTest.java new file mode 100644 index 000000000..ce78b7671 --- /dev/null +++ b/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/MfpModelCliTest.java @@ -0,0 +1,96 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.examples.myfirstpolicy; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.io.IOException; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.apex.auth.clieditor.ApexCommandLineEditorMain; +import org.onap.policy.apex.model.basicmodel.handling.ApexModelException; +import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.onap.policy.apex.model.utilities.TextFileUtils; + +/** + * Test MyFirstPolicyModel CLI. + */ +public class MfpModelCliTest { + private static AxPolicyModel testApexModel1; + private static AxPolicyModel testApexModel2; + + /** + * Setup the test. + * + * @throws Exception if there is an error + */ + @BeforeClass + public static void setup() throws Exception { + testApexModel1 = new TestMfpModelCreator.TestMfp1ModelCreator().getModel(); + testApexModel2 = new TestMfpModelCreator.TestMfp2ModelCreator().getModel(); + } + + /** + * Test CLI policy. + * + * @throws IOException Signals that an I/O exception has occurred. + * @throws ApexModelException ifd there is an Apex Error + */ + @Test + public void testCliPolicy() throws IOException, ApexModelException { + + final File tempLogFile1 = File.createTempFile("TestMyFirstPolicy1CLI", ".log"); + final File tempModelFile1 = File.createTempFile("TestMyFirstPolicy1CLI", ".json"); + final File tempLogFile2 = File.createTempFile("TestMyFirstPolicy2CLI", ".log"); + final File tempModelFile2 = File.createTempFile("TestMyFirstPolicy2CLI", ".json"); + final String[] testApexModel1CliArgs = + { "-c", "src/main/resources/examples/models/MyFirstPolicy/1/MyFirstPolicyModel_0.0.1.apex", "-l", + tempLogFile1.getAbsolutePath(), "-o", tempModelFile1.getAbsolutePath() }; + final String[] testApexModel2CliArgs = + { "-c", "src/main/resources/examples/models/MyFirstPolicy/2/MyFirstPolicyModel_0.0.1.apex", "-l", + tempLogFile2.getAbsolutePath(), "-o", tempModelFile2.getAbsolutePath() }; + + new ApexCommandLineEditorMain(testApexModel1CliArgs); + new ApexCommandLineEditorMain(testApexModel2CliArgs); + + final ApexModelReader reader = new ApexModelReader<>(AxPolicyModel.class); + AxPolicyModel generatedmodel = reader.read(TextFileUtils.getTextFileAsString(tempModelFile1.getAbsolutePath())); + + assertEquals("Model generated from the CLI (" + testApexModel1CliArgs[1] + ") into file " + + tempModelFile1.getAbsolutePath() + " is not the same as the test Model for " + + testApexModel1.getKey(), testApexModel1, generatedmodel); + + generatedmodel = reader.read(TextFileUtils.getTextFileAsString(tempModelFile2.getAbsolutePath())); + assertEquals("Model generated from the CLI (" + testApexModel2CliArgs[1] + ") into file " + + tempModelFile2.getAbsolutePath() + " is not the same as the test Model for " + + testApexModel2.getKey(), testApexModel2, generatedmodel); + + tempLogFile1.delete(); + tempModelFile1.delete(); + + tempLogFile2.delete(); + tempModelFile2.delete(); + + } +} diff --git a/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/MfpModelTest.java b/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/MfpModelTest.java new file mode 100644 index 000000000..d6ec2bb8d --- /dev/null +++ b/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/MfpModelTest.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.examples.myfirstpolicy; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.sql.Connection; +import java.sql.DriverManager; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.basicmodel.test.TestApexModel; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; + +/** + * Test MyFirstPolicy Model. + * + * @author John Keeney (john.keeney@ericsson.com) + */ +public class MfpModelTest { + + private static Connection connection; + private static TestApexModel testApexModel1; + private static TestApexModel testApexModel2; + + /** + * Setup. + * + * @throws Exception if there is an error + */ + @BeforeClass + public static void setup() throws Exception { + Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); + connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); + testApexModel1 = new TestApexModel<>(AxPolicyModel.class, new TestMfpModelCreator.TestMfp1ModelCreator()); + testApexModel2 = new TestApexModel<>(AxPolicyModel.class, new TestMfpModelCreator.TestMfp2ModelCreator()); + } + + /** + * Teardown. + * + * @throws Exception if there is an error + */ + @AfterClass + public static void teardown() throws Exception { + connection.close(); + new File("derby.log").delete(); + } + + /** + * Test model is valid. + * + * @throws Exception if there is an error + */ + @Test + public void testModelValid() throws Exception { + AxValidationResult result = testApexModel1.testApexModelValid(); + assertTrue("Model did not validate cleanly", result.isOk()); + + result = testApexModel2.testApexModelValid(); + assertTrue("Model did not validate cleanly", result.isOk()); + } + + /** + * Test model write and read XML. + * + * @throws Exception if there is an error + */ + @Test + public void testModelWriteReadXml() throws Exception { + testApexModel1.testApexModelWriteReadXml(); + testApexModel2.testApexModelWriteReadXml(); + } + + /** + * Test model write and read JSON. + * + * @throws Exception if there is an error + */ + @Test + public void testModelWriteReadJson() throws Exception { + testApexModel1.testApexModelWriteReadJson(); + testApexModel2.testApexModelWriteReadJson(); + } +} diff --git a/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/MfpUseCaseTest.java b/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/MfpUseCaseTest.java new file mode 100644 index 000000000..1b9a5a5c7 --- /dev/null +++ b/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/MfpUseCaseTest.java @@ -0,0 +1,383 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.examples.myfirstpolicy; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; +import org.onap.policy.apex.context.parameters.ContextParameterConstants; +import org.onap.policy.apex.context.parameters.ContextParameters; +import org.onap.policy.apex.context.parameters.SchemaParameters; +import org.onap.policy.apex.core.engine.EngineParameters; +import org.onap.policy.apex.core.engine.engine.impl.ApexEngineFactory; +import org.onap.policy.apex.core.engine.engine.impl.ApexEngineImpl; +import org.onap.policy.apex.core.engine.event.EnEvent; +import org.onap.policy.apex.examples.myfirstpolicy.model.MfpDomainModelFactory; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.eventmodel.concepts.AxEvent; +import org.onap.policy.apex.model.eventmodel.concepts.AxField; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters; +import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; +import org.onap.policy.common.parameters.ParameterService; +import org.onap.policy.common.utils.resources.ResourceUtils; + +/** + * Test MyFirstPolicy Use Case. + */ +public class MfpUseCaseTest { + // CHECKSTYLE:OFF: MagicNumber + + private static ApexEngineImpl apexEngine; + + /** + * Test MFP use case setup. + */ + @BeforeClass + public static void testMfpUseCaseSetup() { + final AxArtifactKey key = new AxArtifactKey("MyFirstPolicyApexEngine", "0.0.1"); + apexEngine = (ApexEngineImpl) new ApexEngineFactory().createApexEngine(key); + } + + private static ContextParameters contextParameters; + private static SchemaParameters schemaParameters; + private static EngineParameters engineParameters; + + /** + * Before test. + */ + @BeforeClass + public static void beforeTest() { + schemaParameters = new SchemaParameters(); + + schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); + schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); + + ParameterService.register(schemaParameters); + + contextParameters = new ContextParameters(); + + contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); + contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); + contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); + contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); + + ParameterService.register(contextParameters); + ParameterService.register(contextParameters.getDistributorParameters()); + ParameterService.register(contextParameters.getLockManagerParameters()); + ParameterService.register(contextParameters.getPersistorParameters()); + + engineParameters = new EngineParameters(); + engineParameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); + engineParameters.getExecutorParameterMap().put("JAVASCRIPT", new JavascriptExecutorParameters()); + ParameterService.register(engineParameters); + } + + /** + * After test. + */ + @AfterClass + public static void afterTest() { + ParameterService.deregister(engineParameters); + + ParameterService.deregister(contextParameters.getDistributorParameters()); + ParameterService.deregister(contextParameters.getLockManagerParameters()); + ParameterService.deregister(contextParameters.getPersistorParameters()); + ParameterService.deregister(contextParameters); + + ParameterService.deregister(schemaParameters); + } + + /** + * Test MyFirstPolicy#1 use case. + * + * @throws ApexException if there is an Apex error + * @throws InterruptedException if there is an Interruption. + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testMfp1Case() throws ApexException, InterruptedException, IOException { + final AxPolicyModel apexPolicyModel = new MfpDomainModelFactory().getMfp1PolicyModel(); + assertNotNull(apexPolicyModel); + + final TestSaleAuthListener listener = new TestSaleAuthListener("Test"); + apexEngine.addEventListener("listener", listener); + apexEngine.updateModel(apexPolicyModel); + apexEngine.start(); + + final AxEvent axEventin = apexPolicyModel.getEvents().get(new AxArtifactKey("SALE_INPUT:0.0.1")); + assertNotNull(axEventin); + final AxEvent axEventout = apexPolicyModel.getEvents().get(new AxArtifactKey("SALE_AUTH:0.0.1")); + assertNotNull(axEventout); + + EnEvent event = fillTriggerEvent(axEventin, "examples/events/MyFirstPolicy/1/EventIn_BoozeItem_084106GMT.json"); + apexEngine.handleEvent(event); + EnEvent resultout = listener.getResult(); + EnEvent resulexpected = + fillResultEvent(axEventout, "examples/events/MyFirstPolicy/1/EventOut_BoozeItem_084106GMT.json"); + assertEquals(resulexpected, resultout); + + event = fillTriggerEvent(axEventin, "examples/events/MyFirstPolicy/1/EventIn_BoozeItem_201713GMT.json"); + apexEngine.handleEvent(event); + resultout = listener.getResult(); + resulexpected = + fillResultEvent(axEventout, "examples/events/MyFirstPolicy/1/EventOut_BoozeItem_201713GMT.json"); + assertEquals(resulexpected, resultout); + assertEquals("ExecutionIDs are different", event.getExecutionId(), resultout.getExecutionId()); + + event = fillTriggerEvent(axEventin, "examples/events/MyFirstPolicy/1/EventIn_NonBoozeItem_101309GMT.json"); + apexEngine.handleEvent(event); + resultout = listener.getResult(); + resulexpected = + fillResultEvent(axEventout, "examples/events/MyFirstPolicy/1/EventOut_NonBoozeItem_101309GMT.json"); + assertEquals(resulexpected, resultout); + assertEquals("ExecutionIDs are different", event.getExecutionId(), resultout.getExecutionId()); + + apexEngine.stop(); + } + + /** + * Test MyFirstPolicy#2 use case. + * + * @throws ApexException if there is an Apex error + * @throws InterruptedException if there is an Interruption. + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void testMfp2Case() throws ApexException, InterruptedException, IOException { + final AxPolicyModel apexPolicyModel = new MfpDomainModelFactory().getMfp2PolicyModel(); + assertNotNull(apexPolicyModel); + + final TestSaleAuthListener listener = new TestSaleAuthListener("Test"); + apexEngine.addEventListener("listener", listener); + apexEngine.updateModel(apexPolicyModel); + apexEngine.start(); + + final AxEvent axEventin = apexPolicyModel.getEvents().get(new AxArtifactKey("SALE_INPUT:0.0.1")); + assertNotNull(axEventin); + final AxEvent axEventout = apexPolicyModel.getEvents().get(new AxArtifactKey("SALE_AUTH:0.0.1")); + assertNotNull(axEventout); + + EnEvent event = fillTriggerEvent(axEventin, "examples/events/MyFirstPolicy/1/EventIn_BoozeItem_084106GMT.json"); + apexEngine.handleEvent(event); + EnEvent resultout = listener.getResult(); + EnEvent resultexpected = + fillResultEvent(axEventout, "examples/events/MyFirstPolicy/1/EventOut_BoozeItem_084106GMT.json"); + assertEquals(resultexpected, resultout); + assertEquals("ExecutionIDs are different", event.getExecutionId(), resultout.getExecutionId()); + + event = fillTriggerEvent(axEventin, "examples/events/MyFirstPolicy/1/EventIn_BoozeItem_201713GMT.json"); + apexEngine.handleEvent(event); + resultout = listener.getResult(); + resultexpected = + fillResultEvent(axEventout, "examples/events/MyFirstPolicy/1/EventOut_BoozeItem_201713GMT.json"); + assertEquals(resultexpected, resultout); + assertEquals("ExecutionIDs are different", event.getExecutionId(), resultout.getExecutionId()); + + event = fillTriggerEvent(axEventin, "examples/events/MyFirstPolicy/1/EventIn_NonBoozeItem_101309GMT.json"); + apexEngine.handleEvent(event); + resultout = listener.getResult(); + resultexpected = + fillResultEvent(axEventout, "examples/events/MyFirstPolicy/1/EventOut_NonBoozeItem_101309GMT.json"); + assertEquals(resultexpected, resultout); + assertEquals("ExecutionIDs are different", event.getExecutionId(), resultout.getExecutionId()); + + event = fillTriggerEvent(axEventin, "examples/events/MyFirstPolicy/2/EventIn_BoozeItem_101433CET_thurs.json"); + apexEngine.handleEvent(event); + resultout = listener.getResult(); + resultexpected = + fillResultEvent(axEventout, "examples/events/MyFirstPolicy/2/EventOut_BoozeItem_101433CET_thurs.json"); + assertEquals(resultexpected, resultout); + assertEquals("ExecutionIDs are different", event.getExecutionId(), resultout.getExecutionId()); + + event = fillTriggerEvent(axEventin, "examples/events/MyFirstPolicy/2/EventIn_BoozeItem_171937CET_sun.json"); + apexEngine.handleEvent(event); + resultout = listener.getResult(); + resultexpected = + fillResultEvent(axEventout, "examples/events/MyFirstPolicy/2/EventOut_BoozeItem_171937CET_sun.json"); + assertEquals(resultexpected, resultout); + assertEquals("ExecutionIDs are different", event.getExecutionId(), resultout.getExecutionId()); + + event = fillTriggerEvent(axEventin, "examples/events/MyFirstPolicy/2/EventIn_NonBoozeItem_111309CET_mon.json"); + apexEngine.handleEvent(event); + resultout = listener.getResult(); + resultexpected = + fillResultEvent(axEventout, "examples/events/MyFirstPolicy/2/EventOut_NonBoozeItem_111309CET_mon.json"); + assertEquals(resultexpected, resultout); + assertEquals("ExecutionIDs are different", event.getExecutionId(), resultout.getExecutionId()); + + apexEngine.stop(); + } + + /** + * Fill trigger event for test. + * + * @param event the event + * @param inputFile the input file + * @return the filled event + */ + private EnEvent fillTriggerEvent(final AxEvent event, final String inputFile) { + final EnEvent ret = new EnEvent(event.getKey()); + final GsonBuilder gb = new GsonBuilder(); + gb.serializeNulls().enableComplexMapKeySerialization(); + final JsonObject jsonObject = + gb.create().fromJson(ResourceUtils.getResourceAsString(inputFile), JsonObject.class); + assertNotNull(jsonObject); + assertTrue(jsonObject.has("name")); + assertTrue(ret.getName().equals(jsonObject.get("name").getAsString())); + assertTrue(ret.getAxEvent().getKey().getName().equals(jsonObject.get("name").getAsString())); + assertTrue(jsonObject.has("nameSpace")); + assertTrue(ret.getAxEvent().getNameSpace().equals(jsonObject.get("nameSpace").getAsString())); + assertTrue(jsonObject.has("version")); + assertTrue(ret.getAxEvent().getKey().getVersion().equals(jsonObject.get("version").getAsString())); + final List reserved = Arrays.asList("name", "nameSpace", "version", "source", "target"); + for (final Map.Entry e : jsonObject.entrySet()) { + if (reserved.contains(e.getKey())) { + continue; + } + assertTrue("Event file " + inputFile + " has a field " + e.getKey() + " but this is not defined for " + + event.getId(), (event.getParameterMap().containsKey(e.getKey()))); + if (jsonObject.get(e.getKey()).isJsonNull()) { + ret.put(e.getKey(), null); + } + } + for (final AxField field : event.getFields()) { + if (!field.getOptional()) { + assertTrue("Event file " + inputFile + " is missing a mandatory field " + field.getKey().getLocalName() + + " for " + event.getId(), jsonObject.has(field.getKey().getLocalName())); + } else { + ret.put(field.getKey().getLocalName(), null); + } + } + if (jsonObject.has("time") && !jsonObject.get("time").isJsonNull()) { + ret.put("time", jsonObject.get("time").getAsLong()); + } + if (jsonObject.has("sale_ID") && !jsonObject.get("sale_ID").isJsonNull()) { + ret.put("sale_ID", jsonObject.get("sale_ID").getAsLong()); + } + if (jsonObject.has("amount") && !jsonObject.get("amount").isJsonNull()) { + ret.put("amount", jsonObject.get("amount").getAsDouble()); + } + if (jsonObject.has("item_ID") && !jsonObject.get("item_ID").isJsonNull()) { + ret.put("item_ID", jsonObject.get("item_ID").getAsLong()); + } + if (jsonObject.has("quantity") && !jsonObject.get("quantity").isJsonNull()) { + ret.put("quantity", jsonObject.get("quantity").getAsInt()); + } + if (jsonObject.has("assistant_ID") && !jsonObject.get("assistant_ID").isJsonNull()) { + ret.put("assistant_ID", jsonObject.get("assistant_ID").getAsLong()); + } + if (jsonObject.has("branch_ID") && !jsonObject.get("branch_ID").isJsonNull()) { + ret.put("branch_ID", jsonObject.get("branch_ID").getAsLong()); + } + if (jsonObject.has("notes") && !jsonObject.get("notes").isJsonNull()) { + ret.put("notes", jsonObject.get("notes").getAsString()); + } + return ret; + } + + /** + * Fill result event for test. + * + * @param event the event + * @param inputFile the input file + * @return the filled event + */ + private EnEvent fillResultEvent(final AxEvent event, final String inputFile) { + final EnEvent ret = new EnEvent(event.getKey()); + final GsonBuilder gb = new GsonBuilder(); + gb.serializeNulls().enableComplexMapKeySerialization(); + final JsonObject jsonObject = + gb.create().fromJson(ResourceUtils.getResourceAsString(inputFile), JsonObject.class); + assertNotNull(jsonObject); + assertTrue(jsonObject.has("name")); + assertTrue(ret.getName().equals(jsonObject.get("name").getAsString())); + assertTrue(ret.getAxEvent().getKey().getName().equals(jsonObject.get("name").getAsString())); + assertTrue(jsonObject.has("nameSpace")); + assertTrue(ret.getAxEvent().getNameSpace().equals(jsonObject.get("nameSpace").getAsString())); + assertTrue(jsonObject.has("version")); + assertTrue(ret.getAxEvent().getKey().getVersion().equals(jsonObject.get("version").getAsString())); + final List reserved = Arrays.asList("name", "nameSpace", "version", "source", "target"); + for (final Map.Entry e : jsonObject.entrySet()) { + if (reserved.contains(e.getKey())) { + continue; + } + assertTrue("Event file " + inputFile + " has a field " + e.getKey() + " but this is not defined for " + + event.getId(), (event.getParameterMap().containsKey(e.getKey()))); + if (jsonObject.get(e.getKey()).isJsonNull()) { + ret.put(e.getKey(), null); + } + } + for (final AxField field : event.getFields()) { + if (!field.getOptional()) { + assertTrue("Event file " + inputFile + " is missing a mandatory field " + field.getKey().getLocalName() + + " for " + event.getId(), jsonObject.has(field.getKey().getLocalName())); + } else { + ret.put(field.getKey().getLocalName(), null); + } + } + if (jsonObject.has("time") && !jsonObject.get("time").isJsonNull()) { + ret.put("time", jsonObject.get("time").getAsLong()); + } + if (jsonObject.has("sale_ID") && !jsonObject.get("sale_ID").isJsonNull()) { + ret.put("sale_ID", jsonObject.get("sale_ID").getAsLong()); + } + if (jsonObject.has("amount") && !jsonObject.get("amount").isJsonNull()) { + ret.put("amount", jsonObject.get("amount").getAsDouble()); + } + if (jsonObject.has("item_ID") && !jsonObject.get("item_ID").isJsonNull()) { + ret.put("item_ID", jsonObject.get("item_ID").getAsLong()); + } + if (jsonObject.has("quantity") && !jsonObject.get("quantity").isJsonNull()) { + ret.put("quantity", jsonObject.get("quantity").getAsInt()); + } + if (jsonObject.has("assistant_ID") && !jsonObject.get("assistant_ID").isJsonNull()) { + ret.put("assistant_ID", jsonObject.get("assistant_ID").getAsLong()); + } + if (jsonObject.has("branch_ID") && !jsonObject.get("branch_ID").isJsonNull()) { + ret.put("branch_ID", jsonObject.get("branch_ID").getAsLong()); + } + if (jsonObject.has("notes") && !jsonObject.get("notes").isJsonNull()) { + ret.put("notes", jsonObject.get("notes").getAsString()); + } + if (jsonObject.has("authorised") && !jsonObject.get("authorised").isJsonNull()) { + ret.put("authorised", jsonObject.get("authorised").getAsString()); + } + if (jsonObject.has("message") && !jsonObject.get("message").isJsonNull()) { + ret.put("message", jsonObject.get("message").getAsString()); + } + return ret; + } +} diff --git a/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpLogic.java b/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpLogic.java deleted file mode 100644 index e425088ff..000000000 --- a/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpLogic.java +++ /dev/null @@ -1,183 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.examples.myfirstpolicy; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; - -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.apex.examples.myfirstpolicy.model.MfpDomainModelFactory; -import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicy; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; -import org.onap.policy.apex.model.policymodel.concepts.AxState; -import org.onap.policy.apex.model.policymodel.concepts.AxTask; -import org.onap.policy.common.utils.resources.ResourceUtils; - -/** - * The Class TestMfpLogic. - */ -public class TestMfpLogic { - - private static final Map LOGICEXTENSIONS = new LinkedHashMap<>(); - - /** - * Test setup. - */ - @BeforeClass - public static void testMfpUseCaseSetup() { - LOGICEXTENSIONS.put("MVEL", "mvel"); - LOGICEXTENSIONS.put("JAVASCRIPT", "js"); - } - - /** - * Check logic for MyFirstPolicy#1. - */ - @Test - public void testMfp1TaskLogic() { - final AxPolicyModel apexPolicyModel = new MfpDomainModelFactory().getMfp1PolicyModel(); - assertNotNull(apexPolicyModel); - - final Map logics = new LinkedHashMap<>(); - logics.putAll(getTslLogics(apexPolicyModel)); - logics.putAll(getTaskLogics(apexPolicyModel)); - - for (final Entry logicvalue : logics.entrySet()) { - final String filename = "examples/models/MyFirstPolicy/1/" + logicvalue.getKey(); - final String logic = logicvalue.getValue(); - final String expectedlogic = ResourceUtils.getResourceAsString(filename); - assertNotNull("File " + filename + " was not found. It should contain logic for PolicyModel " - + apexPolicyModel.getKey(), expectedlogic); - assertEquals( - "The task in " + filename + " is not the same as the relevant logic in PolicyModel " - + apexPolicyModel.getKey(), - expectedlogic.replaceAll("\\s", ""), logic.replaceAll("\\s", "")); - } - } - - - /** - * Check logic for MyFirstPolicyAlt#1. - */ - @Test - public void testMfp1AltTaskLogic() { - final AxPolicyModel apexPolicyModel = new MfpDomainModelFactory().getMfp1AltPolicyModel(); - assertNotNull(apexPolicyModel); - - final Map logics = new LinkedHashMap<>(); - logics.putAll(getTslLogics(apexPolicyModel)); - logics.putAll(getTaskLogics(apexPolicyModel)); - - for (final Entry logicvalue : logics.entrySet()) { - final String filename = "examples/models/MyFirstPolicy/1/" + logicvalue.getKey(); - final String logic = logicvalue.getValue(); - final String expectedlogic = ResourceUtils.getResourceAsString(filename); - assertNotNull("File " + filename + " was not found. It should contain logic for PolicyModel " - + apexPolicyModel.getKey(), expectedlogic); - assertEquals( - "The task in " + filename + " is not the same as the relevant logic in PolicyModel " - + apexPolicyModel.getKey(), - expectedlogic.replaceAll("\\s", ""), logic.replaceAll("\\s", "")); - } - } - - /** - * Check logic for MyFirstPolicy2. - */ - @Test - public void testMfp2TaskLogic() { - final AxPolicyModel apexPolicyModel = new MfpDomainModelFactory().getMfp2PolicyModel(); - assertNotNull(apexPolicyModel); - - final Map logics = new LinkedHashMap<>(); - logics.putAll(getTslLogics(apexPolicyModel)); - logics.putAll(getTaskLogics(apexPolicyModel)); - - for (final Entry logicvalue : logics.entrySet()) { - final String filename = "examples/models/MyFirstPolicy/2/" + logicvalue.getKey(); - final String logic = logicvalue.getValue(); - final String expectedlogic = ResourceUtils.getResourceAsString(filename); - assertNotNull("File " + filename + " was not found. It should contain logic for PolicyModel " - + apexPolicyModel.getKey(), expectedlogic); - assertEquals( - "The task in " + filename + " is not the same as the relevant logic in PolicyModel " - + apexPolicyModel.getKey(), - expectedlogic.replaceAll("\\s", ""), logic.replaceAll("\\s", "")); - } - } - - /** - * Gets the TSL logics. - * - * @param apexPolicyModel the apex policy model - * @return the TSL logics - */ - private Map getTslLogics(final AxPolicyModel apexPolicyModel) { - final Map ret = new LinkedHashMap<>(); - for (final Entry policyentry : apexPolicyModel.getPolicies().getPolicyMap() - .entrySet()) { - for (final Entry statesentry : policyentry.getValue().getStateMap().entrySet()) { - final AxState state = statesentry.getValue(); - final String tsllogic = state.getTaskSelectionLogic().getLogic(); - final String tsllogicflavour = state.getTaskSelectionLogic().getLogicFlavour(); - if (tsllogic != null && tsllogic.trim().length() > 0) { - assertNotNull( - "Logic Type \"" + tsllogicflavour + "\" in state " + statesentry.getKey() + " in policy " - + policyentry.getKey() + " is not supported in this test", - LOGICEXTENSIONS.get(tsllogicflavour.toUpperCase())); - final String filename = policyentry.getKey().getName() + "_" + statesentry.getKey() + "TSL." - + LOGICEXTENSIONS.get(tsllogicflavour.toUpperCase()); - ret.put(filename, tsllogic); - } - } - } - return ret; - } - - /** - * Gets the task logics. - * - * @param apexPolicyModel the apex policy model - * @return the task logics - */ - private Map getTaskLogics(final AxPolicyModel apexPolicyModel) { - final Map ret = new LinkedHashMap<>(); - for (final Entry taskentry : apexPolicyModel.getTasks().getTaskMap().entrySet()) { - final AxTask task = taskentry.getValue(); - final String tasklogic = task.getTaskLogic().getLogic(); - final String tasklogicflavour = task.getTaskLogic().getLogicFlavour(); - assertTrue("No/Blank logic found in task " + taskentry.getKey(), - (tasklogic != null && tasklogic.trim().length() > 0)); - assertNotNull("Logic Type \"" + tasklogicflavour + "\" in task " + taskentry.getKey() - + " is not supported in this test", LOGICEXTENSIONS.get(tasklogicflavour.toUpperCase())); - final String filename = - taskentry.getKey().getName() + "." + LOGICEXTENSIONS.get(tasklogicflavour.toUpperCase()); - ret.put(filename, tasklogic); - } - return ret; - } -} diff --git a/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpModel.java b/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpModel.java deleted file mode 100644 index 808da4866..000000000 --- a/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpModel.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.examples.myfirstpolicy; - -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.sql.Connection; -import java.sql.DriverManager; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; -import org.onap.policy.apex.model.basicmodel.test.TestApexModel; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; - -/** - * Test MyFirstPolicy Model. - * - * @author John Keeney (john.keeney@ericsson.com) - */ -public class TestMfpModel { - - private static Connection connection; - private static TestApexModel testApexModel1; - private static TestApexModel testApexModel2; - - /** - * Setup. - * - * @throws Exception if there is an error - */ - @BeforeClass - public static void setup() throws Exception { - Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance(); - connection = DriverManager.getConnection("jdbc:derby:memory:apex_test;create=true"); - testApexModel1 = new TestApexModel<>(AxPolicyModel.class, new TestMfpModelCreator.TestMfp1ModelCreator()); - testApexModel2 = new TestApexModel<>(AxPolicyModel.class, new TestMfpModelCreator.TestMfp2ModelCreator()); - } - - /** - * Teardown. - * - * @throws Exception if there is an error - */ - @AfterClass - public static void teardown() throws Exception { - connection.close(); - new File("derby.log").delete(); - } - - /** - * Test model is valid. - * - * @throws Exception if there is an error - */ - @Test - public void testModelValid() throws Exception { - AxValidationResult result = testApexModel1.testApexModelValid(); - assertTrue("Model did not validate cleanly", result.isOk()); - - result = testApexModel2.testApexModelValid(); - assertTrue("Model did not validate cleanly", result.isOk()); - } - - /** - * Test model write and read XML. - * - * @throws Exception if there is an error - */ - @Test - public void testModelWriteReadXml() throws Exception { - testApexModel1.testApexModelWriteReadXml(); - testApexModel2.testApexModelWriteReadXml(); - } - - /** - * Test model write and read JSON. - * - * @throws Exception if there is an error - */ - @Test - public void testModelWriteReadJson() throws Exception { - testApexModel1.testApexModelWriteReadJson(); - testApexModel2.testApexModelWriteReadJson(); - } -} diff --git a/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpModelCli.java b/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpModelCli.java deleted file mode 100644 index a63df03bc..000000000 --- a/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpModelCli.java +++ /dev/null @@ -1,96 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.examples.myfirstpolicy; - -import static org.junit.Assert.assertEquals; - -import java.io.File; -import java.io.IOException; - -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.apex.auth.clieditor.ApexCommandLineEditorMain; -import org.onap.policy.apex.model.basicmodel.handling.ApexModelException; -import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; -import org.onap.policy.apex.model.utilities.TextFileUtils; - -/** - * Test MyFirstPolicyModel CLI. - */ -public class TestMfpModelCli { - private static AxPolicyModel testApexModel1; - private static AxPolicyModel testApexModel2; - - /** - * Setup the test. - * - * @throws Exception if there is an error - */ - @BeforeClass - public static void setup() throws Exception { - testApexModel1 = new TestMfpModelCreator.TestMfp1ModelCreator().getModel(); - testApexModel2 = new TestMfpModelCreator.TestMfp2ModelCreator().getModel(); - } - - /** - * Test CLI policy. - * - * @throws IOException Signals that an I/O exception has occurred. - * @throws ApexModelException ifd there is an Apex Error - */ - @Test - public void testCliPolicy() throws IOException, ApexModelException { - - final File tempLogFile1 = File.createTempFile("TestMyFirstPolicy1CLI", ".log"); - final File tempModelFile1 = File.createTempFile("TestMyFirstPolicy1CLI", ".json"); - final File tempLogFile2 = File.createTempFile("TestMyFirstPolicy2CLI", ".log"); - final File tempModelFile2 = File.createTempFile("TestMyFirstPolicy2CLI", ".json"); - final String[] testApexModel1CliArgs = - { "-c", "src/main/resources/examples/models/MyFirstPolicy/1/MyFirstPolicyModel_0.0.1.apex", "-l", - tempLogFile1.getAbsolutePath(), "-o", tempModelFile1.getAbsolutePath() }; - final String[] testApexModel2CliArgs = - { "-c", "src/main/resources/examples/models/MyFirstPolicy/2/MyFirstPolicyModel_0.0.1.apex", "-l", - tempLogFile2.getAbsolutePath(), "-o", tempModelFile2.getAbsolutePath() }; - - new ApexCommandLineEditorMain(testApexModel1CliArgs); - new ApexCommandLineEditorMain(testApexModel2CliArgs); - - final ApexModelReader reader = new ApexModelReader<>(AxPolicyModel.class); - AxPolicyModel generatedmodel = reader.read(TextFileUtils.getTextFileAsString(tempModelFile1.getAbsolutePath())); - - assertEquals("Model generated from the CLI (" + testApexModel1CliArgs[1] + ") into file " - + tempModelFile1.getAbsolutePath() + " is not the same as the test Model for " - + testApexModel1.getKey(), testApexModel1, generatedmodel); - - generatedmodel = reader.read(TextFileUtils.getTextFileAsString(tempModelFile2.getAbsolutePath())); - assertEquals("Model generated from the CLI (" + testApexModel2CliArgs[1] + ") into file " - + tempModelFile2.getAbsolutePath() + " is not the same as the test Model for " - + testApexModel2.getKey(), testApexModel2, generatedmodel); - - tempLogFile1.delete(); - tempModelFile1.delete(); - - tempLogFile2.delete(); - tempModelFile2.delete(); - - } -} diff --git a/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpUseCase.java b/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpUseCase.java deleted file mode 100644 index 8c95c9fec..000000000 --- a/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMfpUseCase.java +++ /dev/null @@ -1,383 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.examples.myfirstpolicy; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import com.google.gson.GsonBuilder; -import com.google.gson.JsonObject; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters; -import org.onap.policy.apex.context.parameters.ContextParameterConstants; -import org.onap.policy.apex.context.parameters.ContextParameters; -import org.onap.policy.apex.context.parameters.SchemaParameters; -import org.onap.policy.apex.core.engine.EngineParameters; -import org.onap.policy.apex.core.engine.engine.impl.ApexEngineFactory; -import org.onap.policy.apex.core.engine.engine.impl.ApexEngineImpl; -import org.onap.policy.apex.core.engine.event.EnEvent; -import org.onap.policy.apex.examples.myfirstpolicy.model.MfpDomainModelFactory; -import org.onap.policy.apex.model.basicmodel.concepts.ApexException; -import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; -import org.onap.policy.apex.model.eventmodel.concepts.AxEvent; -import org.onap.policy.apex.model.eventmodel.concepts.AxField; -import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; -import org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters; -import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters; -import org.onap.policy.common.parameters.ParameterService; -import org.onap.policy.common.utils.resources.ResourceUtils; - -/** - * Test MyFirstPolicy Use Case. - */ -public class TestMfpUseCase { - // CHECKSTYLE:OFF: MagicNumber - - private static ApexEngineImpl apexEngine; - - /** - * Test MFP use case setup. - */ - @BeforeClass - public static void testMfpUseCaseSetup() { - final AxArtifactKey key = new AxArtifactKey("MyFirstPolicyApexEngine", "0.0.1"); - apexEngine = (ApexEngineImpl) new ApexEngineFactory().createApexEngine(key); - } - - private static ContextParameters contextParameters; - private static SchemaParameters schemaParameters; - private static EngineParameters engineParameters; - - /** - * Before test. - */ - @BeforeClass - public static void beforeTest() { - schemaParameters = new SchemaParameters(); - - schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME); - schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters()); - - ParameterService.register(schemaParameters); - - contextParameters = new ContextParameters(); - - contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME); - contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME); - contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME); - contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME); - - ParameterService.register(contextParameters); - ParameterService.register(contextParameters.getDistributorParameters()); - ParameterService.register(contextParameters.getLockManagerParameters()); - ParameterService.register(contextParameters.getPersistorParameters()); - - engineParameters = new EngineParameters(); - engineParameters.getExecutorParameterMap().put("MVEL", new MvelExecutorParameters()); - engineParameters.getExecutorParameterMap().put("JAVASCRIPT", new JavascriptExecutorParameters()); - ParameterService.register(engineParameters); - } - - /** - * After test. - */ - @AfterClass - public static void afterTest() { - ParameterService.deregister(engineParameters); - - ParameterService.deregister(contextParameters.getDistributorParameters()); - ParameterService.deregister(contextParameters.getLockManagerParameters()); - ParameterService.deregister(contextParameters.getPersistorParameters()); - ParameterService.deregister(contextParameters); - - ParameterService.deregister(schemaParameters); - } - - /** - * Test MyFirstPolicy#1 use case. - * - * @throws ApexException if there is an Apex error - * @throws InterruptedException if there is an Interruption. - * @throws IOException Signals that an I/O exception has occurred. - */ - @Test - public void testMfp1Case() throws ApexException, InterruptedException, IOException { - final AxPolicyModel apexPolicyModel = new MfpDomainModelFactory().getMfp1PolicyModel(); - assertNotNull(apexPolicyModel); - - final TestSaleAuthListener listener = new TestSaleAuthListener("Test"); - apexEngine.addEventListener("listener", listener); - apexEngine.updateModel(apexPolicyModel); - apexEngine.start(); - - final AxEvent axEventin = apexPolicyModel.getEvents().get(new AxArtifactKey("SALE_INPUT:0.0.1")); - assertNotNull(axEventin); - final AxEvent axEventout = apexPolicyModel.getEvents().get(new AxArtifactKey("SALE_AUTH:0.0.1")); - assertNotNull(axEventout); - - EnEvent event = fillTriggerEvent(axEventin, "examples/events/MyFirstPolicy/1/EventIn_BoozeItem_084106GMT.json"); - apexEngine.handleEvent(event); - EnEvent resultout = listener.getResult(); - EnEvent resulexpected = - fillResultEvent(axEventout, "examples/events/MyFirstPolicy/1/EventOut_BoozeItem_084106GMT.json"); - assertEquals(resulexpected, resultout); - - event = fillTriggerEvent(axEventin, "examples/events/MyFirstPolicy/1/EventIn_BoozeItem_201713GMT.json"); - apexEngine.handleEvent(event); - resultout = listener.getResult(); - resulexpected = - fillResultEvent(axEventout, "examples/events/MyFirstPolicy/1/EventOut_BoozeItem_201713GMT.json"); - assertEquals(resulexpected, resultout); - assertEquals("ExecutionIDs are different", event.getExecutionId(), resultout.getExecutionId()); - - event = fillTriggerEvent(axEventin, "examples/events/MyFirstPolicy/1/EventIn_NonBoozeItem_101309GMT.json"); - apexEngine.handleEvent(event); - resultout = listener.getResult(); - resulexpected = - fillResultEvent(axEventout, "examples/events/MyFirstPolicy/1/EventOut_NonBoozeItem_101309GMT.json"); - assertEquals(resulexpected, resultout); - assertEquals("ExecutionIDs are different", event.getExecutionId(), resultout.getExecutionId()); - - apexEngine.stop(); - } - - /** - * Test MyFirstPolicy#2 use case. - * - * @throws ApexException if there is an Apex error - * @throws InterruptedException if there is an Interruption. - * @throws IOException Signals that an I/O exception has occurred. - */ - @Test - public void testMfp2Case() throws ApexException, InterruptedException, IOException { - final AxPolicyModel apexPolicyModel = new MfpDomainModelFactory().getMfp2PolicyModel(); - assertNotNull(apexPolicyModel); - - final TestSaleAuthListener listener = new TestSaleAuthListener("Test"); - apexEngine.addEventListener("listener", listener); - apexEngine.updateModel(apexPolicyModel); - apexEngine.start(); - - final AxEvent axEventin = apexPolicyModel.getEvents().get(new AxArtifactKey("SALE_INPUT:0.0.1")); - assertNotNull(axEventin); - final AxEvent axEventout = apexPolicyModel.getEvents().get(new AxArtifactKey("SALE_AUTH:0.0.1")); - assertNotNull(axEventout); - - EnEvent event = fillTriggerEvent(axEventin, "examples/events/MyFirstPolicy/1/EventIn_BoozeItem_084106GMT.json"); - apexEngine.handleEvent(event); - EnEvent resultout = listener.getResult(); - EnEvent resultexpected = - fillResultEvent(axEventout, "examples/events/MyFirstPolicy/1/EventOut_BoozeItem_084106GMT.json"); - assertEquals(resultexpected, resultout); - assertEquals("ExecutionIDs are different", event.getExecutionId(), resultout.getExecutionId()); - - event = fillTriggerEvent(axEventin, "examples/events/MyFirstPolicy/1/EventIn_BoozeItem_201713GMT.json"); - apexEngine.handleEvent(event); - resultout = listener.getResult(); - resultexpected = - fillResultEvent(axEventout, "examples/events/MyFirstPolicy/1/EventOut_BoozeItem_201713GMT.json"); - assertEquals(resultexpected, resultout); - assertEquals("ExecutionIDs are different", event.getExecutionId(), resultout.getExecutionId()); - - event = fillTriggerEvent(axEventin, "examples/events/MyFirstPolicy/1/EventIn_NonBoozeItem_101309GMT.json"); - apexEngine.handleEvent(event); - resultout = listener.getResult(); - resultexpected = - fillResultEvent(axEventout, "examples/events/MyFirstPolicy/1/EventOut_NonBoozeItem_101309GMT.json"); - assertEquals(resultexpected, resultout); - assertEquals("ExecutionIDs are different", event.getExecutionId(), resultout.getExecutionId()); - - event = fillTriggerEvent(axEventin, "examples/events/MyFirstPolicy/2/EventIn_BoozeItem_101433CET_thurs.json"); - apexEngine.handleEvent(event); - resultout = listener.getResult(); - resultexpected = - fillResultEvent(axEventout, "examples/events/MyFirstPolicy/2/EventOut_BoozeItem_101433CET_thurs.json"); - assertEquals(resultexpected, resultout); - assertEquals("ExecutionIDs are different", event.getExecutionId(), resultout.getExecutionId()); - - event = fillTriggerEvent(axEventin, "examples/events/MyFirstPolicy/2/EventIn_BoozeItem_171937CET_sun.json"); - apexEngine.handleEvent(event); - resultout = listener.getResult(); - resultexpected = - fillResultEvent(axEventout, "examples/events/MyFirstPolicy/2/EventOut_BoozeItem_171937CET_sun.json"); - assertEquals(resultexpected, resultout); - assertEquals("ExecutionIDs are different", event.getExecutionId(), resultout.getExecutionId()); - - event = fillTriggerEvent(axEventin, "examples/events/MyFirstPolicy/2/EventIn_NonBoozeItem_111309CET_mon.json"); - apexEngine.handleEvent(event); - resultout = listener.getResult(); - resultexpected = - fillResultEvent(axEventout, "examples/events/MyFirstPolicy/2/EventOut_NonBoozeItem_111309CET_mon.json"); - assertEquals(resultexpected, resultout); - assertEquals("ExecutionIDs are different", event.getExecutionId(), resultout.getExecutionId()); - - apexEngine.stop(); - } - - /** - * Fill trigger event for test. - * - * @param event the event - * @param inputFile the input file - * @return the filled event - */ - private EnEvent fillTriggerEvent(final AxEvent event, final String inputFile) { - final EnEvent ret = new EnEvent(event.getKey()); - final GsonBuilder gb = new GsonBuilder(); - gb.serializeNulls().enableComplexMapKeySerialization(); - final JsonObject jsonObject = - gb.create().fromJson(ResourceUtils.getResourceAsString(inputFile), JsonObject.class); - assertNotNull(jsonObject); - assertTrue(jsonObject.has("name")); - assertTrue(ret.getName().equals(jsonObject.get("name").getAsString())); - assertTrue(ret.getAxEvent().getKey().getName().equals(jsonObject.get("name").getAsString())); - assertTrue(jsonObject.has("nameSpace")); - assertTrue(ret.getAxEvent().getNameSpace().equals(jsonObject.get("nameSpace").getAsString())); - assertTrue(jsonObject.has("version")); - assertTrue(ret.getAxEvent().getKey().getVersion().equals(jsonObject.get("version").getAsString())); - final List reserved = Arrays.asList("name", "nameSpace", "version", "source", "target"); - for (final Map.Entry e : jsonObject.entrySet()) { - if (reserved.contains(e.getKey())) { - continue; - } - assertTrue("Event file " + inputFile + " has a field " + e.getKey() + " but this is not defined for " - + event.getId(), (event.getParameterMap().containsKey(e.getKey()))); - if (jsonObject.get(e.getKey()).isJsonNull()) { - ret.put(e.getKey(), null); - } - } - for (final AxField field : event.getFields()) { - if (!field.getOptional()) { - assertTrue("Event file " + inputFile + " is missing a mandatory field " + field.getKey().getLocalName() - + " for " + event.getId(), jsonObject.has(field.getKey().getLocalName())); - } else { - ret.put(field.getKey().getLocalName(), null); - } - } - if (jsonObject.has("time") && !jsonObject.get("time").isJsonNull()) { - ret.put("time", jsonObject.get("time").getAsLong()); - } - if (jsonObject.has("sale_ID") && !jsonObject.get("sale_ID").isJsonNull()) { - ret.put("sale_ID", jsonObject.get("sale_ID").getAsLong()); - } - if (jsonObject.has("amount") && !jsonObject.get("amount").isJsonNull()) { - ret.put("amount", jsonObject.get("amount").getAsDouble()); - } - if (jsonObject.has("item_ID") && !jsonObject.get("item_ID").isJsonNull()) { - ret.put("item_ID", jsonObject.get("item_ID").getAsLong()); - } - if (jsonObject.has("quantity") && !jsonObject.get("quantity").isJsonNull()) { - ret.put("quantity", jsonObject.get("quantity").getAsInt()); - } - if (jsonObject.has("assistant_ID") && !jsonObject.get("assistant_ID").isJsonNull()) { - ret.put("assistant_ID", jsonObject.get("assistant_ID").getAsLong()); - } - if (jsonObject.has("branch_ID") && !jsonObject.get("branch_ID").isJsonNull()) { - ret.put("branch_ID", jsonObject.get("branch_ID").getAsLong()); - } - if (jsonObject.has("notes") && !jsonObject.get("notes").isJsonNull()) { - ret.put("notes", jsonObject.get("notes").getAsString()); - } - return ret; - } - - /** - * Fill result event for test. - * - * @param event the event - * @param inputFile the input file - * @return the filled event - */ - private EnEvent fillResultEvent(final AxEvent event, final String inputFile) { - final EnEvent ret = new EnEvent(event.getKey()); - final GsonBuilder gb = new GsonBuilder(); - gb.serializeNulls().enableComplexMapKeySerialization(); - final JsonObject jsonObject = - gb.create().fromJson(ResourceUtils.getResourceAsString(inputFile), JsonObject.class); - assertNotNull(jsonObject); - assertTrue(jsonObject.has("name")); - assertTrue(ret.getName().equals(jsonObject.get("name").getAsString())); - assertTrue(ret.getAxEvent().getKey().getName().equals(jsonObject.get("name").getAsString())); - assertTrue(jsonObject.has("nameSpace")); - assertTrue(ret.getAxEvent().getNameSpace().equals(jsonObject.get("nameSpace").getAsString())); - assertTrue(jsonObject.has("version")); - assertTrue(ret.getAxEvent().getKey().getVersion().equals(jsonObject.get("version").getAsString())); - final List reserved = Arrays.asList("name", "nameSpace", "version", "source", "target"); - for (final Map.Entry e : jsonObject.entrySet()) { - if (reserved.contains(e.getKey())) { - continue; - } - assertTrue("Event file " + inputFile + " has a field " + e.getKey() + " but this is not defined for " - + event.getId(), (event.getParameterMap().containsKey(e.getKey()))); - if (jsonObject.get(e.getKey()).isJsonNull()) { - ret.put(e.getKey(), null); - } - } - for (final AxField field : event.getFields()) { - if (!field.getOptional()) { - assertTrue("Event file " + inputFile + " is missing a mandatory field " + field.getKey().getLocalName() - + " for " + event.getId(), jsonObject.has(field.getKey().getLocalName())); - } else { - ret.put(field.getKey().getLocalName(), null); - } - } - if (jsonObject.has("time") && !jsonObject.get("time").isJsonNull()) { - ret.put("time", jsonObject.get("time").getAsLong()); - } - if (jsonObject.has("sale_ID") && !jsonObject.get("sale_ID").isJsonNull()) { - ret.put("sale_ID", jsonObject.get("sale_ID").getAsLong()); - } - if (jsonObject.has("amount") && !jsonObject.get("amount").isJsonNull()) { - ret.put("amount", jsonObject.get("amount").getAsDouble()); - } - if (jsonObject.has("item_ID") && !jsonObject.get("item_ID").isJsonNull()) { - ret.put("item_ID", jsonObject.get("item_ID").getAsLong()); - } - if (jsonObject.has("quantity") && !jsonObject.get("quantity").isJsonNull()) { - ret.put("quantity", jsonObject.get("quantity").getAsInt()); - } - if (jsonObject.has("assistant_ID") && !jsonObject.get("assistant_ID").isJsonNull()) { - ret.put("assistant_ID", jsonObject.get("assistant_ID").getAsLong()); - } - if (jsonObject.has("branch_ID") && !jsonObject.get("branch_ID").isJsonNull()) { - ret.put("branch_ID", jsonObject.get("branch_ID").getAsLong()); - } - if (jsonObject.has("notes") && !jsonObject.get("notes").isJsonNull()) { - ret.put("notes", jsonObject.get("notes").getAsString()); - } - if (jsonObject.has("authorised") && !jsonObject.get("authorised").isJsonNull()) { - ret.put("authorised", jsonObject.get("authorised").getAsString()); - } - if (jsonObject.has("message") && !jsonObject.get("message").isJsonNull()) { - ret.put("message", jsonObject.get("message").getAsString()); - } - return ret; - } -} diff --git a/examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AaiAndGuardSim.java b/examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AaiAndGuardSim.java index bb754d99f..93b587a41 100644 --- a/examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AaiAndGuardSim.java +++ b/examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AaiAndGuardSim.java @@ -39,7 +39,7 @@ public class AaiAndGuardSim { * Instantiates a new aai and guard sim. */ public AaiAndGuardSim() { - final ResourceConfig rc = new ResourceConfig(AaiAndGuardSimEndpoint.class); + final ResourceConfig rc = new ResourceConfig(AaiAndGuardSimEndpointTest.class); server = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc); while (!server.isStarted()) { diff --git a/examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AaiAndGuardSimEndpoint.java b/examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AaiAndGuardSimEndpoint.java deleted file mode 100644 index e36ef4d11..000000000 --- a/examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AaiAndGuardSimEndpoint.java +++ /dev/null @@ -1,183 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2016-2018 Ericsson. 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. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.apex.domains.onap.vcpe; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import com.google.gson.Gson; - -import java.util.Map; -import java.util.Random; - -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.core.Response; - -/** - * The Class AaiAndGuardSimEndpoint. - */ -@Path("/sim") -public class AaiAndGuardSimEndpoint { - - private static int postMessagesReceived = 0; - private static int putMessagesReceived = 0; - private static int statMessagesReceived = 0; - private static int getMessagesReceived = 0; - - /** - * Service get stats. - * - * @return the response - */ - @Path("/pdp/api/Stats") - @GET - public Response serviceGetStats() { - statMessagesReceived++; - return Response.status(200).entity("{\"GET\": " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived - + ",\"POST\": " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build(); - } - - /** - * Service guard post request. - * - * @param jsonString the json string - * @return the response - */ - @Path("/pdp/api/getDecision") - @POST - public Response serviceGuardPostRequest(final String jsonString) { - postMessagesReceived++; - - if (postMessagesReceived % 2 == 0) { - return Response.status(200).entity("{\"decision\": \"PERMIT\", \"details\": \"Decision Permit. OK!\"}") - .build(); - } else { - return Response.status(200).entity("{\"decision\": \"DENY\", \"details\": \"Decision Denied. NOK :-(\"}") - .build(); - } - } - - /** - * Service get event. - * - * @return the response - */ - @Path("/event/GetEvent") - @GET - public Response serviceGetEvent() { - final Random rand = new Random(); - final int nextMatchCase = rand.nextInt(4); - final String nextEventName = "Event0" + rand.nextInt(2) + "00"; - - final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.sample.events\",\n" + "\"name\": \"" - + nextEventName + "\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_" + getMessagesReceived - + "\",\n" + "\"target\": \"apex\",\n" + "\"TestSlogan\": \"Test slogan for External Event0\",\n" - + "\"TestMatchCase\": " + nextMatchCase + ",\n" + "\"TestTimestamp\": " + System.currentTimeMillis() - + ",\n" + "\"TestTemperature\": 9080.866\n" + "}"; - - getMessagesReceived++; - - return Response.status(200).entity(eventString).build(); - } - - /** - * Service get empty event. - * - * @return the response - */ - @Path("/event/GetEmptyEvent") - @GET - public Response serviceGetEmptyEvent() { - return Response.status(200).build(); - } - - /** - * Service get event bad response. - * - * @return the response - */ - @Path("/event/GetEventBadResponse") - @GET - public Response serviceGetEventBadResponse() { - return Response.status(400).build(); - } - - /** - * Service post request. - * - * @param jsonString the json string - * @return the response - */ - @Path("/event/PostEvent") - @POST - public Response servicePostRequest(final String jsonString) { - postMessagesReceived++; - - @SuppressWarnings("unchecked") - final Map jsonMap = new Gson().fromJson(jsonString, Map.class); - assertTrue(jsonMap.containsKey("name")); - assertEquals("0.0.1", jsonMap.get("version")); - assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace")); - assertEquals("Act", jsonMap.get("source")); - assertEquals("Outside", jsonMap.get("target")); - - return Response.status(200).entity("{\"GET\": , " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived - + ",\"POST\": , " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build(); - } - - /** - * Service post request bad response. - * - * @param jsonString the json string - * @return the response - */ - @Path("/event/PostEventBadResponse") - @POST - public Response servicePostRequestBadResponse(final String jsonString) { - return Response.status(400).build(); - } - - /** - * Service put request. - * - * @param jsonString the json string - * @return the response - */ - @Path("/event/PutEvent") - @PUT - public Response servicePutRequest(final String jsonString) { - putMessagesReceived++; - - @SuppressWarnings("unchecked") - final Map jsonMap = new Gson().fromJson(jsonString, Map.class); - assertTrue(jsonMap.containsKey("name")); - assertEquals("0.0.1", jsonMap.get("version")); - assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace")); - assertEquals("Act", jsonMap.get("source")); - assertEquals("Outside", jsonMap.get("target")); - - return Response.status(200).entity("{\"GET\": , " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived - + ",\"POST\": , " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build(); - } -} diff --git a/examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AaiAndGuardSimEndpointTest.java b/examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AaiAndGuardSimEndpointTest.java new file mode 100644 index 000000000..5b9040f95 --- /dev/null +++ b/examples/examples-onap-vcpe/src/test/java/org/onap/policy/apex/domains/onap/vcpe/AaiAndGuardSimEndpointTest.java @@ -0,0 +1,183 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.domains.onap.vcpe; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import com.google.gson.Gson; + +import java.util.Map; +import java.util.Random; + +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.core.Response; + +/** + * The Class AaiAndGuardSimEndpoint. + */ +@Path("/sim") +public class AaiAndGuardSimEndpointTest { + + private static int postMessagesReceived = 0; + private static int putMessagesReceived = 0; + private static int statMessagesReceived = 0; + private static int getMessagesReceived = 0; + + /** + * Service get stats. + * + * @return the response + */ + @Path("/pdp/api/Stats") + @GET + public Response serviceGetStats() { + statMessagesReceived++; + return Response.status(200).entity("{\"GET\": " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived + + ",\"POST\": " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build(); + } + + /** + * Service guard post request. + * + * @param jsonString the json string + * @return the response + */ + @Path("/pdp/api/getDecision") + @POST + public Response serviceGuardPostRequest(final String jsonString) { + postMessagesReceived++; + + if (postMessagesReceived % 2 == 0) { + return Response.status(200).entity("{\"decision\": \"PERMIT\", \"details\": \"Decision Permit. OK!\"}") + .build(); + } else { + return Response.status(200).entity("{\"decision\": \"DENY\", \"details\": \"Decision Denied. NOK :-(\"}") + .build(); + } + } + + /** + * Service get event. + * + * @return the response + */ + @Path("/event/GetEvent") + @GET + public Response serviceGetEvent() { + final Random rand = new Random(); + final int nextMatchCase = rand.nextInt(4); + final String nextEventName = "Event0" + rand.nextInt(2) + "00"; + + final String eventString = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.sample.events\",\n" + "\"name\": \"" + + nextEventName + "\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_" + getMessagesReceived + + "\",\n" + "\"target\": \"apex\",\n" + "\"TestSlogan\": \"Test slogan for External Event0\",\n" + + "\"TestMatchCase\": " + nextMatchCase + ",\n" + "\"TestTimestamp\": " + System.currentTimeMillis() + + ",\n" + "\"TestTemperature\": 9080.866\n" + "}"; + + getMessagesReceived++; + + return Response.status(200).entity(eventString).build(); + } + + /** + * Service get empty event. + * + * @return the response + */ + @Path("/event/GetEmptyEvent") + @GET + public Response serviceGetEmptyEvent() { + return Response.status(200).build(); + } + + /** + * Service get event bad response. + * + * @return the response + */ + @Path("/event/GetEventBadResponse") + @GET + public Response serviceGetEventBadResponse() { + return Response.status(400).build(); + } + + /** + * Service post request. + * + * @param jsonString the json string + * @return the response + */ + @Path("/event/PostEvent") + @POST + public Response servicePostRequest(final String jsonString) { + postMessagesReceived++; + + @SuppressWarnings("unchecked") + final Map jsonMap = new Gson().fromJson(jsonString, Map.class); + assertTrue(jsonMap.containsKey("name")); + assertEquals("0.0.1", jsonMap.get("version")); + assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace")); + assertEquals("Act", jsonMap.get("source")); + assertEquals("Outside", jsonMap.get("target")); + + return Response.status(200).entity("{\"GET\": , " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived + + ",\"POST\": , " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build(); + } + + /** + * Service post request bad response. + * + * @param jsonString the json string + * @return the response + */ + @Path("/event/PostEventBadResponse") + @POST + public Response servicePostRequestBadResponse(final String jsonString) { + return Response.status(400).build(); + } + + /** + * Service put request. + * + * @param jsonString the json string + * @return the response + */ + @Path("/event/PutEvent") + @PUT + public Response servicePutRequest(final String jsonString) { + putMessagesReceived++; + + @SuppressWarnings("unchecked") + final Map jsonMap = new Gson().fromJson(jsonString, Map.class); + assertTrue(jsonMap.containsKey("name")); + assertEquals("0.0.1", jsonMap.get("version")); + assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace")); + assertEquals("Act", jsonMap.get("source")); + assertEquals("Outside", jsonMap.get("target")); + + return Response.status(200).entity("{\"GET\": , " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived + + ",\"POST\": , " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + "}").build(); + } +} -- cgit 1.2.3-korg