From 825ae627d4378c5cc7ab4b7d5f4b4ffefcb7977e Mon Sep 17 00:00:00 2001 From: Dinh Danh Le Date: Wed, 29 Aug 2018 17:21:52 +0100 Subject: Fix checkstyle warnings in examples Change-Id: Iad533f3987792d8713426234f3277c1ef6b72284 Issue-ID: POLICY-1034 Signed-off-by: Dinh Danh Le --- ...yDetectionPolicy_Decide_TaskSelectionLogic.java | 164 +++++++-------- .../adaptive/TestAnomalyDetectionDBWrite.java | 60 ------ .../adaptive/TestAnomalyDetectionDbWrite.java | 63 ++++++ .../adaptive/TestAnomalyDetectionModel.java | 10 +- .../adaptive/TestAnomalyDetectionModelCreator.java | 1 + .../adaptive/TestAnomalyDetectionTSLUseCase.java | 211 ------------------- .../adaptive/TestAnomalyDetectionTslUseCase.java | 211 +++++++++++++++++++ .../examples/adaptive/TestAutoLearnDBWrite.java | 60 ------ .../examples/adaptive/TestAutoLearnDbWrite.java | 64 ++++++ .../apex/examples/adaptive/TestAutoLearnModel.java | 10 +- .../adaptive/TestAutoLearnModelCreator.java | 1 + .../examples/adaptive/TestAutoLearnTSLUseCase.java | 234 --------------------- .../examples/adaptive/TestAutoLearnTslUseCase.java | 234 +++++++++++++++++++++ 13 files changed, 666 insertions(+), 657 deletions(-) delete mode 100644 examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAnomalyDetectionDBWrite.java create 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/TestAnomalyDetectionTSLUseCase.java create 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 create 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/TestAutoLearnTSLUseCase.java create mode 100644 examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAutoLearnTslUseCase.java (limited to 'examples/examples-adaptive/src') diff --git a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AnomalyDetectionPolicy_Decide_TaskSelectionLogic.java b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AnomalyDetectionPolicy_Decide_TaskSelectionLogic.java index a044ad14b..2a654c38e 100644 --- a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AnomalyDetectionPolicy_Decide_TaskSelectionLogic.java +++ b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AnomalyDetectionPolicy_Decide_TaskSelectionLogic.java @@ -47,15 +47,18 @@ public class AnomalyDetectionPolicy_Decide_TaskSelectionLogic { /** * A map to hold the Anomaly degree/levels/probabilities required for each task.
- * If there is no task defined for a calculated anomaly-degree, then the default task is used.
- * The map use (LinkedHashMap) is an insertion-ordered map, so the first interval matching a query is used. + * If there is no task defined for a calculated anomaly-degree, then the default task is + * used.
+ * The map use (LinkedHashMap) is an insertion-ordered map, so the first interval matching a + * query is used. */ // CHECKSTYLE:OFF: checkstyle:magicNumber private static final Map TASK_INTERVALS = new LinkedHashMap<>(); + static { - TASK_INTERVALS.put(new double[] { 0.0, 0.1 }, null); // null will mean default task - TASK_INTERVALS.put(new double[] { 0.25, 0.5 }, "AnomalyDetectionDecideTask1"); - TASK_INTERVALS.put(new double[] { 0.5, 1.01 }, "AnomalyDetectionDecideTask2"); + TASK_INTERVALS.put(new double[] {0.0, 0.1}, null); // null will mean default task + TASK_INTERVALS.put(new double[] {0.25, 0.5}, "AnomalyDetectionDecideTask1"); + TASK_INTERVALS.put(new double[] {0.5, 1.01}, "AnomalyDetectionDecideTask2"); } // CHECKSTYLE:ON: checkstyle:magicNumber @@ -74,8 +77,8 @@ public class AnomalyDetectionPolicy_Decide_TaskSelectionLogic { logger.debug(executor.inFields.toString()); final double now = (Double) (executor.inFields.get("MonitoredValue")); final Integer iteration = (Integer) (executor.inFields.get("Iteration")); - final double[] vals = this.forecastingAndAnomaly(now); // double[forecastedValue, AnomalyScore, - // AnomalyProbability] + // get the double[forecastedValue, AnomalyScore, AnomalyProbability] + final double[] vals = this.forecastingAndAnomaly(now); final double anomalyness = vals[2]; String task = null; for (final Map.Entry i : TASK_INTERVALS.entrySet()) { @@ -103,8 +106,8 @@ public class AnomalyDetectionPolicy_Decide_TaskSelectionLogic { * Anomaly detection and forecast. * * @param value The current value - * @return Null if the function can not be executed correctly, otherwise double[forecastedValue, AnomalyScore, - * AnomalyProbability] + * @return Null if the function can not be executed correctly, otherwise double[forecastedValue, + * AnomalyScore, AnomalyProbability] */ public double[] forecastingAndAnomaly(final double value) { try { @@ -167,7 +170,7 @@ public class AnomalyDetectionPolicy_Decide_TaskSelectionLogic { double anomalyProbability = 0.0; if (anomalyDetection.getAnomalyScores().size() > 30) { // 0.5 - anomalyProbability = gStatsTest(anomalyDetection.getAnomalyScores(), ANOMALY_SENSITIVITY); + anomalyProbability = getStatsTest(anomalyDetection.getAnomalyScores(), ANOMALY_SENSITIVITY); } // CHECKSTYLE:ON: checkstyle:magicNumber @@ -178,16 +181,16 @@ public class AnomalyDetectionPolicy_Decide_TaskSelectionLogic { return null; } - return new double[] { forecastedValue, anomalyScore, anomalyProbability }; + return new double[] {forecastedValue, anomalyScore, anomalyProbability}; } /** - * Is the passed value inside the interval, i.e. (value=interval[0]) + * Is the passed value inside the interval, i.e. (value < interval[1] && value>=interval[0]). * * @param value The value to check * @param interval A 2 element double array describing an interval - * @return true if the value is between interval[0] (inclusive) and interval[1] (exclusive), i.e. (value=interval[0]). Otherwise false; + * @return true if the value is between interval[0] (inclusive) and interval[1] (exclusive), + * i.e. (value < interval[1] && value>=interval[0]). Otherwise false; */ private static boolean checkInterval(final double value, final double[] interval) { if (interval == null || interval.length != 2) { @@ -203,100 +206,89 @@ public class AnomalyDetectionPolicy_Decide_TaskSelectionLogic { * * @param values the values * @param significanceLevel the significance level - * @return the double + * @return the anomaly probability */ - private static double gStatsTest(final List values, final double significanceLevel) { + private static double getStatsTest(final List values, final double significanceLevel) { if (isAllEqual(values)) { return 0.0; } // the targeted value or the last value final double currentV = values.get(values.size() - 1); - Double[] lValuesCopy = values.toArray(new Double[values.size()]); - Arrays.sort(lValuesCopy); // takes ~40% of method time - // if(logger.isDebugEnabled()){ - // logger.debug("values:" + Arrays.toString(lValuesCopy)); - // } + Double[] lvaluesCopy = values.toArray(new Double[values.size()]); + Arrays.sort(lvaluesCopy); // takes ~40% of method time // get mean - double mean = getMean(lValuesCopy); - // get the test value: v - double v = getV(lValuesCopy, mean, true); + double mean = getMean(lvaluesCopy); + // get the test value: val + double val = getV(lvaluesCopy, mean, true); // get the p value for the test value - double pValue = getPValue(lValuesCopy, v, mean); // takes approx 25% of method time - // if(logger.isDebugEnabled()){ - // logger.debug("pValue:" + pValue); - // } + double pvalue = getPValue(lvaluesCopy, val, mean); // takes approx 25% of method time // check the critical level - while (pValue < significanceLevel) { // takes approx 20% of method time + while (pvalue < significanceLevel) { // takes approx 20% of method time // the score value as the anomaly probability - final double score = (significanceLevel - pValue) / significanceLevel; - if (Double.compare(v, currentV) == 0) { + final double score = (significanceLevel - pvalue) / significanceLevel; + if (Double.compare(val, currentV) == 0) { return score; } // do the critical check again for the left values - lValuesCopy = removevalue(lValuesCopy, v); - if (isAllEqual(lValuesCopy)) { + lvaluesCopy = removevalue(lvaluesCopy, val); + if (isAllEqual(lvaluesCopy)) { return 0.0; } - // if(logger.isDebugEnabled()){ - // logger.debug("left values:" + Arrays.toString(lValuesCopy)); - // } - mean = getMean(lValuesCopy); - v = getV(lValuesCopy, mean, true); - pValue = getPValue(lValuesCopy, v, mean); + + mean = getMean(lvaluesCopy); + val = getV(lvaluesCopy, mean, true); + pvalue = getPValue(lvaluesCopy, val, mean); } return 0.0; } /** - * get the test value based on mean from sorted values. + * Get the test value based on mean from sorted values. * - * @param lValues the l values + * @param lvalues the l values * @param mean the mean * @param maxValueOnly : only the max extreme value will be tested * @return the value to be tested */ - private static double getV(final Double[] lValues, final double mean, final boolean maxValueOnly) { - double v = lValues[lValues.length - 1]; + private static double getV(final Double[] lvalues, final double mean, final boolean maxValueOnly) { + double val = lvalues[lvalues.length - 1]; // max value as the extreme value if (maxValueOnly) { - return v; + return val; } // check the extreme side - if ((v - mean) < (mean - lValues[0])) { - v = lValues[0]; + if ((val - mean) < (mean - lvalues[0])) { + val = lvalues[0]; } - return v; + return val; } /** * calculate the P value for the t distribution. * - * @param lValues the l values - * @param v the v + * @param lvalues the l values + * @param val the value * @param mean the mean * @return the p value */ - private static double getPValue(final Double[] lValues, final double v, final double mean) { + private static double getPValue(final Double[] lvalues, final double val, final double mean) { // calculate z value - final double z = FastMath.abs(v - mean) / getStdDev(lValues, mean); - // logger.debug("z: " + z); + final double z = FastMath.abs(val - mean) / getStdDev(lvalues, mean); // calculate T - final double n = lValues.length; + final double n = lvalues.length; final double s = (z * z * n * (2.0 - n)) / (z * z * n - (n - 1.0) * (n - 1.0)); final double t = FastMath.sqrt(s); - // logger.debug("t:" + t); // default p value = 0 - double pValue = 0.0; + double pvalue = 0.0; if (!Double.isNaN(t)) { // t distribution with n-2 degrees of freedom final TDistribution tDist = new TDistribution(n - 2); - pValue = n * (1.0 - tDist.cumulativeProbability(t)); - // set max pValue = 1 - pValue = pValue > 1.0 ? 1.0 : pValue; + pvalue = n * (1.0 - tDist.cumulativeProbability(t)); + // set max pvalue = 1 + pvalue = pvalue > 1.0 ? 1.0 : pvalue; } - // logger.debug("value: "+ v + " , pValue: " + pValue); - return pValue; + return pvalue; } /* @@ -318,52 +310,52 @@ public class AnomalyDetectionPolicy_Decide_TaskSelectionLogic { } /** - * Remove the first occurence of the value v from the array. + * Remove the first occurrence of the value val from the array. * - * @param lValues the l values - * @param v the v + * @param lvalues the l values + * @param val the value * @return the double[] */ - private static Double[] removevalue(final Double[] lValues, final double v) { - for (int i = 0; i < lValues.length; i++) { - if (Double.compare(lValues[i], v) == 0) { - final Double[] ret = new Double[lValues.length - 1]; - System.arraycopy(lValues, 0, ret, 0, i); - System.arraycopy(lValues, i + 1, ret, i, lValues.length - i - 1); + private static Double[] removevalue(final Double[] lvalues, final double val) { + for (int i = 0; i < lvalues.length; i++) { + if (Double.compare(lvalues[i], val) == 0) { + final Double[] ret = new Double[lvalues.length - 1]; + System.arraycopy(lvalues, 0, ret, 0, i); + System.arraycopy(lvalues, i + 1, ret, i, lvalues.length - i - 1); return ret; } } - return lValues; + return lvalues; } /** * get mean value of double list. * - * @param lValues the l values + * @param lvalues the l values * @return the mean */ - private static double getMean(final Double[] lValues) { + private static double getMean(final Double[] lvalues) { double sum = 0.0; - for (final double d : lValues) { + for (final double d : lvalues) { sum += d; } - return sum / lValues.length; + return sum / lvalues.length; } /** * get standard deviation of double list. * - * @param lValues the l values + * @param lvalues the l values * @param mean the mean * @return stddev */ - private static double getStdDev(final Double[] lValues, final double mean) { + private static double getStdDev(final Double[] lvalues, final double mean) { double temp = 0.0; - for (final double d : lValues) { + for (final double d : lvalues) { temp += (mean - d) * (mean - d); } - return FastMath.sqrt(temp / lValues.length); + return FastMath.sqrt(temp / lvalues.length); } /** @@ -383,12 +375,12 @@ public class AnomalyDetectionPolicy_Decide_TaskSelectionLogic { /** * return true if all values are equal. * - * @param lValues the l values + * @param lvalues the l values * @return true, if checks if is all equal */ - private static boolean isAllEqual(final List lValues) { - final double first = lValues.get(0); - for (final Double d : lValues) { + private static boolean isAllEqual(final List lvalues) { + final double first = lvalues.get(0); + for (final Double d : lvalues) { if (Double.compare(d, first) != 0) { return false; } @@ -399,12 +391,12 @@ public class AnomalyDetectionPolicy_Decide_TaskSelectionLogic { /** * return true if all values are equal. * - * @param lValues the l values + * @param lvalues the l values * @return true, if checks if is all equal */ - private static boolean isAllEqual(final Double[] lValues) { - final double first = lValues[0]; - for (final Double d : lValues) { + private static boolean isAllEqual(final Double[] lvalues) { + final double first = lvalues[0]; + for (final Double d : lvalues) { if (Double.compare(d, first) != 0) { return false; } 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 9affa7876..000000000 --- a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAnomalyDetectionDBWrite.java +++ /dev/null @@ -1,60 +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; - - @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/TestAnomalyDetectionDbWrite.java b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAnomalyDetectionDbWrite.java new file mode 100644 index 000000000..8f54bf12f --- /dev/null +++ b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAnomalyDetectionDbWrite.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 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 index 3782f2d88..9e631ef2e 100644 --- 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 @@ -38,6 +38,10 @@ 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(); @@ -59,17 +63,17 @@ public class TestAnomalyDetectionModel { } @Test - public void testModelWriteReadXML() throws Exception { + public void testModelWriteReadXml() throws Exception { testApexModel.testApexModelWriteReadXml(); } @Test - public void testModelWriteReadJSON() throws Exception { + public void testModelWriteReadJson() throws Exception { testApexModel.testApexModelWriteReadJson(); } @Test - public void testModelWriteReadJPA() throws Exception { + public void testModelWriteReadJpa() throws Exception { final DaoParameters DaoParameters = new DaoParameters(); DaoParameters.setPluginClass("org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao"); DaoParameters.setPersistenceUnit("AdaptiveModelsTest"); diff --git a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAnomalyDetectionModelCreator.java b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAnomalyDetectionModelCreator.java index 2b50d69ab..439452cec 100644 --- a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAnomalyDetectionModelCreator.java +++ b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAnomalyDetectionModelCreator.java @@ -25,6 +25,7 @@ import org.onap.policy.apex.model.basicmodel.test.TestApexModelCreator; import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; /** + * The class TestAnomalyDetectionModelCreator. * @author Liam Fallon (liam.fallon@ericsson.com) */ public class TestAnomalyDetectionModelCreator implements TestApexModelCreator { 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 3d3fad973..000000000 --- a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAnomalyDetectionTSLUseCase.java +++ /dev/null @@ -1,211 +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.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 - 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 - 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 - // 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(); - Thread.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 TestAnomalyDetectionTSL_main() 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(); - Thread.sleep(1000); - } - - public static void main(final String[] args) throws ApexException, InterruptedException, IOException { - new TestAnomalyDetectionTSLUseCase().TestAnomalyDetectionTSL_main(); - } -} 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 new file mode 100644 index 000000000..1925a53f5 --- /dev/null +++ b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAnomalyDetectionTslUseCase.java @@ -0,0 +1,211 @@ +/*- + * ============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.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 + 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 + 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 + // 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(); + Thread.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(); + Thread.sleep(1000); + } + + 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 e096105d9..000000000 --- a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAutoLearnDBWrite.java +++ /dev/null @@ -1,60 +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; - - @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/TestAutoLearnDbWrite.java b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAutoLearnDbWrite.java new file mode 100644 index 000000000..d4c1ab193 --- /dev/null +++ b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAutoLearnDbWrite.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 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 index beb7a9c80..9bf7ce57a 100644 --- 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 @@ -38,6 +38,10 @@ 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(); @@ -59,17 +63,17 @@ public class TestAutoLearnModel { } @Test - public void testModelWriteReadXML() throws Exception { + public void testModelWriteReadXml() throws Exception { testApexModel.testApexModelWriteReadXml(); } @Test - public void testModelWriteReadJSON() throws Exception { + public void testModelWriteReadJson() throws Exception { testApexModel.testApexModelWriteReadJson(); } @Test - public void testModelWriteReadJPA() throws Exception { + public void testModelWriteReadJpa() throws Exception { final DaoParameters DaoParameters = new DaoParameters(); DaoParameters.setPluginClass("org.onap.policy.apex.model.basicmodel.dao.impl.DefaultApexDao"); DaoParameters.setPersistenceUnit("AdaptiveModelsTest"); diff --git a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAutoLearnModelCreator.java b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAutoLearnModelCreator.java index 11f1991bf..35d049dc7 100644 --- a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAutoLearnModelCreator.java +++ b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAutoLearnModelCreator.java @@ -25,6 +25,7 @@ import org.onap.policy.apex.model.basicmodel.test.TestApexModelCreator; import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; /** + * The class TestAutoLearnModelCreator. * @author Liam Fallon (liam.fallon@ericsson.com) */ public class TestAutoLearnModelCreator implements TestApexModelCreator { 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 723b56653..000000000 --- a/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAutoLearnTSLUseCase.java +++ /dev/null @@ -1,234 +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.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; - -/** - * 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 - 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 - 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 - // 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(); - Thread.sleep(1); - 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 TestAutoLearnTSL_main() throws ApexException, InterruptedException, IOException { - - final double WANT = 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 MIN = -100; - final double MAX = 100; - - double rval = (((rand.nextGaussian() + 1) / 2) * (MAX - MIN)) + MIN; - 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(WANT - avval); - if (distance < toleranceTileJump) { - rval = (((rand.nextGaussian() + 1) / 2) * (MAX - MIN)) + MIN; - val = rval; - triggerEvent.put("MonitoredValue", val); - LOGGER.info("Iteration " + iteration + ": Average " + avval + " has become closer (" + distance - + ") than " + toleranceTileJump + " to " + WANT + " 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(); - Thread.sleep(1); - } - - apexEngine1.stop(); - Thread.sleep(1000); - - } - - public static void main(final String[] args) throws ApexException, InterruptedException, IOException { - new TestAutoLearnTSLUseCase().TestAutoLearnTSL_main(); - } -} 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 new file mode 100644 index 000000000..ce9a07e16 --- /dev/null +++ b/examples/examples-adaptive/src/test/java/org/onap/policy/apex/examples/adaptive/TestAutoLearnTslUseCase.java @@ -0,0 +1,234 @@ +/*- + * ============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.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; + +/** + * 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 + 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 + 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 + // 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(); + Thread.sleep(1); + 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(); + Thread.sleep(1); + } + + apexEngine1.stop(); + Thread.sleep(1000); + + } + + public static void main(final String[] args) throws ApexException, InterruptedException, IOException { + new TestAutoLearnTslUseCase().testAutoLearnTslMain(); + } +} -- cgit 1.2.3-korg