diff options
author | ramverma <ram.krishna.verma@ericsson.com> | 2018-07-25 17:26:52 +0100 |
---|---|---|
committer | ramverma <ram.krishna.verma@ericsson.com> | 2018-07-25 17:32:29 +0100 |
commit | f8959f5c51e6338b62e23ea503eb86d9c65d7c74 (patch) | |
tree | 7a8afbbf61f7091c30aadfc1cace70fb6e65bff9 /examples/examples-myfirstpolicy/src/test | |
parent | dccf9a9e0758be0a926c94bf1599ee625066100d (diff) |
Renaming examples in apex-pdp
Renaming the examples as per what the documentation expects them.
Otherwise the documents won't work.
Change-Id: Ib9e30bf5a4cec0fec981372e1d9f3a0ee5d60f2f
Issue-ID: POLICY-861
Signed-off-by: ramverma <ram.krishna.verma@ericsson.com>
Diffstat (limited to 'examples/examples-myfirstpolicy/src/test')
8 files changed, 1058 insertions, 0 deletions
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 new file mode 100644 index 000000000..652e228c8 --- /dev/null +++ b/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMFPLogic.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.apex.model.utilities.ResourceUtils; + +/** + * The Class TestMFPLogic. + */ +public class TestMFPLogic { + + private static final Map<String, String> 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<String, String> logics = new LinkedHashMap<>(); + logics.putAll(getTSLLogics(apexPolicyModel)); + logics.putAll(getTaskLogics(apexPolicyModel)); + + for (final Entry<String, String> 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<String, String> logics = new LinkedHashMap<>(); + logics.putAll(getTSLLogics(apexPolicyModel)); + logics.putAll(getTaskLogics(apexPolicyModel)); + + for (final Entry<String, String> 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<String, String> logics = new LinkedHashMap<>(); + logics.putAll(getTSLLogics(apexPolicyModel)); + logics.putAll(getTaskLogics(apexPolicyModel)); + + for (final Entry<String, String> 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<String, String> getTSLLogics(final AxPolicyModel apexPolicyModel) { + final Map<String, String> ret = new LinkedHashMap<>(); + for (final Entry<AxArtifactKey, AxPolicy> policyentry : apexPolicyModel.getPolicies().getPolicyMap() + .entrySet()) { + for (final Entry<String, AxState> 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<String, String> getTaskLogics(final AxPolicyModel apexPolicyModel) { + final Map<String, String> ret = new LinkedHashMap<>(); + for (final Entry<AxArtifactKey, AxTask> 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 new file mode 100644 index 000000000..a8be6c4e4 --- /dev/null +++ b/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMFPModel.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 TestMFPModel { + + private static Connection connection; + private static TestApexModel<AxPolicyModel> testApexModel1; + private static TestApexModel<AxPolicyModel> 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 new file mode 100644 index 000000000..fe9d3a205 --- /dev/null +++ b/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMFPModelCLI.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.ApexCLIEditorMain; +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 ApexCLIEditorMain(testApexModel1CliArgs); + new ApexCLIEditorMain(testApexModel2CliArgs); + + final ApexModelReader<AxPolicyModel> 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/TestMFPModelCreator.java b/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMFPModelCreator.java new file mode 100644 index 000000000..2f51f2851 --- /dev/null +++ b/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMFPModelCreator.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 org.onap.policy.apex.examples.myfirstpolicy.model.MFPDomainModelFactory; +import org.onap.policy.apex.model.basicmodel.test.TestApexModelCreator; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; + +/** + * Create the MyFirstPolicyModel - base class. + * + * @author John Keeney (John.Keeney@ericsson.com) + */ +public abstract class TestMFPModelCreator implements TestApexModelCreator<AxPolicyModel> { + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.test.TestApexModelCreator#getMalstructuredModel() + */ + @Override + public AxPolicyModel getMalstructuredModel() { + return null; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.test.TestApexModelCreator#getObservationModel() + */ + @Override + public AxPolicyModel getObservationModel() { + return null; + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.test.TestApexModelCreator#getWarningModel() + */ + @Override + public AxPolicyModel getWarningModel() { + return getModel(); + } + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.test.TestApexModelCreator#getInvalidModel() + */ + @Override + public AxPolicyModel getInvalidModel() { + return null; + } + + /** + * Create the MyFirstPolicyModel #1. + */ + public static class TestMFP1ModelCreator extends TestMFPModelCreator { + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.handling.ApexModelCreator#getModel() + */ + @Override + public AxPolicyModel getModel() { + return new MFPDomainModelFactory().getMFP1PolicyModel(); + } + } + + /** + * Create the MyFirstPolicyModel#2. + */ + public static class TestMFP2ModelCreator extends TestMFPModelCreator { + + /* + * (non-Javadoc) + * + * @see org.onap.policy.apex.model.basicmodel.handling.ApexModelCreator#getModel() + */ + @Override + public AxPolicyModel getModel() { + return new MFPDomainModelFactory().getMFP2PolicyModel(); + } + } + +} 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 new file mode 100644 index 000000000..194072d99 --- /dev/null +++ b/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestMFPUseCase.java @@ -0,0 +1,331 @@ +/*- + * ============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.BeforeClass; +import org.junit.Test; +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.model.utilities.ResourceUtils; +import org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters; +import org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters; + +/** + * 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"); + final EngineParameters parameters = new EngineParameters(); + parameters.getExecutorParameterMap().put("MVEL", new MVELExecutorParameters()); + parameters.getExecutorParameterMap().put("JAVASCRIPT", new JavascriptExecutorParameters()); + apexEngine = (ApexEngineImpl) new ApexEngineFactory().createApexEngine(key); + } + + /** + * 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 resulexpected = + fillResultEvent(axEventout, "examples/events/MyFirstPolicy/1/EventOut_BoozeItem_084106GMT.json"); + assertEquals(resulexpected, 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(); + 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()); + + event = fillTriggerEvent(axEventin, "examples/events/MyFirstPolicy/2/EventIn_BoozeItem_101433CET_thurs.json"); + apexEngine.handleEvent(event); + resultout = listener.getResult(); + resulexpected = + fillResultEvent(axEventout, "examples/events/MyFirstPolicy/2/EventOut_BoozeItem_101433CET_thurs.json"); + assertEquals(resulexpected, 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(); + resulexpected = + fillResultEvent(axEventout, "examples/events/MyFirstPolicy/2/EventOut_BoozeItem_171937CET_sun.json"); + assertEquals(resulexpected, 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(); + resulexpected = + fillResultEvent(axEventout, "examples/events/MyFirstPolicy/2/EventOut_NonBoozeItem_111309CET_mon.json"); + assertEquals(resulexpected, 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<String> reserved = Arrays.asList("name", "nameSpace", "version", "source", "target"); + for (final Map.Entry<String, ?> 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<String> reserved = Arrays.asList("name", "nameSpace", "version", "source", "target"); + for (final Map.Entry<String, ?> 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/TestSaleAuthListener.java b/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestSaleAuthListener.java new file mode 100644 index 000000000..2dfd1af61 --- /dev/null +++ b/examples/examples-myfirstpolicy/src/test/java/org/onap/policy/apex/examples/myfirstpolicy/TestSaleAuthListener.java @@ -0,0 +1,93 @@ +/*- + * ============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 java.util.ArrayList; +import java.util.List; + +import org.onap.policy.apex.core.engine.engine.EnEventListener; +import org.onap.policy.apex.core.engine.event.EnEvent; +import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities; + +/** + * The listener interface for receiving SaleAuth events. The class that is interested in processing a SaleAuth event + * implements this interface, and the object created with that class is registered with a component using the + * component's <code>addTestApexActionListener</code> method. When the testApexAction event occurs, that object's + * appropriate method is invoked. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public class TestSaleAuthListener implements EnEventListener { + // CHECKSTYLE:OFF: MagicNumber + + private final List<EnEvent> resultEvents = new ArrayList<>(); + + private final String id; + + /** + * Instantiates a new action listener. + * + * @param id the id + */ + public TestSaleAuthListener(final String id) { + this.id = id; + } + + /** + * Gets the result. + * + * @return the result + */ + public EnEvent getResult() { + while (resultEvents.isEmpty()) { + ThreadUtilities.sleep(100); + } + return resultEvents.remove(0); + } + + /* + * (non-Javadoc) + * + * @see + * org.onap.policy.apex.core.engine.engine.EnEventListener#onEnEvent(org.onap.policy.apex.core.engine.event.EnEvent) + */ + @Override + public void onEnEvent(final EnEvent saleauthEvent) { + try { + Thread.sleep(100); + } catch (final InterruptedException e) { + e.printStackTrace(); + } + if (saleauthEvent != null) { + System.out.println("SaleAuth event from engine:" + saleauthEvent.getName()); + resultEvents.add(saleauthEvent); + } + } + + /** + * Gets the id. + * + * @return the id + */ + public String getId() { + return id; + } +} diff --git a/examples/examples-myfirstpolicy/src/test/resources/META-INF/persistence.xml b/examples/examples-myfirstpolicy/src/test/resources/META-INF/persistence.xml new file mode 100644 index 000000000..4dcba14b7 --- /dev/null +++ b/examples/examples-myfirstpolicy/src/test/resources/META-INF/persistence.xml @@ -0,0 +1,69 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ============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========================================================= +--> + +<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0"> + <persistence-unit name="MFPModelTest" transaction-type="RESOURCE_LOCAL"> + <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> + + <class>org.onap.policy.apex.model.basicmodel.dao.converters.CDATAConditioner</class> + <class>org.onap.policy.apex.model.basicmodel.dao.converters.UUID2String</class> + <class>org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey</class> + <class>org.onap.policy.apex.model.basicmodel.concepts.AxConcept</class> + <class>org.onap.policy.apex.model.basicmodel.concepts.AxKeyInfo</class> + <class>org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation</class> + <class>org.onap.policy.apex.model.basicmodel.concepts.AxModel</class> + <class>org.onap.policy.apex.model.basicmodel.concepts.TestEntity</class> + <class>org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema</class> + <class>org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas</class> + <class>org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbum</class> + <class>org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbums</class> + <class>org.onap.policy.apex.model.contextmodel.concepts.AxContextModel</class> + <class>org.onap.policy.apex.model.eventmodel.concepts.AxField</class> + <class>org.onap.policy.apex.model.eventmodel.concepts.AxInputField</class> + <class>org.onap.policy.apex.model.eventmodel.concepts.AxOutputField</class> + <class>org.onap.policy.apex.model.eventmodel.concepts.AxEvent</class> + <class>org.onap.policy.apex.model.eventmodel.concepts.AxEvents</class> + <class>org.onap.policy.apex.model.eventmodel.concepts.AxEventModel</class> + <class>org.onap.policy.apex.model.policymodel.concepts.AxLogic</class> + <class>org.onap.policy.apex.model.policymodel.concepts.AxTaskParameter</class> + <class>org.onap.policy.apex.model.policymodel.concepts.AxTaskLogic</class> + <class>org.onap.policy.apex.model.policymodel.concepts.AxTask</class> + <class>org.onap.policy.apex.model.policymodel.concepts.AxTasks</class> + <class>org.onap.policy.apex.model.policymodel.concepts.AxTaskSelectionLogic</class> + <class>org.onap.policy.apex.model.policymodel.concepts.AxStateFinalizerLogic</class> + <class>org.onap.policy.apex.model.policymodel.concepts.AxStateOutput</class> + <class>org.onap.policy.apex.model.policymodel.concepts.AxStateTaskReference</class> + <class>org.onap.policy.apex.model.policymodel.concepts.AxState</class> + <class>org.onap.policy.apex.model.policymodel.concepts.AxPolicy</class> + <class>org.onap.policy.apex.model.policymodel.concepts.AxPolicies</class> + <class>org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel</class> + + <properties> + <property name="javax.persistence.jdbc.url" value="jdbc:derby:memory:apex_test" /> + <property name="javax.persistence.target-database" value="Derby" /> + <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" /> + + <property name="eclipselink.ddl-generation" value="drop-and-create-tables" /> + <property name="eclipselink.ddl-generation.output-mode" value="database" /> + <property name="eclipselink.logging.level" value="INFO" /> + </properties> + </persistence-unit> +</persistence> diff --git a/examples/examples-myfirstpolicy/src/test/resources/logback-test.xml b/examples/examples-myfirstpolicy/src/test/resources/logback-test.xml new file mode 100644 index 000000000..ea201e0a9 --- /dev/null +++ b/examples/examples-myfirstpolicy/src/test/resources/logback-test.xml @@ -0,0 +1,74 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ============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========================================================= +--> + +<configuration> + <contextName>Apex</contextName> + + <statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener" /> + <property name="LOG_DIR" value="${java.io.tmpdir}/apex_logging/" /> + + <!-- USE FOR STD OUT ONLY --> + <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> + <encoder> + <Pattern>%d %contextName [%t] %level %logger{36} - %msg%n</Pattern> + </encoder> + </appender> + + <root level="INFO"> + <appender-ref ref="STDOUT" /> + </root> + + <logger name="org.infinispan" level="INFO" additivity="false"> + <appender-ref ref="STDOUT" /> + </logger> + + <logger name="org.apache.zookeeper.ClientCnxn" level="OFF" additivity="false"> + <appender-ref ref="STDOUT" /> + </logger> + + <appender name="FILE" class="ch.qos.logback.core.FileAppender"> + <file>${LOG_DIR}/apex.log</file> + <encoder> + <pattern>%d %-5relative [procId=${processId}] [%thread] %-5level + %logger{26} - %msg %n %ex{full}</pattern> + </encoder> + </appender> + + <appender name="CTXT_FILE" class="ch.qos.logback.core.FileAppender"> + <file>${LOG_DIR}/apex_ctxt.log</file> + <encoder> + <pattern>%d %-5relative [procId=${processId}] [%thread] %-5level + %logger{26} - %msg %n %ex{full}</pattern> + </encoder> + </appender> + + <logger name="org.onap.policy.apex.core.context.impl.monitoring" level="TRACE" additivity="false"> + <appender-ref ref="CTXT_FILE" /> + </logger> + + <logger name="org.onap.policy.apex" level="TRACE" additivity="false"> + <appender-ref ref="STDOUT" /> + </logger> + + <logger name="org.onap.policy.apex.core.infrastructure" level="INFO" additivity="false"> + <appender-ref ref="STDOUT" /> + </logger> +</configuration> |