# 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=========================================================
#-------------------------------------------------------------------------------
schema create name=AvroFloat_type flavour=Avro schema=LS
{
- "type" : "double"
+ "type" : "float"
}
LE
var customSet = executor.getContextAlbum("CustomSetAlbum" ).get("CustomSet" );
var customMap = executor.getContextAlbum("CustomMapAlbum" ).get("CustomMap" );
-javaIntegerType = Java.type("java.lang.Integer");
-javaLongType = Java.type("java.lang.Long");
-javaFloatType = Java.type("java.lang.Float");
+javaIntegerType = java.lang.Integer;
+javaLongType = java.lang.Long;
+javaFloatType = java.lang.Float;
-avroBoolean = !avroBoolean;
+avroBoolean = avroBoolean == false;
avroByte = new javaIntegerType(avroByte + 1);
avroShort = new javaIntegerType(avroShort + 1);
avroInteger = new javaIntegerType(avroInteger + 1);
avroFloat = new javaFloatType (avroFloat + 0.99);
avroDouble += 0.99;
avroString = avroString + " added to end of string";
-customBoolean.put("flag", !customBoolean.get("flag"));
+customBoolean.put("flag", customBoolean.get("flag") == false);
customByte .put("byteValue" , customByte .get("byteValue" ) + 1);
customInteger.put("intValue" , customInteger.get("intValue" ) + 1);
customDouble .put("doubleValue", customDouble .get("doubleValue") + 1.0);
executor.outFields.put("CustomSet" , executor.getContextAlbum("CustomSetAlbum" ).get("CustomSet" ));
executor.outFields.put("CustomMap" , executor.getContextAlbum("CustomMapAlbum" ).get("CustomMap" ));
-var returnValueType = Java.type("java.lang.Boolean");
-var returnValue = new returnValueType(true);
+var returnValue = true;
+returnValue;
LE
var customSet = executor.getContextAlbum("CustomSetAlbum" ).get("CustomSet" );
var customMap = executor.getContextAlbum("CustomMapAlbum" ).get("CustomMap" );
-javaBoolean = !javaBoolean;
+javaBoolean = javaBoolean == false;
javaByte += 1;
-javaShortType = Java.type("java.lang.Short");
+javaShortType = java.lang.Short;
javaShort = new javaShortType(javaShort + 1);
javaInteger += 1;
javaLong += 1;
customString .setStringValue(customString .getStringValue() + " added to end of string");
customJLong .setLongValue (customJLong .getIncrementedLongValue());
-customDate0Type = Java.type("org.onap.policy.apex.context.test.concepts.TestContextDateItem");
+customDate0Type = org.onap.policy.apex.context.test.concepts.TestContextDateItem;
customDate0 = new customDate0Type(1499868391);
-customDate1Type = Java.type("org.onap.policy.apex.context.test.concepts.TestContextDateTzItem");
+customDate1Type = org.onap.policy.apex.context.test.concepts.TestContextDateTzItem;
customDate1 = new customDate1Type();
customDate1.setDateValue(customDate0);
-customDate2Type = Java.type("org.onap.policy.apex.context.test.concepts.TestContextDateLocaleItem");
+customDate2Type = org.onap.policy.apex.context.test.concepts.TestContextDateLocaleItem;
customDate2 = new customDate2Type();
customDate2.setDateValue(customDate0);
executor.outFields.put("CustomSet" , executor.getContextAlbum("CustomSetAlbum" ).get("CustomSet" ));
executor.outFields.put("CustomMap" , executor.getContextAlbum("CustomMapAlbum" ).get("CustomMap" ));
-var returnValueType = Java.type("java.lang.Boolean");
-var returnValue = new returnValueType(true);
-
+var returnValue = true;
+returnValue;
LE
policy create name=Test_Policy template=FREEFORM firstState=OnlyState
final int logCharCount = logString.replaceAll(SPACES, EMPTY_STRING).length();
final int modelCharCount = modelString.replaceAll(SPACES, EMPTY_STRING).length();
- assertEquals(25996, logCharCount);
- assertEquals(46162, modelCharCount);
+ assertEquals(25892, logCharCount);
+ assertEquals(46048, modelCharCount);
}
/**
final int logCharCount = logString.replaceAll(SPACES, EMPTY_STRING).length();
final int modelCharCount = modelString.replaceAll(SPACES, EMPTY_STRING).length();
- assertEquals(30154, logCharCount);
- assertEquals(52690, modelCharCount);
+ assertEquals(30068, logCharCount);
+ assertEquals(52596, modelCharCount);
}
import org.onap.policy.apex.context.parameters.SchemaParameters;
import org.onap.policy.apex.model.basicmodel.concepts.AxKey;
import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema;
-import org.onap.policy.apex.model.utilities.typeutils.TypeBuilder;
import org.onap.policy.common.parameters.ParameterService;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;
// For Java, the schema is the Java class canonical path
try {
- setSchemaClass(TypeBuilder.getJavaTypeClass(schema.getSchema()));
- } catch (final IllegalArgumentException e) {
+ setSchemaClass(Class.forName(schema.getSchema()));
+ } catch (final Exception e) {
String resultSting = userKey.getId() + ": class/type " + schema.getSchema() + " for context schema \""
+ schema.getId() + "\" not found.";
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@Override
public void onClose(final WebSocket conn, final int code, final String reason, final boolean remote) {
LOGGER.entry(conn, code, remote);
- LOGGER.debug("A client connection from machine {} closing with code {}.",
- conn.getRemoteSocketAddress().getAddress().getHostAddress(), code);
+ LOGGER.debug("A client connection from machine {} closing with code {}.", super.getAddress(), code);
LOGGER.exit();
}
/*
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* 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=========================================================
*/
var returnValueType = Java.type("java.lang.Boolean");
var returnValue = new returnValueType(true);
-// Load compatibility script for imports etc
+// Load compatibility script for imports etc
load("nashorn:mozilla_compat.js");
importPackage(java.text);
importClass(java.text.SimpleDateFormat);
item_id = executor.inFields.get("item_ID");
-//All times in this script are in GMT/UTC since the policy and events assume time is in GMT.
+//All times in this script are in GMT/UTC since the policy and events assume time is in GMT.
var timenow_gmt = new Date(Number(executor.inFields.get("time")));
var midnight_gmt = new Date(Number(executor.inFields.get("time")));
var itemisalcohol = false;
if(item_id != null && item_id >=1000 && item_id < 2000)
itemisalcohol = true;
-
+
if( itemisalcohol
&& timenow_gmt.getTime() >= midnight_gmt.getTime()
&& timenow_gmt.getTime() < eleven30_gmt.getTime()) {
}
else{
executor.outFields.put("authorised", true);
- executor.outFields.put("message", "Sale authorised by policy task " +
+ executor.outFields.put("message", "Sale authorised by policy task " +
executor.subject.taskName + " for time "+timeformatter.format(timenow_gmt.getTime()));
}
/*
This task checks if a sale request is for an item that is an alcoholic drink.
If the local time is between 00:00:00 GMT and 11:30:00 GMT then the sale is not
-authorised. Otherwise the sale is authorised.
-In this implementation we assume that items with item_ID value between 1000 and
+authorised. Otherwise the sale is authorised.
+In this implementation we assume that items with item_ID value between 1000 and
2000 are all alcoholic drinks :-)
*/
/*
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* 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=========================================================
*/
/*
This task checks if a sale request is for an item that is an alcoholic drink.
If the local time is between 00:00:00 GMT and 11:30:00 GMT then the sale is not
-authorised. Otherwise the sale is authorised.
-In this implementation we assume that items with item_ID value between 1000 and
+authorised. Otherwise the sale is authorised.
+In this implementation we assume that items with item_ID value between 1000 and
2000 are all alcoholic drinks :-)
*/
"version" : "0.0.1"
},
"UUID" : "3351b0f4-cf06-4fa2-8823-edf67bd30223",
- "description" : "This task checks if the sales request is for an item that contains alcohol. \nIf the local time is between 00:00:00 and 11:30:00 then the sale is not authorised. Otherwise the sale is authorised. \nIn this implementation we assume that all items with item_ID values between 1000 and 2000 contain alcohol :-)"
+ "description" : "This task checks if the sales request is for an item that contains alcohol.\nIf the local time is between 00:00:00 and 11:30:00 then the sale is not authorised. Otherwise the sale is authorised.\nIn this implementation we assume that all items with item_ID values between 1000 and 2000 contain alcohol :-)"
}
}, {
"key" : {
"taskLogic" : {
"key" : "TaskLogic",
"logicFlavour" : "JAVASCRIPT",
- "logic" : "/**============LICENSE_START=======================================================*Copyright(C)2016-2018Ericsson.Allrightsreserved.*================================================================================*LicensedundertheApacheLicense,Version2.0(the\"License\");*youmaynotusethisfileexceptincompliancewiththeLicense.*YoumayobtainacopyoftheLicenseat**http://www.apache.org/licenses/LICENSE-2.0**Unlessrequiredbyapplicablelaworagreedtoinwriting,software*distributedundertheLicenseisdistributedonan\"ASIS\"BASIS,*WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.*SeetheLicenseforthespecificlanguagegoverningpermissionsand*limitationsundertheLicense.**SPDX-License-Identifier:Apache-2.0*============LICENSE_END=========================================================*/\nvar returnValueType = Java.type(\"java.lang.Boolean\");\nvar returnValue = new returnValueType(true);\n\n// Load compatibility script for imports etc \nload(\"nashorn:mozilla_compat.js\");\nimportPackage(java.text);\nimportClass(java.text.SimpleDateFormat);\n\nexecutor.logger.info(\"Task Execution: '\"+executor.subject.id+\"'. Input Fields: '\"+executor.inFields+\"'\");\n\nexecutor.outFields.put(\"amount\" , executor.inFields.get(\"amount\"));\nexecutor.outFields.put(\"assistant_ID\", executor.inFields.get(\"assistant_ID\"));\nexecutor.outFields.put(\"notes\" , executor.inFields.get(\"notes\"));\nexecutor.outFields.put(\"quantity\" , executor.inFields.get(\"quantity\"));\nexecutor.outFields.put(\"branch_ID\" , executor.inFields.get(\"branch_ID\"));\nexecutor.outFields.put(\"item_ID\" , executor.inFields.get(\"item_ID\"));\nexecutor.outFields.put(\"time\" , executor.inFields.get(\"time\"));\nexecutor.outFields.put(\"sale_ID\" , executor.inFields.get(\"sale_ID\"));\n\nitem_id = executor.inFields.get(\"item_ID\");\n\n//All times in this script are in GMT/UTC since the policy and events assume time is in GMT. \nvar timenow_gmt = new Date(Number(executor.inFields.get(\"time\")));\n\nvar midnight_gmt = new Date(Number(executor.inFields.get(\"time\")));\nmidnight_gmt.setUTCHours(0,0,0,0);\n\nvar eleven30_gmt = new Date(Number(executor.inFields.get(\"time\")));\neleven30_gmt.setUTCHours(11,30,0,0);\n\nvar timeformatter = new java.text.SimpleDateFormat(\"HH:mm:ss z\");\n\nvar itemisalcohol = false;\nif(item_id != null && item_id >=1000 && item_id < 2000)\n itemisalcohol = true;\n \nif( itemisalcohol\n && timenow_gmt.getTime() >= midnight_gmt.getTime()\n && timenow_gmt.getTime() < eleven30_gmt.getTime()) {\n\n executor.outFields.put(\"authorised\", false);\n executor.outFields.put(\"message\", \"Sale not authorised by policy task \" +\n executor.subject.taskName+ \" for time \" + timeformatter.format(timenow_gmt.getTime()) +\n \". Alcohol can not be sold between \" + timeformatter.format(midnight_gmt.getTime()) +\n \" and \" + timeformatter.format(eleven30_gmt.getTime()));\n}\nelse{\n executor.outFields.put(\"authorised\", true);\n executor.outFields.put(\"message\", \"Sale authorised by policy task \" + \n executor.subject.taskName + \" for time \"+timeformatter.format(timenow_gmt.getTime()));\n}\n\n/*\nThis task checks if a sale request is for an item that is an alcoholic drink.\nIf the local time is between 00:00:00 GMT and 11:30:00 GMT then the sale is not\nauthorised. Otherwise the sale is authorised. \nIn this implementation we assume that items with item_ID value between 1000 and \n2000 are all alcoholic drinks :-)\n*/"
+ "logic" : "/**============LICENSE_START=======================================================*Copyright(C)2016-2018Ericsson.Allrightsreserved.*ModificationsCopyright(C)2020NordixFoundation.*================================================================================*LicensedundertheApacheLicense,Version2.0(the\"License\");*youmaynotusethisfileexceptincompliancewiththeLicense.*YoumayobtainacopyoftheLicenseat**http://www.apache.org/licenses/LICENSE-2.0**Unlessrequiredbyapplicablelaworagreedtoinwriting,software*distributedundertheLicenseisdistributedonan\"ASIS\"BASIS,*WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.*SeetheLicenseforthespecificlanguagegoverningpermissionsand*limitationsundertheLicense.**SPDX-License-Identifier:Apache-2.0*============LICENSE_END=========================================================*/\nvar returnValueType = Java.type(\"java.lang.Boolean\");\nvar returnValue = new returnValueType(true);\n\n// Load compatibility script for imports etc\nload(\"nashorn:mozilla_compat.js\");\nimportPackage(java.text);\nimportClass(java.text.SimpleDateFormat);\n\nexecutor.logger.info(\"Task Execution: '\"+executor.subject.id+\"'. Input Fields: '\"+executor.inFields+\"'\");\n\nexecutor.outFields.put(\"amount\" , executor.inFields.get(\"amount\"));\nexecutor.outFields.put(\"assistant_ID\", executor.inFields.get(\"assistant_ID\"));\nexecutor.outFields.put(\"notes\" , executor.inFields.get(\"notes\"));\nexecutor.outFields.put(\"quantity\" , executor.inFields.get(\"quantity\"));\nexecutor.outFields.put(\"branch_ID\" , executor.inFields.get(\"branch_ID\"));\nexecutor.outFields.put(\"item_ID\" , executor.inFields.get(\"item_ID\"));\nexecutor.outFields.put(\"time\" , executor.inFields.get(\"time\"));\nexecutor.outFields.put(\"sale_ID\" , executor.inFields.get(\"sale_ID\"));\n\nitem_id = executor.inFields.get(\"item_ID\");\n\n//All times in this script are in GMT/UTC since the policy and events assume time is in GMT.\nvar timenow_gmt = new Date(Number(executor.inFields.get(\"time\")));\n\nvar midnight_gmt = new Date(Number(executor.inFields.get(\"time\")));\nmidnight_gmt.setUTCHours(0,0,0,0);\n\nvar eleven30_gmt = new Date(Number(executor.inFields.get(\"time\")));\neleven30_gmt.setUTCHours(11,30,0,0);\n\nvar timeformatter = new java.text.SimpleDateFormat(\"HH:mm:ss z\");\n\nvar itemisalcohol = false;\nif(item_id != null && item_id >=1000 && item_id < 2000)\n itemisalcohol = true;\n\nif( itemisalcohol\n && timenow_gmt.getTime() >= midnight_gmt.getTime()\n && timenow_gmt.getTime() < eleven30_gmt.getTime()) {\n\n executor.outFields.put(\"authorised\", false);\n executor.outFields.put(\"message\", \"Sale not authorised by policy task \" +\n executor.subject.taskName+ \" for time \" + timeformatter.format(timenow_gmt.getTime()) +\n \". Alcohol can not be sold between \" + timeformatter.format(midnight_gmt.getTime()) +\n \" and \" + timeformatter.format(eleven30_gmt.getTime()));\n}\nelse{\n executor.outFields.put(\"authorised\", true);\n executor.outFields.put(\"message\", \"Sale authorised by policy task \" + \n executor.subject.taskName + \" for time \"+timeformatter.format(timenow_gmt.getTime()));\n}\n\n/*\nThis task checks if a sale request is for an item that is an alcoholic drink.\nIf the local time is between 00:00:00 GMT and 11:30:00 GMT then the sale is not\nauthorised. Otherwise the sale is authorised.\nIn this implementation we assume that items with item_ID value between 1000 and\n2000 are all alcoholic drinks :-)\n*/"
}
}
} ]
#-------------------------------------------------------------------------------
# ============LICENSE_START=======================================================
# Copyright (C) 2016-2018 Ericsson. All rights reserved.
+# Modifications Copyright (C) 2020 Nordix Foundation.
# ================================================================================
# 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=========================================================
#-------------------------------------------------------------------------------
schema create name=timestamp_type version=0.0.1 uuid=fd594e88-411d-4a94-b2be-697b3a0d7adf description="A type for 'time' values" flavour=Java schema=java.lang.Long
task create name=MorningBoozeCheck version=0.0.1 uuid=3351b0f4-cf06-4fa2-8823-edf67bd30223 description=LS
-This task checks if the sales request is for an item that contains alcohol.
-If the local time is between 00:00:00 and 11:30:00 then the sale is not authorised. Otherwise the sale is authorised.
+This task checks if the sales request is for an item that contains alcohol.
+If the local time is between 00:00:00 and 11:30:00 then the sale is not authorised. Otherwise the sale is authorised.
In this implementation we assume that all items with item_ID values between 1000 and 2000 contain alcohol :-)
LE
task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
/*
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* 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=========================================================
*/
/*
This task checks if a sale request is for an item that is an alcoholic drink.
If the local time is between 00:00:00 GMT and 11:30:00 GMT then the sale is not
-authorised. Otherwise the sale is authorised.
-In this implementation we assume that items with item_ID value between 1000 and
+authorised. Otherwise the sale is authorised.
+In this implementation we assume that items with item_ID value between 1000 and
2000 are all alcoholic drinks :-)
*/
LE
"version" : "0.0.1"
},
"UUID" : "3351b0f4-cf06-4fa2-8823-edf67bd30223",
- "description" : "This task checks if the sales request is for an item that contains alcohol. \nIf the local time is between 00:00:00 and 11:30:00 then the sale is not authorised. Otherwise the sale is authorised. \nIn this implementation we assume that all items with item_ID values between 1000 and 2000 contain alcohol :-)"
+ "description" : "This task checks if the sales request is for an item that contains alcohol.\nIf the local time is between 00:00:00 and 11:30:00 then the sale is not authorised. Otherwise the sale is authorised.\nIn this implementation we assume that all items with item_ID values between 1000 and 2000 contain alcohol :-)"
}
}, {
"key" : {
"taskLogic" : {
"key" : "TaskLogic",
"logicFlavour" : "MVEL",
- "logic" : "/*\n * ============LICENSE_START=======================================================\n * Copyright (C) 2016-2018 Ericsson. All rights reserved.\n * ================================================================================\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * \n * SPDX-License-Identifier: Apache-2.0\n * ============LICENSE_END=========================================================\n */\nimport java.util.Date;\nimport java.util.Calendar;\nimport java.util.TimeZone;\nimport java.text.SimpleDateFormat;\n\nlogger.info(\"Task Execution: '\"+subject.id+\"'. Input Fields: '\"+inFields+\"'\");\n\noutFields.put(\"amount\" , inFields.get(\"amount\"));\noutFields.put(\"assistant_ID\", inFields.get(\"assistant_ID\"));\noutFields.put(\"notes\" , inFields.get(\"notes\"));\noutFields.put(\"quantity\" , inFields.get(\"quantity\"));\noutFields.put(\"branch_ID\" , inFields.get(\"branch_ID\"));\noutFields.put(\"item_ID\" , inFields.get(\"item_ID\"));\noutFields.put(\"time\" , inFields.get(\"time\"));\noutFields.put(\"sale_ID\" , inFields.get(\"sale_ID\"));\n\nitem_id = inFields.get(\"item_ID\");\n\n//The events used later to test this task use GMT timezone!\ngmt = TimeZone.getTimeZone(\"GMT\");\ntimenow = Calendar.getInstance(gmt);\ndf = new SimpleDateFormat(\"HH:mm:ss z\");\ndf.setTimeZone(gmt);\ntimenow.setTimeInMillis(inFields.get(\"time\"));\n\nmidnight = timenow.clone();\nmidnight.set(\n timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),\n timenow.get(Calendar.DATE),0,0,0);\neleven30 = timenow.clone();\neleven30.set(\n timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),\n timenow.get(Calendar.DATE),11,30,0);\n\nitemisalcohol = false;\nif(item_id != null && item_id >=1000 && item_id < 2000)\n itemisalcohol = true;\n\nif( itemisalcohol\n && timenow.after(midnight) && timenow.before(eleven30)){\n outFields.put(\"authorised\", false);\n outFields.put(\"message\", \"Sale not authorised by policy task \"+subject.taskName+\n \" for time \"+df.format(timenow.getTime())+\n \". Alcohol can not be sold between \"+df.format(midnight.getTime())+\n \" and \"+df.format(eleven30.getTime()));\n return true;\n}\nelse{\n outFields.put(\"authorised\", true);\n outFields.put(\"message\", \"Sale authorised by policy task \"+subject.taskName+\n \" for time \"+df.format(timenow.getTime()));\n return true;\n}\n\n/*\nThis task checks if a sale request is for an item that is an alcoholic drink.\nIf the local time is between 00:00:00 GMT and 11:30:00 GMT then the sale is not\nauthorised. Otherwise the sale is authorised. \nIn this implementation we assume that items with item_ID value between 1000 and \n2000 are all alcoholic drinks :-)\n*/"
+ "logic" : "/*\n * ============LICENSE_START=======================================================\n * Copyright (C) 2016-2018 Ericsson. All rights reserved.\n * Modifications Copyright (C) 2020 Nordix Foundation.\n * ================================================================================\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * SPDX-License-Identifier: Apache-2.0\n * ============LICENSE_END=========================================================\n */\nimport java.util.Date;\nimport java.util.Calendar;\nimport java.util.TimeZone;\nimport java.text.SimpleDateFormat;\n\nlogger.info(\"Task Execution: '\"+subject.id+\"'. Input Fields: '\"+inFields+\"'\");\n\noutFields.put(\"amount\" , inFields.get(\"amount\"));\noutFields.put(\"assistant_ID\", inFields.get(\"assistant_ID\"));\noutFields.put(\"notes\" , inFields.get(\"notes\"));\noutFields.put(\"quantity\" , inFields.get(\"quantity\"));\noutFields.put(\"branch_ID\" , inFields.get(\"branch_ID\"));\noutFields.put(\"item_ID\" , inFields.get(\"item_ID\"));\noutFields.put(\"time\" , inFields.get(\"time\"));\noutFields.put(\"sale_ID\" , inFields.get(\"sale_ID\"));\n\nitem_id = inFields.get(\"item_ID\");\n\n//The events used later to test this task use GMT timezone!\ngmt = TimeZone.getTimeZone(\"GMT\");\ntimenow = Calendar.getInstance(gmt);\ndf = new SimpleDateFormat(\"HH:mm:ss z\");\ndf.setTimeZone(gmt);\ntimenow.setTimeInMillis(inFields.get(\"time\"));\n\nmidnight = timenow.clone();\nmidnight.set(\n timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),\n timenow.get(Calendar.DATE),0,0,0);\neleven30 = timenow.clone();\neleven30.set(\n timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),\n timenow.get(Calendar.DATE),11,30,0);\n\nitemisalcohol = false;\nif(item_id != null && item_id >=1000 && item_id < 2000)\n itemisalcohol = true;\n\nif( itemisalcohol\n && timenow.after(midnight) && timenow.before(eleven30)){\n outFields.put(\"authorised\", false);\n outFields.put(\"message\", \"Sale not authorised by policy task \"+subject.taskName+\n \" for time \"+df.format(timenow.getTime())+\n \". Alcohol can not be sold between \"+df.format(midnight.getTime())+\n \" and \"+df.format(eleven30.getTime()));\n return true;\n}\nelse{\n outFields.put(\"authorised\", true);\n outFields.put(\"message\", \"Sale authorised by policy task \"+subject.taskName+\n \" for time \"+df.format(timenow.getTime()));\n return true;\n}\n\n/*\nThis task checks if a sale request is for an item that is an alcoholic drink.\nIf the local time is between 00:00:00 GMT and 11:30:00 GMT then the sale is not\nauthorised. Otherwise the sale is authorised.\nIn this implementation we assume that items with item_ID value between 1000 and\n2000 are all alcoholic drinks :-)\n*/"
}
}
} ]
/*
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* 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=========================================================
*/
if(item_id != null && item_id >=1000 && item_id < 2000)
itemisalcohol = true;
-if( itemisalcohol
+if( itemisalcohol
&& timenow.after(midnight) && timenow.before(eleven30)){
outFields.put("authorised", false);
outFields.put("message", "Sale not authorised by policy task "+subject.taskName+
/*
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* 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=========================================================
*/
}
/*
-This task checks if a sale request is for an item that is an alcoholic drink.
-If the local time is between 00:00:00 CET and 13:00:00 CET then the sale is not authorised.
-Also alcohol sales are not allowed on Sundays. Otherwise the sale is authorised.
+This task checks if a sale request is for an item that is an alcoholic drink.
+If the local time is between 00:00:00 CET and 13:00:00 CET then the sale is not authorised.
+Also alcohol sales are not allowed on Sundays. Otherwise the sale is authorised.
In this implementation we assume that items with item_ID between 1000 and 2000 are all alcoholic drinks :-)
*/
#-------------------------------------------------------------------------------
# ============LICENSE_START=======================================================
# Copyright (C) 2016-2018 Ericsson. All rights reserved.
+# Modifications Copyright (C) 2020 Nordix Foundation.
# ================================================================================
# 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=========================================================
#-------------------------------------------------------------------------------
schema create name=timestamp_type version=0.0.1 uuid=fd594e88-411d-4a94-b2be-697b3a0d7adf description="A type for 'time' values" flavour=Java schema=java.lang.Long
task create name=MorningBoozeCheck version=0.0.1 uuid=3351b0f4-cf06-4fa2-8823-edf67bd30223 description=LS
-This task checks if the sales request is for an item that contains alcohol.
-If the local time is between 00:00:00 and 11:30:00 then the sale is not authorised. Otherwise the sale is authorised.
+This task checks if the sales request is for an item that contains alcohol.
+If the local time is between 00:00:00 and 11:30:00 then the sale is not authorised. Otherwise the sale is authorised.
In this implementation we assume that all items with item_ID values between 1000 and 2000 contain alcohol :-)
LE
task inputfield create name=MorningBoozeCheck version=0.0.1 fieldName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
/*
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* 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=========================================================
*/
/*
This task checks if a sale request is for an item that is an alcoholic drink.
If the local time is between 00:00:00 GMT and 11:30:00 GMT then the sale is not
-authorised. Otherwise the sale is authorised.
-In this implementation we assume that items with item_ID value between 1000 and
+authorised. Otherwise the sale is authorised.
+In this implementation we assume that items with item_ID value between 1000 and
2000 are all alcoholic drinks :-)
*/
LE
task create name=MorningBoozeCheckAlt1 version=0.0.1 uuid=bc6d90c9-c902-4686-afd3-925b30e39990 description=LS
-This task checks if a sale request is for an item that is an alcoholic drink.
-If the local time is between 00:00:00 CET and 13:00:00 CET then the sale is not authorised.
-Also alcohol sales are not allowed on Sundays. Otherwise the sale is authorised.
+This task checks if a sale request is for an item that is an alcoholic drink.
+If the local time is between 00:00:00 CET and 13:00:00 CET then the sale is not authorised.
+Also alcohol sales are not allowed on Sundays. Otherwise the sale is authorised.
In this implementation we assume that items with item_ID between 1000 and 2000 are all alcoholic drinks
LE
task inputfield create name=MorningBoozeCheckAlt1 version=0.0.1 fieldName=sale_ID schemaName=sale_ID_type schemaVersion=0.0.1
/*
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* 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=========================================================
*/
}
/*
-This task checks if a sale request is for an item that is an alcoholic drink.
-If the local time is between 00:00:00 CET and 13:00:00 CET then the sale is not authorised.
-Also alcohol sales are not allowed on Sundays. Otherwise the sale is authorised.
+This task checks if a sale request is for an item that is an alcoholic drink.
+If the local time is between 00:00:00 CET and 13:00:00 CET then the sale is not authorised.
+Also alcohol sales are not allowed on Sundays. Otherwise the sale is authorised.
In this implementation we assume that items with item_ID between 1000 and 2000 are all alcoholic drinks :-)
*/
LE
/*
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* 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=========================================================
*/
-var returnValueType = Java.type("java.lang.Boolean");
-var returnValue = new returnValueType(true);
+var returnValue = true;
executor.logger.info("Task Selection Execution: '"+executor.subject.id+"'. Input Event: '"+executor.inFields+"'");
/*
This task selection logic selects task "MorningBoozeCheck" for branches with 0<=branch_ID<1000 and selects task "MorningBoozeCheckAlt1" for branches with 1000<=branch_ID<2000. Otherwise the default task is selected. In this case the default task is also "MorningBoozeCheck"
*/
+
+returnValue;
LE
"version" : "0.0.1"
},
"UUID" : "3351b0f4-cf06-4fa2-8823-edf67bd30223",
- "description" : "This task checks if the sales request is for an item that contains alcohol. \nIf the local time is between 00:00:00 and 11:30:00 then the sale is not authorised. Otherwise the sale is authorised. \nIn this implementation we assume that all items with item_ID values between 1000 and 2000 contain alcohol :-)"
+ "description" : "This task checks if the sales request is for an item that contains alcohol.\nIf the local time is between 00:00:00 and 11:30:00 then the sale is not authorised. Otherwise the sale is authorised.\nIn this implementation we assume that all items with item_ID values between 1000 and 2000 contain alcohol :-)"
}
}, {
"key" : {
"version" : "0.0.1"
},
"UUID" : "bc6d90c9-c902-4686-afd3-925b30e39990",
- "description" : "This task checks if a sale request is for an item that is an alcoholic drink. \nIf the local time is between 00:00:00 CET and 13:00:00 CET then the sale is not authorised. \nAlso alcohol sales are not allowed on Sundays. Otherwise the sale is authorised. \nIn this implementation we assume that items with item_ID between 1000 and 2000 are all alcoholic drinks"
+ "description" : "This task checks if a sale request is for an item that is an alcoholic drink.\nIf the local time is between 00:00:00 CET and 13:00:00 CET then the sale is not authorised.\nAlso alcohol sales are not allowed on Sundays. Otherwise the sale is authorised.\nIn this implementation we assume that items with item_ID between 1000 and 2000 are all alcoholic drinks"
}
}, {
"key" : {
"UUID" : "540226fb-55ee-4f0e-a444-983a0494818e",
"description" : "This is my first Apex Policy Model."
}
- }, {
- "key" : {
- "name" : "MyFirstPolicyModel_Albums",
- "version" : "0.0.1"
- },
- "value" : {
- "key" : {
- "name" : "MyFirstPolicyModel_Albums",
- "version" : "0.0.1"
- },
- "UUID" : "3f70ec50-f896-31ba-afec-5fd47e69045b",
- "description" : "Generated description for concept referred to by key \"MyFirstPolicyModel_Albums:0.0.1\""
- }
}, {
"key" : {
"name" : "MyFirstPolicyModel_Events",
"taskSelectionLogic" : {
"key" : "TaskSelectionLogic",
"logicFlavour" : "JAVASCRIPT",
- "logic" : "/* * ============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========================================================= */var returnValueType = Java.type(\"java.lang.Boolean\");\nvar returnValue = new returnValueType(true);\n\nexecutor.logger.info(\"Task Selection Execution: '\"+executor.subject.id+\"'. Input Event: '\"+executor.inFields+\"'\");\n\nbranchid = executor.inFields.get(\"branch_ID\");\ntaskorig = executor.subject.getTaskKey(\"MorningBoozeCheck\");\ntaskalt = executor.subject.getTaskKey(\"MorningBoozeCheckAlt1\");\ntaskdef = executor.subject.getDefaultTaskKey();\n\nif(branchid >=0 && branchid <1000){\n taskorig.copyTo(executor.selectedTask);\n}\nelse if (branchid >=1000 && branchid <2000){\n taskalt.copyTo(executor.selectedTask);\n}\nelse{\n taskdef.copyTo(executor.selectedTask);\n}\n\n/*\nThis task selection logic selects task \"MorningBoozeCheck\" for branches with 0<=branch_ID<1000 and selects task \"MorningBoozeCheckAlt1\" for branches with 1000<=branch_ID<2000. Otherwise the default task is selected. In this case the default task is also \"MorningBoozeCheck\"\n*/"
+ "logic" : "/*\n * ============LICENSE_START=======================================================\n * Copyright (C) 2016-2018 Ericsson. All rights reserved.\n * Modifications Copyright (C) 2020 Nordix Foundation.\n * ================================================================================\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * SPDX-License-Identifier: Apache-2.0\n * ============LICENSE_END=========================================================\n */\n\nvar returnValue = true;\n\nexecutor.logger.info(\"Task Selection Execution: '\"+executor.subject.id+\"'. Input Event: '\"+executor.inFields+\"'\");\n\nbranchid = executor.inFields.get(\"branch_ID\");\ntaskorig = executor.subject.getTaskKey(\"MorningBoozeCheck\");\ntaskalt = executor.subject.getTaskKey(\"MorningBoozeCheckAlt1\");\ntaskdef = executor.subject.getDefaultTaskKey();\n\nif(branchid >=0 && branchid <1000){\n taskorig.copyTo(executor.selectedTask);\n}\nelse if (branchid >=1000 && branchid <2000){\n taskalt.copyTo(executor.selectedTask);\n}\nelse{\n taskdef.copyTo(executor.selectedTask);\n}\n\n/*\nThis task selection logic selects task \"MorningBoozeCheck\" for branches with 0<=branch_ID<1000 and selects task \"MorningBoozeCheckAlt1\" for branches with 1000<=branch_ID<2000. Otherwise the default task is selected. In this case the default task is also \"MorningBoozeCheck\"\n*/\n\nreturnValue;"
},
"stateFinalizerLogicMap" : {
"entry" : [ ]
"taskLogic" : {
"key" : "TaskLogic",
"logicFlavour" : "MVEL",
- "logic" : "/*\n * ============LICENSE_START=======================================================\n * Copyright (C) 2016-2018 Ericsson. All rights reserved.\n * ================================================================================\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * \n * SPDX-License-Identifier: Apache-2.0\n * ============LICENSE_END=========================================================\n */\nimport java.util.Date;\nimport java.util.Calendar;\nimport java.util.TimeZone;\nimport java.text.SimpleDateFormat;\n\nlogger.info(\"Task Execution: '\"+subject.id+\"'. Input Fields: '\"+inFields+\"'\");\n\noutFields.put(\"amount\" , inFields.get(\"amount\"));\noutFields.put(\"assistant_ID\", inFields.get(\"assistant_ID\"));\noutFields.put(\"notes\" , inFields.get(\"notes\"));\noutFields.put(\"quantity\" , inFields.get(\"quantity\"));\noutFields.put(\"branch_ID\" , inFields.get(\"branch_ID\"));\noutFields.put(\"item_ID\" , inFields.get(\"item_ID\"));\noutFields.put(\"time\" , inFields.get(\"time\"));\noutFields.put(\"sale_ID\" , inFields.get(\"sale_ID\"));\n\nitem_id = inFields.get(\"item_ID\");\n\n//The events used later to test this task use GMT timezone!\ngmt = TimeZone.getTimeZone(\"GMT\");\ntimenow = Calendar.getInstance(gmt);\ndf = new SimpleDateFormat(\"HH:mm:ss z\");\ndf.setTimeZone(gmt);\ntimenow.setTimeInMillis(inFields.get(\"time\"));\n\nmidnight = timenow.clone();\nmidnight.set(\n timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),\n timenow.get(Calendar.DATE),0,0,0);\neleven30 = timenow.clone();\neleven30.set(\n timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),\n timenow.get(Calendar.DATE),11,30,0);\n\nitemisalcohol = false;\nif(item_id != null && item_id >=1000 && item_id < 2000)\n itemisalcohol = true;\n\nif( itemisalcohol\n && timenow.after(midnight) && timenow.before(eleven30)){\n outFields.put(\"authorised\", false);\n outFields.put(\"message\", \"Sale not authorised by policy task \"+subject.taskName+\n \" for time \"+df.format(timenow.getTime())+\n \". Alcohol can not be sold between \"+df.format(midnight.getTime())+\n \" and \"+df.format(eleven30.getTime()));\n return true;\n}\nelse{\n outFields.put(\"authorised\", true);\n outFields.put(\"message\", \"Sale authorised by policy task \"+subject.taskName+\n \" for time \"+df.format(timenow.getTime()));\n return true;\n}\n\n/*\nThis task checks if a sale request is for an item that is an alcoholic drink.\nIf the local time is between 00:00:00 GMT and 11:30:00 GMT then the sale is not\nauthorised. Otherwise the sale is authorised. \nIn this implementation we assume that items with item_ID value between 1000 and \n2000 are all alcoholic drinks :-)\n*/"
+ "logic" : "/*\n * ============LICENSE_START=======================================================\n * Copyright (C) 2016-2018 Ericsson. All rights reserved.\n * Modifications Copyright (C) 2020 Nordix Foundation.\n * ================================================================================\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * SPDX-License-Identifier: Apache-2.0\n * ============LICENSE_END=========================================================\n */\nimport java.util.Date;\nimport java.util.Calendar;\nimport java.util.TimeZone;\nimport java.text.SimpleDateFormat;\n\nlogger.info(\"Task Execution: '\"+subject.id+\"'. Input Fields: '\"+inFields+\"'\");\n\noutFields.put(\"amount\" , inFields.get(\"amount\"));\noutFields.put(\"assistant_ID\", inFields.get(\"assistant_ID\"));\noutFields.put(\"notes\" , inFields.get(\"notes\"));\noutFields.put(\"quantity\" , inFields.get(\"quantity\"));\noutFields.put(\"branch_ID\" , inFields.get(\"branch_ID\"));\noutFields.put(\"item_ID\" , inFields.get(\"item_ID\"));\noutFields.put(\"time\" , inFields.get(\"time\"));\noutFields.put(\"sale_ID\" , inFields.get(\"sale_ID\"));\n\nitem_id = inFields.get(\"item_ID\");\n\n//The events used later to test this task use GMT timezone!\ngmt = TimeZone.getTimeZone(\"GMT\");\ntimenow = Calendar.getInstance(gmt);\ndf = new SimpleDateFormat(\"HH:mm:ss z\");\ndf.setTimeZone(gmt);\ntimenow.setTimeInMillis(inFields.get(\"time\"));\n\nmidnight = timenow.clone();\nmidnight.set(\n timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),\n timenow.get(Calendar.DATE),0,0,0);\neleven30 = timenow.clone();\neleven30.set(\n timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),\n timenow.get(Calendar.DATE),11,30,0);\n\nitemisalcohol = false;\nif(item_id != null && item_id >=1000 && item_id < 2000)\n itemisalcohol = true;\n\nif( itemisalcohol\n && timenow.after(midnight) && timenow.before(eleven30)){\n outFields.put(\"authorised\", false);\n outFields.put(\"message\", \"Sale not authorised by policy task \"+subject.taskName+\n \" for time \"+df.format(timenow.getTime())+\n \". Alcohol can not be sold between \"+df.format(midnight.getTime())+\n \" and \"+df.format(eleven30.getTime()));\n return true;\n}\nelse{\n outFields.put(\"authorised\", true);\n outFields.put(\"message\", \"Sale authorised by policy task \"+subject.taskName+\n \" for time \"+df.format(timenow.getTime()));\n return true;\n}\n\n/*\nThis task checks if a sale request is for an item that is an alcoholic drink.\nIf the local time is between 00:00:00 GMT and 11:30:00 GMT then the sale is not\nauthorised. Otherwise the sale is authorised.\nIn this implementation we assume that items with item_ID value between 1000 and\n2000 are all alcoholic drinks :-)\n*/"
}
}
}, {
"taskLogic" : {
"key" : "TaskLogic",
"logicFlavour" : "MVEL",
- "logic" : "/*\n * ============LICENSE_START=======================================================\n * Copyright (C) 2016-2018 Ericsson. All rights reserved.\n * ================================================================================\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * \n * SPDX-License-Identifier: Apache-2.0\n * ============LICENSE_END=========================================================\n */\nimport java.util.Date;\nimport java.util.Calendar;\nimport java.util.TimeZone;\nimport java.text.SimpleDateFormat;\n\nlogger.info(\"Task Execution: '\"+subject.id+\"'. Input Event: '\"+inFields+\"'\");\n\noutFields.put(\"amount\" , inFields.get(\"amount\"));\noutFields.put(\"assistant_ID\", inFields.get(\"assistant_ID\"));\noutFields.put(\"notes\" , inFields.get(\"notes\"));\noutFields.put(\"quantity\" , inFields.get(\"quantity\"));\noutFields.put(\"branch_ID\" , inFields.get(\"branch_ID\"));\noutFields.put(\"item_ID\" , inFields.get(\"item_ID\"));\noutFields.put(\"time\" , inFields.get(\"time\"));\noutFields.put(\"sale_ID\" , inFields.get(\"sale_ID\"));\n\nitem_id = inFields.get(\"item_ID\");\n\n//The events used later to test this task use CET timezone!\ncet = TimeZone.getTimeZone(\"CET\");\ntimenow = Calendar.getInstance(cet);\ndf = new SimpleDateFormat(\"HH:mm:ss z\");\ndf.setTimeZone(cet);\ntimenow.setTimeInMillis(inFields.get(\"time\"));\n\nmidnight = timenow.clone();\nmidnight.set(\n timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),\n timenow.get(Calendar.DATE),0,0,0);\nonepm = timenow.clone();\nonepm.set(\n timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),\n timenow.get(Calendar.DATE),13,0,0);\n\nitemisalcohol = false;\nif(item_id != null && item_id >=1000 && item_id < 2000)\n itemisalcohol = true;\n\nif( itemisalcohol &&\n ( (timenow.after(midnight) && timenow.before(onepm))\n ||\n (timenow.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)\n )){\n outFields.put(\"authorised\", false);\n outFields.put(\"message\", \"Sale not authorised by policy task \"+subject.taskName+\n \" for time \"+df.format(timenow.getTime())+\n \". Alcohol can not be sold between \"+df.format(midnight.getTime())+\n \" and \"+df.format(onepm.getTime()) +\" or on Sunday\");\n return true;\n}\nelse{\n outFields.put(\"authorised\", true);\n outFields.put(\"message\", \"Sale authorised by policy task \"+subject.taskName+\n \" for time \"+df.format(timenow.getTime()));\n return true;\n}\n\n/*\nThis task checks if a sale request is for an item that is an alcoholic drink. \nIf the local time is between 00:00:00 CET and 13:00:00 CET then the sale is not authorised. \nAlso alcohol sales are not allowed on Sundays. Otherwise the sale is authorised. \nIn this implementation we assume that items with item_ID between 1000 and 2000 are all alcoholic drinks :-)\n*/"
+ "logic" : "/*\n * ============LICENSE_START=======================================================\n * Copyright (C) 2016-2018 Ericsson. All rights reserved.\n * Modifications Copyright (C) 2020 Nordix Foundation.\n * ================================================================================\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * SPDX-License-Identifier: Apache-2.0\n * ============LICENSE_END=========================================================\n */\nimport java.util.Date;\nimport java.util.Calendar;\nimport java.util.TimeZone;\nimport java.text.SimpleDateFormat;\n\nlogger.info(\"Task Execution: '\"+subject.id+\"'. Input Event: '\"+inFields+\"'\");\n\noutFields.put(\"amount\" , inFields.get(\"amount\"));\noutFields.put(\"assistant_ID\", inFields.get(\"assistant_ID\"));\noutFields.put(\"notes\" , inFields.get(\"notes\"));\noutFields.put(\"quantity\" , inFields.get(\"quantity\"));\noutFields.put(\"branch_ID\" , inFields.get(\"branch_ID\"));\noutFields.put(\"item_ID\" , inFields.get(\"item_ID\"));\noutFields.put(\"time\" , inFields.get(\"time\"));\noutFields.put(\"sale_ID\" , inFields.get(\"sale_ID\"));\n\nitem_id = inFields.get(\"item_ID\");\n\n//The events used later to test this task use CET timezone!\ncet = TimeZone.getTimeZone(\"CET\");\ntimenow = Calendar.getInstance(cet);\ndf = new SimpleDateFormat(\"HH:mm:ss z\");\ndf.setTimeZone(cet);\ntimenow.setTimeInMillis(inFields.get(\"time\"));\n\nmidnight = timenow.clone();\nmidnight.set(\n timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),\n timenow.get(Calendar.DATE),0,0,0);\nonepm = timenow.clone();\nonepm.set(\n timenow.get(Calendar.YEAR),timenow.get(Calendar.MONTH),\n timenow.get(Calendar.DATE),13,0,0);\n\nitemisalcohol = false;\nif(item_id != null && item_id >=1000 && item_id < 2000)\n itemisalcohol = true;\n\nif( itemisalcohol &&\n ( (timenow.after(midnight) && timenow.before(onepm))\n ||\n (timenow.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)\n )){\n outFields.put(\"authorised\", false);\n outFields.put(\"message\", \"Sale not authorised by policy task \"+subject.taskName+\n \" for time \"+df.format(timenow.getTime())+\n \". Alcohol can not be sold between \"+df.format(midnight.getTime())+\n \" and \"+df.format(onepm.getTime()) +\" or on Sunday\");\n return true;\n}\nelse{\n outFields.put(\"authorised\", true);\n outFields.put(\"message\", \"Sale authorised by policy task \"+subject.taskName+\n \" for time \"+df.format(timenow.getTime()));\n return true;\n}\n\n/*\nThis task checks if a sale request is for an item that is an alcoholic drink.\nIf the local time is between 00:00:00 CET and 13:00:00 CET then the sale is not authorised.\nAlso alcohol sales are not allowed on Sundays. Otherwise the sale is authorised.\nIn this implementation we assume that items with item_ID between 1000 and 2000 are all alcoholic drinks :-)\n*/"
}
}
} ]
} ]
}
},
- "albums" : {
- "key" : {
- "name" : "MyFirstPolicyModel_Albums",
- "version" : "0.0.1"
- },
- "albums" : {
- "entry" : [ ]
- }
- },
"schemas" : {
"key" : {
"name" : "MyFirstPolicyModel_Schemas",
/*
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* 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=========================================================
*/
-
-var returnValueType = Java.type("java.lang.Boolean");
-var returnValue = new returnValueType(true);
+var returnValue = true;
executor.logger.info("Task Selection Execution: '"+executor.subject.id+
"'. Input Event: '"+executor.inFields+"'");
}
/*
-This task selection logic selects task "MorningBoozeCheck" for branches with
-0<=branch_ID<1000 and selects task "MorningBoozeCheckAlt1" for branches with
-1000<=branch_ID<2000. Otherwise the default task is selected.
+This task selection logic selects task "MorningBoozeCheck" for branches with
+0<=branch_ID<1000 and selects task "MorningBoozeCheckAlt1" for branches with
+1000<=branch_ID<2000. Otherwise the default task is selected.
In this case the default task is also "MorningBoozeCheck"
*/
+
+returnValue;
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
}
}
-
/**
* Check logic for MyFirstPolicyAlt#1.
*/
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 filename = "examples/models/MyFirstPolicy/2/" + logicvalue.getKey();
final String expectedlogic = ResourceUtils.getResourceAsString(filename);
assertNotNull("File " + filename + " was not found. It should contain logic for PolicyModel "
+ apexPolicyModel.getKey(), expectedlogic);
+ tempModelFile1.getAbsolutePath() + " is not the same as the test Model for "
+ testApexModel1.getKey(), testApexModel1, generatedmodel);
+ tempLogFile1.delete();
+ tempModelFile1.delete();
+
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();
</dependency>
</dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.antlr</groupId>
- <artifactId>antlr4-maven-plugin</artifactId>
- <version>4.7.1</version>
- <executions>
- <execution>
- <id>antlr-sources</id>
- <phase>generate-sources</phase>
- <goals>
- <goal>antlr4</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
-
<profiles>
<profile>
<id>apexSite</id>
+++ /dev/null
-//-------------------------------------------------------------------------------
-// ============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=========================================================
-//-------------------------------------------------------------------------------
-
-grammar ParametrizedType;
-
-@header {
-/*
- * ============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=========================================================
- */
-}
-
-type returns[ClassBuilder value]
- : cls=CLASS { $value = ClassBuilder.parse($cls.text); }
- | cls=CLASS { $value = ClassBuilder.parse($cls.text); }
- LT head=type { $value.add($head.value); }
- (COMMA tail=type { $value.add($tail.value); })* GT
- ;
-
-GT : '>'
- ;
-
-LT : '<'
- ;
-
-COMMA
- : ','
- ;
-
-CLASS
- : ('a'..'z'|'A'..'Z') ('a'..'z'|'A'..'Z'|'0'..'9'|'$'|'.'|'_')*
- ;
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2016-2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2020 Nordix Foundation.
- * ================================================================================
- * 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.model.utilities.typeutils;
-
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.slf4j.ext.XLogger;
-import org.slf4j.ext.XLoggerFactory;
-
-/**
- * This class is a utility class that builds a class with a set of user defined fields. It is used to get the Type of
- * fields in Java schemas<br> For more information see:<br> <a
- * href="http://stackoverflow.com/questions/39401083/class-forname-equivalent-for-creating-parameterizedtypes-from-string">
- * http://stackoverflow.com/questions/39401083/class-forname-equivalent-for-creating-parameterizedtypes-from-string</a><br>
- * <a href="https://github.com/KetothXupack/stackoverflow-answers/tree/master/q39401083">
- * https://github.com/KetothXupack/stackoverflow-answers/tree/master/q39401083</a><br>
- */
-public class ClassBuilder {
- // Logger for this class
- private static final XLogger LOGGER = XLoggerFactory.getXLogger(ClassBuilder.class);
-
- private final Class<?> clazz;
- private final List<ClassBuilder> parameters = new ArrayList<>();
-
- /**
- * Constructor that sets the class for the class builder.
- *
- * @param clazz the class of the class builder
- */
- public ClassBuilder(final Class<?> clazz) {
- this.clazz = clazz;
- }
-
- /**
- * Creates a {@link ClassBuilder} instance for a class with the given class name.
- *
- * @param className the class name of the class builder to create
- * @return the class builder that is created
- */
- public static ClassBuilder parse(final String className) {
- try {
- return new ClassBuilder(Class.forName(className));
- } catch (ClassNotFoundException e) {
- try {
- return new ClassBuilder(Class.forName("java.lang." + className));
- } catch (Exception classFindException) {
- LOGGER.warn("class not found", classFindException);
- throw new IllegalArgumentException("Class '" + className
- + "' not found. Also looked for a class called 'java.lang." + className + "'", e);
- }
- }
- }
-
- /**
- * Adds a field to the class builder. Each field is itself a class builder.
- *
- * @param fieldBuilder the class builder for the field
- */
- public void add(final ClassBuilder fieldBuilder) {
- parameters.add(fieldBuilder);
- }
-
- /**
- * Builds the {@link Type} of the class.
- *
- * @return the {@link Type} of the class
- */
- public Type build() {
- // class is not parameterized
- if (parameters.isEmpty()) {
- return clazz;
- }
- Type[] paramTypes = new Type[parameters.size()];
- int paramTypeIndex = 0;
- for (ClassBuilder classBuilder : parameters) {
- paramTypes[paramTypeIndex++] = classBuilder.build();
- }
- // TODO: Fix this for parameterized types if needed or adapt to work with generic types only
- // return ParameterizedTypeImpl.make(clazz, paramTypes, null);
- return null;
- }
-}
+++ /dev/null
-/*
- * ============LICENSE_START=======================================================
- * Copyright (C) 2016-2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 Nordix Foundation.
- * ================================================================================
- * 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.model.utilities.typeutils;
-
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-
-import org.antlr.v4.runtime.BailErrorStrategy;
-import org.antlr.v4.runtime.CharStream;
-import org.antlr.v4.runtime.CharStreams;
-import org.antlr.v4.runtime.CommonTokenStream;
-import org.antlr.v4.runtime.TokenStream;
-
-/**
- * This class builds a type from a grammar using ANTLR.
- */
-public final class TypeBuilder {
- /**
- * Private constructor used to prevent sub class instantiation.
- */
- private TypeBuilder() {
- }
-
- /**
- * Builds the Type of the Type string that was input.
- *
- * @param type the java Type as a string
- * @return the Type of the string that was input
- */
- public static Type build(final String type) {
- if (type == null || type.length() == 0) {
- throw new IllegalArgumentException(
- "Blank type string passed to " + TypeBuilder.class.getName() + ".build(String type)");
- }
-
- try {
- final CharStream stream = CharStreams.fromString(type);
- final TokenStream tokenStream = new CommonTokenStream(new ParametrizedTypeLexer(stream));
-
- final ParametrizedTypeParser parser = new ParametrizedTypeParser(tokenStream);
- parser.removeErrorListeners();
- parser.setErrorHandler(new BailErrorStrategy());
- parser.setBuildParseTree(true);
- return parser.type().value.build();
- } catch (final Exception e) {
- throw new IllegalArgumentException("Failed to build type '" + type + "': " + e, e);
- }
- }
-
- /**
- * Gets the class of Java Type.
- *
- * @param type the java Type as a string
- * @return the java Type
- */
- public static Class<?> getJavaTypeClass(final String type) {
- return getJavaTypeClass(build(type));
- }
-
- /**
- * Gets the class of Java Type.
- *
- * @param type the java Type as a Type
- * @return the java Type
- */
- public static Class<?> getJavaTypeClass(final Type type) {
- if (type instanceof Class<?>) {
- return (Class<?>) type;
- } else if (type instanceof ParameterizedType) {
- final Type raw = ((ParameterizedType) type).getRawType();
- if (!(raw instanceof Class<?>)) {
- throw new IllegalArgumentException("The Parameterised javatype " + type + " with base type " + raw
- + " is not a Java 'Class' that can be instantiated");
- }
- return (Class<?>) raw;
- }
- throw new IllegalArgumentException(
- "The Parameterised javatype " + type + " is not a Java 'Type' that has a 'Class'");
- }
-
- /**
- * Gets the parameters of a Java Type.
- *
- * @param type the Java Type
- * @return the parameters of the java Type
- */
- public static Type[] getJavaTypeParameters(final Type type) {
- if (type instanceof Class<?>) {
- return new Type[0];
- } else if (type instanceof ParameterizedType) {
- return ((ParameterizedType) type).getActualTypeArguments();
- }
- throw new IllegalArgumentException(
- "\"The Parameterised javatype \" + type + \" is not a Java 'Type' that has parameter types");
- }
-}
+++ /dev/null
-/*
- * ============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=========================================================
- */
-
-/**
- * Provides utility classes that operate on and work with Java Types.
- *
- * @author Liam Fallon (liam.fallon@ericsson.com)
- */
-package org.onap.policy.apex.model.utilities.typeutils;
/*
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* 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.model.utilities.typeutils;
+package org.onap.policy.apex.model.utilities;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Test key comparisons.
+ *
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
public class KeyComparerTest {
@Test
public void test() {
KeyDifference<String> keyDifference = new KeyComparer<String>().compareKeys("Hello", "Goodbye");
-
+
assertFalse(keyDifference.isEqual());
assertTrue("Hello".equals(keyDifference.getLeftKey().toString()));
assertTrue("Goodbye".equals(keyDifference.getRightKey().toString()));
assertTrue("left key Hello and right key Goodbye differ\n".equals(keyDifference.asString(true)));
assertTrue("left key Hello and right key Goodbye differ\n".equals(keyDifference.asString(false)));
-
+
KeyDifference<String> keyDifference2 = new KeyComparer<String>().compareKeys("Here", "Here");
assertTrue("".equals(keyDifference2.asString(true)));
assertTrue("left key Here equals right key Here\n".equals(keyDifference2.asString(false)));
/*
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* 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.model.utilities.typeutils;
+package org.onap.policy.apex.model.utilities;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Test key map comparisons.
- *
+ *
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
public class KeyedMapComparerTest {
rightMap.put("F", "FFFFF");
rightMap.put("G", "G");
- KeyedMapDifference<String, String> kmComparedSame = new KeyedMapComparer<String, String>().compareMaps(leftMap,
- leftMap);
- KeyedMapDifference<String, String> kmComparedDiff = new KeyedMapComparer<String, String>().compareMaps(leftMap,
- rightMap);
+ KeyedMapDifference<String, String> kmComparedSame =
+ new KeyedMapComparer<String, String>().compareMaps(leftMap, leftMap);
+ KeyedMapDifference<String, String> kmComparedDiff =
+ new KeyedMapComparer<String, String>().compareMaps(leftMap, rightMap);
assertTrue(kmComparedSame.getIdenticalValues().equals(leftMap));
assertEquals(1, kmComparedDiff.getLeftOnly().size());
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2016-2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2020 Nordix Foundation.
- * ================================================================================
- * 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.model.utilities.typeutils;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-
-import java.lang.reflect.Type;
-
-import org.antlr.v4.runtime.BailErrorStrategy;
-import org.antlr.v4.runtime.CharStream;
-import org.antlr.v4.runtime.CharStreams;
-import org.antlr.v4.runtime.CommonTokenStream;
-import org.antlr.v4.runtime.TokenStream;
-import org.junit.Ignore;
-import org.junit.Test;
-
-/**
- * Test Java parsing.
- */
-public class ParserTest {
- // TODO: Fix this test based on the decision around prameterized vs generic types
- @Ignore
- @Test
- public void testParser() {
- final CharStream stream = CharStreams
- .fromString("java.util.Map<java.util.List<java.lang.Integer>,java.util.Set<java.lang.String>>");
- final TokenStream tokenStream = new CommonTokenStream(new ParametrizedTypeLexer(stream));
-
- final ParametrizedTypeParser parser = new ParametrizedTypeParser(tokenStream);
- parser.removeErrorListeners();
- parser.setErrorHandler(new BailErrorStrategy());
- parser.setBuildParseTree(true);
- assertEquals("java.util.Map<java.util.List<java.lang.Integer>, java.util.Set<java.lang.String>>",
- parser.type().value.build().getTypeName());
-
- }
-
- // TODO: Fix this test based on the decision around prameterized vs generic types
- @Ignore
- @Test
- public void testBuilder() throws IllegalArgumentException {
- String typeString = "java.lang.Integer";
- Type ret = TypeBuilder.build(typeString);
- assertEquals(java.lang.Integer.class, TypeBuilder.getJavaTypeClass(ret));
-
- typeString = "java.util.Map<java.util.List<java.lang.Integer>,java.util.Set<java.lang.String>>";
- ret = TypeBuilder.build(typeString);
- assertEquals("java.util.Map<java.util.List<java.lang.Integer>, java.util.Set<java.lang.String>>",
- ret.getTypeName());
- assertEquals(java.util.Map.class, TypeBuilder.getJavaTypeClass(ret));
-
- final Type[] args = TypeBuilder.getJavaTypeParameters(ret);
- assertEquals("java.util.List<java.lang.Integer>", args[0].getTypeName());
- assertEquals("java.util.Set<java.lang.String>", args[1].getTypeName());
- }
-
- @Test
- public void testBoundaryConditions() {
- try {
- TypeBuilder.build(null);
- fail("Test should throw exception");
- } catch (final IllegalArgumentException e) {
- assertEquals(
- "Blank type string passed to "
- + "org.onap.policy.apex.model.utilities.typeutils.TypeBuilder.build(String type)",
- e.getMessage());
- }
-
- try {
- TypeBuilder.build("org.zooby.Wooby");
- fail("Test should throw exception");
- } catch (final IllegalArgumentException e) {
- assertEquals(e.getMessage(),
- "Failed to build type 'org.zooby.Wooby': java.lang.IllegalArgumentException: "
- + "Class 'org.zooby.Wooby' not found. "
- + "Also looked for a class called 'java.lang.org.zooby.Wooby'");
- }
-
- assertEquals(TypeBuilder.getJavaTypeClass("java.lang.String"), String.class);
- }
-}
+++ /dev/null
-/*-
- * ============LICENSE_START=======================================================
- * Copyright (C) 2016-2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2020 Nordix Foundation.
- * ================================================================================
- * 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.plugins.context.schema.avro;
-
-import static org.junit.Assert.assertEquals;
-
-import java.io.IOException;
-
-import org.apache.avro.generic.GenericRecord;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.onap.policy.apex.context.SchemaHelper;
-import org.onap.policy.apex.context.impl.schema.SchemaHelperFactory;
-import org.onap.policy.apex.context.parameters.ContextParameterConstants;
-import org.onap.policy.apex.context.parameters.SchemaParameters;
-import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
-import org.onap.policy.apex.model.basicmodel.concepts.AxKey;
-import org.onap.policy.apex.model.basicmodel.service.ModelService;
-import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema;
-import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas;
-import org.onap.policy.common.parameters.ParameterService;
-import org.onap.policy.common.utils.resources.TextFileUtils;
-
-/**
- * The Class TestAvroSchemaUnion.
- *
- * @author Liam Fallon (liam.fallon@ericsson.com)
- * @version
- */
-public class AvroSchemaUnionTest {
- private final AxKey testKey = new AxArtifactKey("AvroTest", "0.0.1");
- private AxContextSchemas schemas;
- private String uinionSchema;
-
- /**
- * Inits the test.
- *
- * @throws IOException Signals that an I/O exception has occurred.
- */
- @Before
- public void initTest() throws IOException {
- schemas = new AxContextSchemas(new AxArtifactKey("AvroSchemas", "0.0.1"));
- ModelService.registerModel(AxContextSchemas.class, schemas);
- uinionSchema = TextFileUtils.getTextFileAsString("src/test/resources/avsc/UnionExample.avsc");
- }
-
- /**
- * Inits the context.
- */
- @Before
- public void initContext() {
- SchemaParameters schemaParameters = new SchemaParameters();
- schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME);
- schemaParameters.getSchemaHelperParameterMap().put("AVRO", new AvroSchemaHelperParameters());
- ParameterService.register(schemaParameters);
-
- }
-
- /**
- * Clear context.
- */
- @After
- public void clearContext() {
- ParameterService.deregister(ContextParameterConstants.SCHEMA_GROUP_NAME);
- }
-
- /**
- * Test union all fields.
- *
- * @throws IOException Signals that an I/O exception has occurred.
- */
- @Ignore
- @Test
- public void testUnionAllFields() throws IOException {
- final AxContextSchema avroSchema =
- new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", uinionSchema);
-
- schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema);
- final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey());
-
- final String inString = TextFileUtils.getTextFileAsString("src/test/resources/data/UnionExampleAllFields.json");
- final GenericRecord user = (GenericRecord) schemaHelper.createNewInstance(inString);
-
- assertEquals("Ben", user.get("name").toString());
- assertEquals(7, user.get("favourite_number"));
- assertEquals("red", user.get("favourite_colour").toString());
- }
-
- /**
- * Test union optional field.
- *
- * @throws IOException Signals that an I/O exception has occurred.
- */
- @Ignore
- @Test
- public void testUnionOptionalField() throws IOException {
- final AxContextSchema avroSchema =
- new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", uinionSchema);
-
- schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema);
- final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey());
-
- final String inString =
- TextFileUtils.getTextFileAsString("src/test/resources/data/UnionExampleOptionalField.json");
- final GenericRecord user = (GenericRecord) schemaHelper.createNewInstance(inString);
-
- assertEquals("Ben", user.get("name").toString());
- assertEquals(7, user.get("favourite_number"));
- assertEquals("red", user.get("favourite_colour").toString());
- }
-
- /**
- * Test union null field.
- *
- * @throws IOException Signals that an I/O exception has occurred.
- */
- @Ignore
- @Test
- public void testUnionNullField() throws IOException {
- final AxContextSchema avroSchema =
- new AxContextSchema(new AxArtifactKey("AvroRecord", "0.0.1"), "AVRO", uinionSchema);
-
- schemas.getSchemasMap().put(avroSchema.getKey(), avroSchema);
- final SchemaHelper schemaHelper = new SchemaHelperFactory().createSchemaHelper(testKey, avroSchema.getKey());
-
- final String inString = TextFileUtils.getTextFileAsString("src/test/resources/data/UnionExampleNullField.json");
- final GenericRecord user = (GenericRecord) schemaHelper.createNewInstance(inString);
-
- assertEquals("Ben", user.get("name").toString());
- assertEquals(7, user.get("favourite_number"));
- assertEquals("red", user.get("favourite_colour").toString());
- }
-}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
private static int deleteMessagesReceived = 0;
private static String EVENT_STRING = "{\n" + "\"nameSpace\": \"org.onap.policy.apex.events\",\n"
- + "\"name\": \"ResponseEvent\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_"
- + getMessagesReceived + "\",\n" + "\"target\": \"apex\",\n" + "\"intPar\": 9080\n" + "}";
+ + "\"name\": \"ResponseEvent\",\n" + "\"version\": \"0.0.1\",\n" + "\"source\": \"REST_"
+ + getMessagesReceived + "\",\n" + "\"target\": \"apex\",\n" + "\"intPar\": 9080\n" + "}";
/**
* Reset counters.
statMessagesReceived++;
}
return Response.status(200)
- .entity("{\"GET\": " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived
- + ",\"POST\": " + postMessagesReceived + ",\"PUT\": " + putMessagesReceived
- + ",\"DELETE\": " + deleteMessagesReceived + "}")
- .build();
+ .entity("{\"GET\": " + getMessagesReceived + ",\"STAT\": " + statMessagesReceived + ",\"POST\": "
+ + postMessagesReceived + ",\"PUT\": " + putMessagesReceived + ",\"DELETE\": "
+ + deleteMessagesReceived + "}")
+ .build();
}
/**
final Map<String, Object> jsonMap = new Gson().fromJson(jsonString, Map.class);
assertTrue(jsonMap.containsKey("name"));
assertEquals("0.0.1", jsonMap.get("version"));
- assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace"));
- assertEquals("Act", jsonMap.get("source"));
- assertEquals("Outside", jsonMap.get("target"));
+ assertEquals("org.onap.policy.apex.events", jsonMap.get("nameSpace"));
+ assertEquals("apex", jsonMap.get("source"));
+ assertEquals("server", jsonMap.get("target"));
return Response.status(200).entity(EVENT_STRING).build();
}
final Map<String, Object> jsonMap = new Gson().fromJson(jsonString, Map.class);
assertTrue(jsonMap.containsKey("name"));
assertEquals("0.0.1", jsonMap.get("version"));
- assertEquals("org.onap.policy.apex.sample.events", jsonMap.get("nameSpace"));
- assertEquals("Act", jsonMap.get("source"));
- assertEquals("Outside", jsonMap.get("target"));
+ assertEquals("org.onap.policy.apex.events", jsonMap.get("nameSpace"));
+ assertEquals("apex", jsonMap.get("source"));
+ assertEquals("server", jsonMap.get("target"));
return Response.status(200).entity(EVENT_STRING).build();
}
"taskLogic" : {
"key" : "TaskLogic",
"logicFlavour" : "JAVASCRIPT",
- "logic" : "executor.logger.debug(executor.subject.getId());\nvar gc = executor.getContextAlbum(\"BasicContextAlbum\");\nexecutor.logger.debug(gc.getName());\nvar returnValue = executor.isTrue;"
+ "logic" : "executor.logger.debug(executor.subject.getId());\nvar gc = executor.getContextAlbum(\"BasicContextAlbum\");\nexecutor.logger.debug(gc.getName());\ntrue;"
}
}
} ]
<dependencies>
<dependency>
- <groupId>org.graalvm.sdk</groupId>
- <artifactId>graal-sdk</artifactId>
- <version>${graalvm.version}</version>
- </dependency>
- <dependency>
- <groupId>org.graalvm.truffle</groupId>
- <artifactId>truffle-api</artifactId>
- <version>${graalvm.version}</version>
- </dependency>
- <dependency>
- <groupId>org.graalvm.js</groupId>
- <artifactId>js</artifactId>
- <version>${graalvm.version}</version>
+ <groupId>org.mozilla</groupId>
+ <artifactId>rhino</artifactId>
+ <version>1.7.12</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
package org.onap.policy.apex.plugins.executor.javascript;
-import org.graalvm.polyglot.Context;
-import org.graalvm.polyglot.HostAccess;
-import org.graalvm.polyglot.Value;
+import org.apache.commons.lang3.StringUtils;
+import org.mozilla.javascript.Context;
+import org.mozilla.javascript.Script;
+import org.mozilla.javascript.Scriptable;
import org.onap.policy.apex.core.engine.executor.exception.StateMachineException;
import org.onap.policy.apex.model.basicmodel.concepts.AxKey;
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
public class JavascriptExecutor {
+ public static final int DEFAULT_OPTIMIZATION_LEVEL = 9;
+
+ // Recurring string constants
+ private static final String WITH_MESSAGE = " with message: ";
+
// The key of the subject that wants to execute Javascript code
final AxKey subjectKey;
- // The Javascript context
- private final Context jsContext;
+ private Context javascriptContext;
+ private Script script;
/**
- * Prepares the executor for processing.
+ * Initializes the Javascripe executor.
*
* @param subjectKey the key of the subject that is requesting Javascript execution
- * @throws StateMachineException thrown when instantiation of the executor fails
*/
- public JavascriptExecutor(final AxKey subjectKey) throws StateMachineException {
+ public JavascriptExecutor(final AxKey subjectKey) {
this.subjectKey = subjectKey;
+ }
- // @formatter:off
- jsContext =
- Context.newBuilder("js")
- .allowHostClassLookup(s -> true)
- .allowHostAccess(HostAccess.ALL)
- .build();
- // @formatter:on
+ /**
+ * Prepares the executor for processing and compiles the Javascript code.
+ *
+ * @param javascriptCode the Javascript code to execute
+ * @throws StateMachineException thrown when instantiation of the executor fails
+ */
+ public void init(final String javascriptCode) throws StateMachineException {
+ if (StringUtils.isEmpty(javascriptCode)) {
+ throw new StateMachineException("no logic specified for " + subjectKey.getId());
+ }
try {
- jsContext.getBindings("js");
+ // Create a Javascript context for this thread
+ javascriptContext = Context.enter();
+
+ // Set up the default values of the context
+ javascriptContext.setOptimizationLevel(DEFAULT_OPTIMIZATION_LEVEL);
+ javascriptContext.setLanguageVersion(Context.VERSION_1_8);
+
+ script = javascriptContext.compileString(javascriptCode, subjectKey.getId(), 1, null);
} catch (Exception e) {
- jsContext.close();
+ Context.exit();
throw new StateMachineException(
- "prepare: javascript engine failed to initialize properly for \"" + subjectKey.getId() + "\"", e);
+ "logic failed to compile for " + subjectKey.getId() + WITH_MESSAGE + e.getMessage(), e);
}
}
* Executes the the Javascript code.
*
* @param executionContext the execution context of the subject to be passed to the Javascript context
- * @param javascriptCode the Javascript code to execute
* @return true if the Javascript executed properly
* @throws StateMachineException thrown when Javascript execution fails
*/
- public boolean execute(final Object executionContext, final String javascriptCode) throws StateMachineException {
+ public boolean execute(final Object executionContext) throws StateMachineException {
+ Object returnObject = null;
+
try {
- // Set up the Javascript engine context
- jsContext.getBindings("js").putMember("executor", executionContext);
- jsContext.eval("js", javascriptCode);
+ // Pass the subject context to the Javascript engine
+ Scriptable javascriptScope = javascriptContext.initStandardObjects();
+ javascriptScope.put("executor", javascriptScope, executionContext);
+ // Run the script
+ returnObject = script.exec(javascriptContext, javascriptScope);
} catch (final Exception e) {
- throw new StateMachineException("execute: logic failed to run for \"" + subjectKey.getId() + "\"", e);
+ throw new StateMachineException(
+ "logic failed to run for " + subjectKey.getId() + WITH_MESSAGE + e.getMessage(), e);
}
- Value returnValue = jsContext.getBindings("js").getMember("returnValue");
-
- if (returnValue == null || returnValue.isNull()) {
+ if (!(returnObject instanceof Boolean)) {
throw new StateMachineException(
- "execute: logic failed to set a return value for \"" + subjectKey.getId() + "\"");
+ "execute: logic for " + subjectKey.getId() + " returned a non-boolean value " + returnObject);
}
- return returnValue.asBoolean();
+ return (boolean) returnObject;
}
/**
*/
public void cleanUp() throws StateMachineException {
try {
- jsContext.close();
+ Context.exit();
} catch (final Exception e) {
- throw new StateMachineException(
- "cleanUp: executor cleanup failed to close for \"" + subjectKey.getId() + "\"", e);
+ throw new StateMachineException("cleanUp: executor cleanup failed to close for " + subjectKey.getId()
+ + WITH_MESSAGE + e.getMessage(), e);
}
}
}
// Call generic prepare logic
super.prepare();
+ // Create the executor
javascriptExecutor = new JavascriptExecutor(getSubject().getKey());
+
+ // Initialize and cleanup the executor to check the Javascript code
+ javascriptExecutor.init(getSubject().getLogic());
+ javascriptExecutor.cleanUp();
}
/**
// Do execution pre work
executePre(executionId, executionProperties, incomingFields);
- // Execute the Javascript and do post processing
- executePost(javascriptExecutor.execute(getExecutionContext(), getSubject().getLogic()));
+ // Execute the Javascript executor
+ javascriptExecutor.init(getSubject().getLogic());
+ boolean result = javascriptExecutor.execute(getExecutionContext());
+ javascriptExecutor.cleanUp();
+
+ // Execute the Javascript
+ executePost(result);
return getOutgoing();
}
public void cleanUp() throws StateMachineException {
LOGGER.debug("cleanUp:" + getSubject().getKey().getId() + "," + getSubject().getLogicFlavour() + ","
+ getSubject().getLogic());
-
- javascriptExecutor.cleanUp();
}
}
// Call generic prepare logic
super.prepare();
+ // Create the executor
javascriptExecutor = new JavascriptExecutor(getSubject().getKey());
+
+ // Initialize and cleanup the executor to check the Javascript code
+ javascriptExecutor.init(getSubject().getTaskLogic().getLogic());
+ javascriptExecutor.cleanUp();
}
/**
@Override
public Map<String, Object> execute(final long executionId, final Properties executionProperties,
final Map<String, Object> incomingFields) throws StateMachineException, ContextException {
+
// Do execution pre work
executePre(executionId, executionProperties, incomingFields);
- // Execute the Javascript and do post processing
- executePost(javascriptExecutor.execute(getExecutionContext(), getSubject().getTaskLogic().getLogic()));
+ // Execute the Javascript executor
+ javascriptExecutor.init(getSubject().getTaskLogic().getLogic());
+ boolean result = javascriptExecutor.execute(getExecutionContext());
+ javascriptExecutor.cleanUp();
+
+ // Execute the Javascript
+ executePost(result);
return getOutgoing();
}
public void cleanUp() throws StateMachineException {
LOGGER.debug("cleanUp:" + getSubject().getKey().getId() + "," + getSubject().getTaskLogic().getLogicFlavour()
+ "," + getSubject().getTaskLogic().getLogic());
-
- javascriptExecutor.cleanUp();
}
}
// Call generic prepare logic
super.prepare();
+ // Create the executor
javascriptExecutor = new JavascriptExecutor(getSubject().getKey());
+
+ // Initialize and cleanup the executor to check the Javascript code
+ javascriptExecutor.init(getSubject().getTaskSelectionLogic().getLogic());
}
/**
// Do execution pre work
executePre(executionId, executionProperties, incomingEvent);
- // Execute the Javascript and do post processing
- executePost(javascriptExecutor.execute(getExecutionContext(), getSubject().getTaskSelectionLogic().getLogic()));
+ // Execute the Javascript executor
+ javascriptExecutor.init(getSubject().getTaskSelectionLogic().getLogic());
+ boolean result = javascriptExecutor.execute(getExecutionContext());
+ javascriptExecutor.cleanUp();
+
+ // Execute the Javascript
+ executePost(result);
return getOutgoing();
}
LOGGER.debug("cleanUp:" + getSubject().getKey().getId() + ","
+ getSubject().getTaskSelectionLogic().getLogicFlavour() + ","
+ getSubject().getTaskSelectionLogic().getLogic());
-
- javascriptExecutor.cleanUp();
}
}
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
import java.util.HashMap;
import java.util.Map;
jsfe.setContext(parentStateExcutor, stateFinalizerLogic, internalContext);
stateFinalizerLogic.setLogic("return false");
- jsfe.prepare();
+ assertThatThrownBy(() -> {
+ jsfe.prepare();
+ }).hasMessage("logic failed to compile for NULL:0.0.0:NULL:NULL "
+ + "with message: invalid return (NULL:0.0.0:NULL:NULL#1)");
Map<String, Object> incomingParameters1 = new HashMap<>();
assertThatThrownBy(() -> {
jsfe.execute(-1, new Properties(), incomingParameters1);
- fail("test should throw an exception here");
- }).hasMessage("execute: logic failed to run for \"NULL:0.0.0:NULL:NULL\"");
+ }).hasMessage("logic failed to compile for NULL:0.0.0:NULL:NULL "
+ + "with message: invalid return (NULL:0.0.0:NULL:NULL#1)");
stateFinalizerLogic.setLogic("java.lang.String");
jsfe.prepare();
AxEvent axEvent = new AxEvent(new AxArtifactKey("Event", "0.0.1"));
EnEvent event = new EnEvent(axEvent);
- stateFinalizerLogic.setLogic(
- "if(executor.executionId==-1)" + "{\r\n" + "var returnValueType = Java.type(\"java.lang.Boolean\");"
- + "var returnValue = new returnValueType(false); }\n" + "else{\n"
- + "executor.setSelectedStateOutputName(\"SelectedOutputIsMe\");\n"
- + "var returnValueType = Java.type(\"java.lang.Boolean\");\n" + "\n"
- + "var returnValue = new returnValueType(true);}");
+ stateFinalizerLogic.setLogic("if(executor.executionId==-1)" + "{\r\n"
+ + "var returnValueType = java.lang.Boolean;" + "var returnValue = new returnValueType(false); }\n"
+ + "else{\n" + "executor.setSelectedStateOutputName(\"SelectedOutputIsMe\");\n"
+ + "var returnValueType = java.lang.Boolean;\n" + "\n"
+ + "var returnValue = new returnValueType(true);} true;");
assertThatThrownBy(() -> {
jsfe.prepare();
jsfe.execute(-1, new Properties(), event);
- }).hasMessage("execute-post: state finalizer logic execution failure on state \"NULL:0.0.0:NULL:NULL\" "
- + "on finalizer logic NULL:0.0.0:NULL:NULL");
+ }).hasMessage("execute-post: state finalizer logic \"NULL:0.0.0:NULL:NULL\" did not select an output state");
state.getStateOutputs().put("SelectedOutputIsMe", null);
jte.prepare();
}).isInstanceOf(NullPointerException.class);
- AxTask task = new AxTask();
+ AxTask task = new AxTask(new AxArtifactKey("TestTask:0.0.1"));
final ApexInternalContext internalContext = new ApexInternalContext(new AxPolicyModel());
jte.setContext(null, task, internalContext);
task.getTaskLogic().setLogic("return boolean;");
- jte.prepare();
- Map<String, Object> incomingParameters2 = new HashMap<>();
assertThatThrownBy(() -> {
- jte.execute(-1, new Properties(), incomingParameters2);
- }).hasMessage("execute: logic failed to run for \"NULL:0.0.0\"");
+ jte.prepare();
+ jte.execute(-1, new Properties(), null);
+ }).hasMessage("logic failed to compile for TestTask:0.0.1 with message: invalid return (TestTask:0.0.1#1)");
task.getTaskLogic().setLogic("var x = 5;");
- jte.prepare();
+ jte.prepare();
assertThatThrownBy(() -> {
jte.execute(-1, new Properties(), null);
}).isInstanceOf(NullPointerException.class);
+ jte.cleanUp();
- Map<String, Object> incomingParameters = new HashMap<>();
- assertThatThrownBy(() -> {
- jte.execute(-1, new Properties(), incomingParameters);
- }).hasMessage("execute: logic failed to set a return value for \"NULL:0.0.0\"");
+ task.getTaskLogic().setLogic("var returnValue = false;\nreturnValue;");
- task.getTaskLogic().setLogic("var returnValueType = Java.type(\"java.lang.Boolean\");\n"
- + "var returnValue = new returnValueType(false); ");
+ Map<String, Object> incomingParameters = new HashMap<>();
assertThatThrownBy(() -> {
jte.prepare();
jte.execute(-1, new Properties(), incomingParameters);
- }).hasMessage("execute-post: task logic execution failure on task \"NULL\" in model NULL:0.0.0");
+ }).hasMessage("execute-post: task logic execution failure on task \"TestTask\" in model NULL:0.0.0");
- task.getTaskLogic().setLogic("var returnValueType = Java.type(\"java.lang.Boolean\");\r\n"
- + "var returnValue = new returnValueType(true); ");
+ jte.cleanUp();
+
+ task.getTaskLogic().setLogic("var returnValue = true;\nreturnValue;");
jte.prepare();
Map<String, Object> returnMap = jte.execute(0, new Properties(), incomingParameters);
jte.prepare();
jte.execute(-1, new Properties(), incomingParameters);
+ jte.cleanUp();
task.getTaskLogic().setLogic(TextFileUtils.getTextFileAsString("src/test/resources/javascript/TestLogic01.js"));
jte.prepare();
Map<String, Object> outcomingParameters = jte.execute(-1, new Properties(), incomingParameters);
+ jte.cleanUp();
assertEquals("returnVal0", outcomingParameters.get("par0"));
assertEquals("returnVal1", outcomingParameters.get("par1"));
AxState state = new AxState();
ApexInternalContext internalContext = new ApexInternalContext(new AxPolicyModel());
jtse.setContext(null, state, internalContext);
- jtse.prepare();
+
+ assertThatThrownBy(() -> {
+ jtse.prepare();
+ }).hasMessage("no logic specified for NULL:0.0.0:NULL:NULL");
AxEvent axEvent1 = new AxEvent(new AxArtifactKey("Event", "0.0.1"));
EnEvent event1 = new EnEvent(axEvent1);
assertThatThrownBy(() -> {
jtse.execute(-1, new Properties(), event1);
- }).hasMessage("execute: logic failed to set a return value for \"NULL:0.0.0:NULL:NULL\"");
+ }).hasMessage("no logic specified for NULL:0.0.0:NULL:NULL");
state.getTaskSelectionLogic().setLogic("java.lang.String");
jtse.prepare();
assertThatThrownBy(() -> {
jtse.execute(-1, new Properties(), event);
- }).hasMessage("execute: logic failed to set a return value for \"NULL:0.0.0:NULL:NULL\"");
+ }).hasMessage(
+ "execute: logic for NULL:0.0.0:NULL:NULL returned a non-boolean value [JavaClass java.lang.String]");
- state.getTaskSelectionLogic().setLogic("var returnValueType = Java.type(\"java.lang.Boolean\");\r\n"
- + "var returnValue = new returnValueType(false); ");
+ state.getTaskSelectionLogic().setLogic("var x=1;\n" + "false; ");
assertThatThrownBy(() -> {
jtse.prepare();
jtse.execute(-1, new Properties(), event);
}).hasMessage("execute-post: task selection logic failed on state \"NULL:0.0.0:NULL:NULL\"");
- state.getTaskSelectionLogic().setLogic("var returnValueType = Java.type(\"java.lang.Boolean\");\r\n"
- + "var returnValue = new returnValueType(true); ");
+ state.getTaskSelectionLogic().setLogic("var x = 1\n" + "true; ");
jtse.prepare();
AxArtifactKey taskKey = jtse.execute(0, new Properties(), event);
executor.logger.info("outgoing value: " + executor.outFields.get("intPar").toString());
-var returnValue = executor.isTrue;
\ No newline at end of file
+executor.isTrue;
\ No newline at end of file
*/
var x = 1;
var returnValue = true;
+
+returnValue;
\ No newline at end of file
executor.logger.info(executor.outFields.get("par0"));
executor.logger.info(executor.outFields.get("par1"));
-var returnValue = executor.isTrue;
+true;
"taskLogic" : {
"key" : "TaskLogic",
"logicFlavour" : "JAVASCRIPT",
- "logic" : "executor.logger.debug(executor.subject.getId());\nvar gc = executor.getContextAlbum(\"BasicContextAlbum\");\nexecutor.logger.debug(gc.getName());\nexecutor.logger.debug(\"incoming value: \" + executor.inFields.get(\"intPar\").toString());\n\nvar intPar = executor.inFields.get(\"intPar\");\n\nexecutor.logger.debug(\"read value: \" + intPar.toString());\n\nvar intParBy2 = intPar * 2;\n\nexecutor.outFields.put(\"intPar\", intParBy2);\n\nexecutor.logger.debug(\"outgoing value: \" + executor.outFields.get(\"intPar\").toString());\n\nvar returnValue = executor.isTrue;"
+ "logic" : "executor.logger.debug(executor.subject.getId());\nvar gc = executor.getContextAlbum(\"BasicContextAlbum\");\nexecutor.logger.debug(gc.getName());\nexecutor.logger.debug(\"incoming value: \" + executor.inFields.get(\"intPar\").toString());\n\nvar intPar = executor.inFields.get(\"intPar\");\n\nexecutor.logger.debug(\"read value: \" + intPar.toString());\n\nvar intParBy2 = intPar * 2;\n\nexecutor.outFields.put(\"intPar\", intParBy2);\n\nexecutor.logger.debug(\"outgoing value: \" + executor.outFields.get(\"intPar\").toString());\n\ntrue;"
}
}
} ]
package org.onap.policy.apex.testsuites.integration.common.model.java;
-import java.security.NoSuchAlgorithmException;
-import java.security.SecureRandom;
+import java.util.Random;
import org.onap.policy.apex.core.engine.executor.context.TaskExecutionContext;
* Gets the event.
*
* @param executor the executor
- * @return true , if the event exists
+ * @return the event
*/
public boolean getEvent(final TaskExecutionContext executor) {
String idString = executor.subject.getId();
String inFieldsString = executor.inFields.toString();
executor.logger.debug(inFieldsString);
-
- try {
- SecureRandom rand = SecureRandom.getInstanceStrong();
- if (executor.inFields.containsKey("TestDecideCaseSelected")) {
- executor.outFields.put("TestActCaseSelected", (byte) rand.nextInt(BOUND_FOR_RANDOM_INT));
- executor.outFields.put("TestActStateTime", System.nanoTime());
- } else if (executor.inFields.containsKey("TestEstablishCaseSelected")) {
- executor.outFields.put("TestDecideCaseSelected", (byte) rand.nextInt(BOUND_FOR_RANDOM_INT));
- executor.outFields.put("TestDecideStateTime", System.nanoTime());
- } else if (executor.inFields.containsKey("TestMatchCaseSelected")) {
- executor.outFields.put("TestEstablishCaseSelected", (byte) rand.nextInt(BOUND_FOR_RANDOM_INT));
- executor.outFields.put("TestEstablishStateTime", System.nanoTime());
- } else {
- executor.outFields.put("TestMatchCaseSelected", (byte) rand.nextInt(BOUND_FOR_RANDOM_INT));
- executor.outFields.put("TestMatchStateTime", System.nanoTime());
- }
- } catch (NoSuchAlgorithmException e) {
- executor.logger.error("Exception during Random number generation ", e);
- return false;
+ final Random rand = new Random();
+ if (executor.inFields.containsKey("TestDecideCaseSelected")) {
+ executor.outFields.put("TestActCaseSelected", (byte) rand.nextInt(BOUND_FOR_RANDOM_INT));
+ executor.outFields.put("TestActStateTime", System.nanoTime());
+ } else if (executor.inFields.containsKey("TestEstablishCaseSelected")) {
+ executor.outFields.put("TestDecideCaseSelected", (byte) rand.nextInt(BOUND_FOR_RANDOM_INT));
+ executor.outFields.put("TestDecideStateTime", System.nanoTime());
+ } else if (executor.inFields.containsKey("TestMatchCaseSelected")) {
+ executor.outFields.put("TestEstablishCaseSelected", (byte) rand.nextInt(BOUND_FOR_RANDOM_INT));
+ executor.outFields.put("TestEstablishStateTime", System.nanoTime());
+ } else {
+ executor.outFields.put("TestMatchCaseSelected", (byte) rand.nextInt(BOUND_FOR_RANDOM_INT));
+ executor.outFields.put("TestMatchStateTime", System.nanoTime());
}
- return true;
+ return true;
}
}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* 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=========================================================
*/
import java.io.Serializable;
+import lombok.Data;
+
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
/**
*
* @author Liam Fallon (liam.fallon@ericsson.com)
*/
+@Data
public class PingTestClass implements Serializable {
private static final long serialVersionUID = -3400711508992955886L;
+ private int id = 0;
private String name = "Rose";
private String description = "A rose by any other name would smell as sweet";
private long pingTime = System.currentTimeMillis();
private long pongTime = -1;
- /**
- * Gets the name.
- *
- * @return the name
- */
- public String getName() {
- return name;
- }
-
- /**
- * Sets the name.
- *
- * @param name the new name
- */
- public void setName(final String name) {
- this.name = name;
- }
-
- /**
- * Gets the description.
- *
- * @return the description
- */
- public String getDescription() {
- return description;
- }
-
- /**
- * Sets the description.
- *
- * @param description the new description
- */
- public void setDescription(final String description) {
- this.description = description;
- }
-
- /**
- * Gets the ping time.
- *
- * @return the ping time
- */
- public long getPingTime() {
- return pingTime;
- }
-
- /**
- * Sets the ping time.
- *
- * @param pingTime the new ping time
- */
- public void setPingTime(final long pingTime) {
- this.pingTime = pingTime;
- }
-
- /**
- * Gets the pong time.
- *
- * @return the pong time
- */
- public long getPongTime() {
- return pongTime;
- }
-
- /**
- * Sets the pong time.
- *
- * @param pongTime the new pong time
- */
- public void setPongTime(final long pongTime) {
- this.pongTime = pongTime;
- }
-
- /**
- * {@inheritDoc}.
- */
- @Override
- public String toString() {
- return "TestPing [name=" + name + ", description=" + description + ", pingTime=" + pingTime + ", pongTime="
- + pongTime + "]";
- }
-
/**
* Verify the class.
*
throw new ApexException("TestPing is not valid, description is incorrect");
}
- if (pongTime <= pingTime) {
- throw new ApexException("TestPing is not valid, pong time is not greater than ping time");
+ if (pongTime < pingTime) {
+ throw new ApexException(
+ "TestPing is not valid, pong time " + pongTime + " is less than ping time " + pingTime);
}
}
}
"taskLogic": {
"key": "TaskLogic",
"logicFlavour": "JAVASCRIPT",
- "logic": "var outFieldType = Java.type(\"org.onap.policy.apex.testsuites.integration.common.testclasses.PingTestClass\");\nvar outValue = new outFieldType();\n\nvar inValue = executor.inFields.get(\"PingTestClass\");\n\nexecutor.logger.info(inValue.toString());\n\noutValue.setPingTime(inValue.getPingTime());\noutValue.setPongTime(new Date().getTime());\noutValue.setName(inValue.getName() + \"_out\");\n\noutValue.setDescription(\ninValue.getDescription() +\n\". So Romeo would, were he not Romeo call'd,\" +\n\" retain that dear perfection which he owes, without that title.\");\n\nexecutor.logger.info(outValue.toString();\nexecutor.outFields.put(\"PingTestClass\", outValue)\n\nvar returnValueType = Java.type(\"java.lang.Boolean\");\nvar returnValue = new returnValueType(true);"
+ "logic": "var outFieldType = org.onap.policy.apex.testsuites.integration.common.testclasses.PingTestClass;\nvar outValue = new outFieldType();\n\nvar inValue = executor.inFields.get(\"PingTestClass\");\n\nexecutor.logger.debug(inValue.toString());\n\noutValue.setPingTime(inValue.getPingTime());\noutValue.setPongTime(new Date().getTime());\noutValue.setName(inValue.getName() + \"_out\");\n\noutValue.setDescription(\ninValue.getDescription() +\n\". So Romeo would, were he not Romeo call'd,\" +\n\" retain that dear perfection which he owes, without that title.\");\n\nexecutor.logger.debug(outValue.toString());\nexecutor.outFields.put(\"PingTestClass\", outValue)\n\ntrue;"
}
}
}
* 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=========================================================
*/
-executor.logger.debug(executor.subject.getId());
+executor.logger.debug(executor.getSubject().getId());
var gc = executor.getContextAlbum("GlobalContextAlbum");
executor.logger.debug(gc.getName());
-executor.getSubject().getDefaultTaskKey().copyTo(executor.selectedTask);
-
-var returnValue = executor.isTrue;
+executor.getSubject().getDefaultTaskKey().copyTo(executor.selectedTask)
+true;
\ No newline at end of file
* 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=========================================================
*/
-executor.logger.debug(executor.subject.getId());
+executor.logger.debug(executor.getSubject().getId());
+executor.logger.debug(executor.getInFields());
+
var gc = executor.getContextAlbum("GlobalContextAlbum");
executor.logger.debug(gc.getName());
-executor.logger.debug(executor.inFields.get("TestSlogan"));
-var caseSelectedType = Java.type("java.lang.Byte");
+var caseSelectedType = java.lang.Byte;
executor.outFields.put("Test<STATE_NAME>CaseSelected", new caseSelectedType(<RANDOM_BYTE_VALUE>));
executor.outFields.put("Test<STATE_NAME>StateTime", java.lang.System.nanoTime());
-executor.logger.debug(executor.inFields.get("TestSlogan"));
+executor.logger.debug(executor.getOutFields());
-var returnValue = executor.isTrue;
+true;
* 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=========================================================
*/
-executor.logger.debug(executor.subject.getId());
+executor.logger.debug(executor.getSubject().getId());
executor.subject.defaultTaskKey.copyTo(executor.selectedTask);
-var returnValue = executor.isTrue;
-
+true;
* 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=========================================================
*/
-executor.logger.debug(executor.subject.getId());
-executor.logger.debug(executor.inFields.get("name"));
+executor.logger.debug(executor.getSubject().getId());
+executor.logger.debug(executor.getInFields());
executor.outFields.put("State<STATE_NUMBER>Timestamp", java.lang.System.nanoTime());
-executor.logger.debug(executor.outFields.get("name"));
+executor.logger.debug(executor.getOutFields());
-var returnValue = executor.isTrue;
+true;
\ No newline at end of file
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* 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=========================================================
*/
ptc.verify();
fail("test should throw an exception");
} catch (ApexException ae) {
- assertEquals("TestPing is not valid, pong time is not greater than ping time", ae.getMessage());
+ assertEquals("TestPing is not valid, pong time -1 is less than ping time 0", ae.getMessage());
}
- ptc.setPongTime(0);
+ ptc.setPongTime(-2);
try {
ptc.verify();
fail("test should throw an exception");
} catch (ApexException ae) {
- assertEquals("TestPing is not valid, pong time is not greater than ping time", ae.getMessage());
+ assertEquals("TestPing is not valid, pong time -2 is less than ping time 0", ae.getMessage());
}
ptc.setPongTime(1);
fail("test should not throw an exception");
}
- assertEquals("TestPing [name=Rose, description=A rose by any other name would smell as sweet, "
- + "pingTime=0, pongTime=1]", ptc.toString());
+ assertEquals(
+ "PingTestClass(id=0, name=Rose, "
+ + "description=A rose by any other name would smell as sweet, pingTime=0, pongTime=1)",
+ ptc.toString());
}
}
package org.onap.policy.apex.testsuites.integration.executor.engine;
+import static org.awaitility.Awaitility.await;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
+import java.util.concurrent.TimeUnit;
import org.onap.policy.apex.core.engine.EngineParameters;
import org.onap.policy.apex.core.engine.engine.ApexEngine;
import org.onap.policy.apex.core.engine.event.EnEvent;
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
+import org.onap.policy.apex.model.enginemodel.concepts.AxEngineState;
import org.onap.policy.apex.model.eventmodel.concepts.AxEvent;
import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
import org.onap.policy.apex.testsuites.integration.common.model.SampleDomainModelFactory;
final Map<AxArtifactKey, Map<String, Object>> apexContext = apexEngine.getEngineContext();
assertNotNull(apexContext);
apexEngine.stop();
+
+ await().atMost(3L, TimeUnit.SECONDS).until(() -> AxEngineState.STOPPED.equals(apexEngine.getState()));
}
/**
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* 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=========================================================
*/
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.infrastructure.threading.ThreadUtilities;
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
import org.onap.policy.apex.plugins.executor.jruby.JrubyExecutorParameters;
import org.onap.policy.common.parameters.ParameterService;
@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);
ParameterService.register(contextParameters.getDistributorParameters());
ParameterService.register(contextParameters.getLockManagerParameters());
ParameterService.register(contextParameters.getPersistorParameters());
-
+
engineParameters = new EngineParameters();
engineParameters.getExecutorParameterMap().put("JRUBY", new JrubyExecutorParameters());
ParameterService.register(engineParameters);
@After
public void afterTest() {
ParameterService.deregister(engineParameters);
-
+
ParameterService.deregister(contextParameters.getDistributorParameters());
ParameterService.deregister(contextParameters.getLockManagerParameters());
ParameterService.deregister(contextParameters.getPersistorParameters());
@Test
public void testApexEngineJRuby() throws ApexException, InterruptedException, IOException {
new TestApexEngine("JRUBY", engineParameters);
- ThreadUtilities.sleep(5000);
new TestApexEngine("JRUBY", engineParameters);
}
}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* 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=========================================================
*/
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.infrastructure.threading.ThreadUtilities;
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
import org.onap.policy.apex.plugins.executor.java.JavaExecutorParameters;
import org.onap.policy.common.parameters.ParameterService;
@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);
ParameterService.register(contextParameters.getDistributorParameters());
ParameterService.register(contextParameters.getLockManagerParameters());
ParameterService.register(contextParameters.getPersistorParameters());
-
+
engineParameters = new EngineParameters();
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());
@Test
public void testApexEngineJava() throws InterruptedException, IOException, ApexException {
new TestApexEngine("JAVA", engineParameters);
- ThreadUtilities.sleep(5000);
new TestApexEngine("JAVA", engineParameters);
}
}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* 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=========================================================
*/
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.infrastructure.threading.ThreadUtilities;
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
import org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters;
import org.onap.policy.common.parameters.ParameterService;
@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);
ParameterService.register(contextParameters.getDistributorParameters());
ParameterService.register(contextParameters.getLockManagerParameters());
ParameterService.register(contextParameters.getPersistorParameters());
-
+
engineParameters = new EngineParameters();
engineParameters.getExecutorParameterMap().put("JAVASCRIPT", new JavascriptExecutorParameters());
ParameterService.register(engineParameters);
@After
public void afterTest() {
ParameterService.deregister(engineParameters);
-
+
ParameterService.deregister(contextParameters.getDistributorParameters());
ParameterService.deregister(contextParameters.getLockManagerParameters());
ParameterService.deregister(contextParameters.getPersistorParameters());
public void testApexEngineJavascript() throws ApexException, InterruptedException, IOException {
new TestApexEngine("JAVASCRIPT", engineParameters);
- ThreadUtilities.sleep(5000);
new TestApexEngine("JAVASCRIPT", engineParameters);
}
}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
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.infrastructure.threading.ThreadUtilities;
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
import org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters;
import org.onap.policy.common.parameters.ParameterService;
@Test
public void testApexEngineJython() throws ApexException, InterruptedException, IOException {
new TestApexEngine("JAVASCRIPT", engineParameters);
- ThreadUtilities.sleep(5000);
new TestApexEngine("JAVASCRIPT", engineParameters);
}
}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* 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=========================================================
*/
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.infrastructure.threading.ThreadUtilities;
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters;
import org.onap.policy.common.parameters.ParameterService;
@Test
public void testApexEngineMvel() throws ApexException, InterruptedException, IOException {
new TestApexEngine("MVEL", engineParameters);
- ThreadUtilities.sleep(5000);
new TestApexEngine("MVEL", engineParameters);
}
}
<!--
============LICENSE_START=======================================================
Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ Modifications Copyright (C) 2020 Nordix Foundation.
================================================================================
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>
</appender>
- <root level="INFO">
+ <root level="OFF">
<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.monitoring" level="INFO" additivity="false">
- <appender-ref ref="CTXT_FILE" />
- </logger>
-
- <logger name="org.onap.policy.apex.core.engine.monitoring" level="INFO" additivity="false">
- <appender-ref ref="CTXT_FILE" />
- </logger>
-
- <logger name="org.onap.policy.apex.executionlogging" level="INFO" additivity="false">
- <appender-ref ref="STDOUT" />
- </logger>
-
- <logger name="org.onap.policy.apex" level="INFO" additivity="false">
- <appender-ref ref="STDOUT" />
- </logger>
</configuration>
public static void main(final String[] args) throws MessagingException, ApexException, IOException {
final String[] apexArgs = {"-rfr", "target", "-c", "examples/config/SampleDomain/File2FileJsonEvent.json"};
+ new File("src/test/resources/events/EventsOut.json").delete();
+
testFileEvents(apexArgs, "src/test/resources/events/EventsOut.json", 48656);
}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019-2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* @throws JMSException the JMS exception
*/
public JmsEventProducer(final String topic, final ConnectionFactory connectionFactory, final String username,
- final String password, final int eventCount, final boolean sendObjects, final long eventInterval)
- throws JMSException {
+ final String password, final int eventCount, final boolean sendObjects,
+ final long eventInterval) throws JMSException {
this.topic = topic;
this.eventCount = eventCount;
this.sendObjects = sendObjects;
public void run() {
final Topic jmsTopic = new ActiveMQTopic(topic);
try (final Session jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- final MessageProducer jmsProducer = jmsSession.createProducer(jmsTopic)) {
+ final MessageProducer jmsProducer = jmsSession.createProducer(jmsTopic)) {
while (producerThread.isAlive() && !stopFlag) {
ThreadUtilities.sleep(50);
Message jmsMessage = null;
if (sendObjects) {
- jmsMessage = jmsSession.createObjectMessage(new PingTestClass());
+ final PingTestClass pingTestClass = new PingTestClass();
+ pingTestClass.setId(i);
+ jmsMessage = jmsSession.createObjectMessage(pingTestClass);
} else {
jmsMessage = jmsSession.createTextMessage(EventGenerator.jsonEvent());
}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
- * Modifications Copyright (C) 2019 Nordix Foundation.
+ * Modifications Copyright (C) 2019-2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* @throws JMSException the JMS exception
*/
public JmsEventSubscriber(final String topic, final ConnectionFactory connectionFactory, final String username,
- final String password) throws JMSException {
+ final String password) throws JMSException {
this.topic = topic;
connection = connectionFactory.createConnection(username, password);
connection.start();
public void run() {
final Topic jmsTopic = new ActiveMQTopic(topic);
try (final Session jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
- final MessageConsumer jmsConsumer = jmsSession.createConsumer(jmsTopic)) {
+ final MessageConsumer jmsConsumer = jmsSession.createConsumer(jmsTopic)) {
while (subscriberThread.isAlive() && !subscriberThread.isInterrupted()) {
try {
((TextMessage) message).getText();
} else {
throw new ApexEventException("unknowm message \"" + message + "\" of type \""
- + message.getClass().getName() + "\" received");
+ + message.getClass().getName() + "\" received");
}
eventsReceivedCount++;
} catch (final Exception e) {
- break;
+ if (!(e.getCause() instanceof InterruptedException)) {
+ throw new ApexEventRuntimeException("JMS message reception failed", e);
+ }
}
}
throw new ApexEventRuntimeException("JMS event consumption failed", e);
}
- LOGGER.debug("{} : event reception completed", this.getClass().getName());
+ LOGGER.info("{} : event reception completed, {} events received", this.getClass().getName(),
+ eventsReceivedCount);
}
/**
* @throws JMSException the JMS exception
*/
public void shutdown() throws JMSException {
+ LOGGER.info("{} : stopping...", this.getClass().getName());
+
subscriberThread.interrupt();
while (subscriberThread.isAlive()) {
}
connection.close();
- LOGGER.debug("{} : stopped", this.getClass().getName());
+ LOGGER.info("{} : stopped", this.getClass().getName());
}
}
package org.onap.policy.apex.testsuites.integration.uservice.adapt.jms;
+import static org.awaitility.Awaitility.await;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
+import java.util.concurrent.TimeUnit;
import javax.jms.JMSException;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
-import org.junit.Ignore;
import org.junit.Test;
-import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
import org.onap.policy.apex.service.engine.main.ApexMain;
import org.slf4j.ext.XLogger;
public static final String JMS_TOPIC_APEX_IN = "jms/topic/apexIn";
public static final String JMS_TOPIC_APEX_OUT = "jms/topic/apexOut";
- private static final int SLEEP_TIME = 1500;
private static final String GROUP_ROLE = "guests";
private static final String PACKAGE_NAME = "org.onap.policy.apex.testsuites.integration.common.testclasses";
private static final String USERNAME = "guest";
private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestJms2Jms.class);
- private static final long MAX_TEST_LENGTH = 10000;
private static final int EVENT_COUNT = 100;
private static final int EVENT_INTERVAL = 20;
* @throws JMSException the JMS exception
*/
@Test
- @Ignore
public void testJmsObjectEvents() throws ApexException, JMSException {
final String[] args = {"-rfr", "target", "-c", "target/examples/config/JMS/JMS2JMSObjectEvent.json"};
testJmsEvents(args, true);
private void testJmsEvents(final String[] args, final Boolean sendObjects) throws ApexException, JMSException {
final JmsEventSubscriber subscriber =
new JmsEventSubscriber(JMS_TOPIC_APEX_OUT, connectionFactory, USERNAME, PASSWORD);
+
final JmsEventProducer producer = new JmsEventProducer(JMS_TOPIC_APEX_IN, connectionFactory, USERNAME, PASSWORD,
EVENT_COUNT, sendObjects, EVENT_INTERVAL);
final ApexMain apexMain = new ApexMain(args);
- ThreadUtilities.sleep(3000);
+
+ await().atMost(3L, TimeUnit.SECONDS).until(() -> apexMain.isAlive());
producer.sendEvents();
- final long testStartTime = System.currentTimeMillis();
+ await().atMost(10L, TimeUnit.SECONDS).until(() -> producer.getEventsSentCount() >= EVENT_COUNT - 1);
+ await().atMost(10L, TimeUnit.SECONDS).until(() -> subscriber.getEventsReceivedCount() >= EVENT_COUNT - 1);
- while (isTimedOut(testStartTime) && subscriber.getEventsReceivedCount() < EVENT_COUNT) {
- ThreadUtilities.sleep(EVENT_INTERVAL);
- }
-
- ThreadUtilities.sleep(SLEEP_TIME);
apexMain.shutdown();
subscriber.shutdown();
producer.shutdown();
- ThreadUtilities.sleep(SLEEP_TIME);
assertEquals(EVENT_COUNT, producer.getEventsSentCount());
assertEquals(producer.getEventsSentCount(), subscriber.getEventsReceivedCount());
-
- }
-
- /**
- * Checks if is timed out.
- *
- * @param testStartTime the test start time
- * @return true, if is timed out
- */
- private boolean isTimedOut(final long testStartTime) {
- return System.currentTimeMillis() < testStartTime + MAX_TEST_LENGTH;
}
}
/*-
* ============LICENSE_START=======================================================
* Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ * Modifications Copyright (C) 2020 Nordix Foundation.
* ================================================================================
* 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=========================================================
*/
engineServiceParameters.setInstanceCount(3);
engineServiceParameters.setId(100);
engineServiceParameters.getEngineParameters().getExecutorParameterMap().put("JAVASCRIPT",
- new JavascriptExecutorParameters());
+ new JavascriptExecutorParameters());
ParameterService.register(engineServiceParameters, true);
ParameterService.register(engineServiceParameters.getEngineParameters(), true);
eventDataMap.put("TestTimestamp", testStartTime.getTime());
eventDataMap.put("TestTemperature", 34.5445667);
- final ApexEvent event0 = new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events",
- "apex", "test");
+ final ApexEvent event0 =
+ new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", "apex", "test");
event0.putAll(eventDataMap);
server.sendEvent(event0);
- final ApexEvent event1 = new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events",
- "apex", "test");
+ final ApexEvent event1 =
+ new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events", "apex", "test");
event1.putAll(eventDataMap);
server.sendEvent(event1);
*/
@After
public void tearDown() throws Exception {
+ ModelService.clear();
}
}
import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
import org.onap.policy.apex.model.basicmodel.handling.ApexModelException;
import org.onap.policy.apex.model.basicmodel.handling.ApexModelWriter;
+import org.onap.policy.apex.model.basicmodel.service.ModelService;
import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
import org.onap.policy.apex.plugins.executor.javascript.JavascriptExecutorParameters;
import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters;
private boolean waitFlag = true;
- /**
- * Sets the up.
- *
- * @throws Exception the exception
- */
@BeforeClass
- public static void setUp() throws Exception {
+ public static void beforeSetUp() throws Exception {
// create engine with 3 threads
parameters.setInstanceCount(3);
parameters.setName(engineServiceKey.getName());
service.registerActionListener("Listener", listener);
}
+ @AfterClass
+ public static void afterCleardown() throws Exception {
+ ModelService.clear();
+ }
+
/**
* Set up parameters.
*/
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
+ * Copyright (C) 2019-2020 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
File compiledPolicyFile = new File("target/ExecutionPropertiesTestPolicyModel.json");
assertTrue(compiledPolicyFile.exists());
- new File("target/" + testName + "_out.properties").delete();
+ File outFile = new File("target/" + testName + "_out.properties");
+ outFile.deleteOnExit();
// @formatter:off
final String[] args = {
// @formatter:on
final ApexMain apexMain = new ApexMain(args);
- // TODO: Set back to 10 seconds
- await().atMost(10000, TimeUnit.SECONDS)
- .until(() -> new File("target/" + testName + "_out.properties").exists());
+ await().atMost(1, TimeUnit.SECONDS).until(() -> apexMain.isAlive());
+ await().atMost(10, TimeUnit.SECONDS).until(() -> outFile.exists());
+ await().atMost(1, TimeUnit.SECONDS).until(() -> outFile.length() > 0);
apexMain.shutdown();
new File("src/test/resources/testdata/executionproperties/" + testName + "_out_expected.properties")));
Properties actualProperties = new Properties();
- actualProperties.load(new FileInputStream(new File("target/" + testName + "_out.properties")));
+ actualProperties.load(new FileInputStream(outFile));
assertEquals(expectedProperties, actualProperties);
}
"AvroBoolean": true,
"AvroByte": -127.0,
"AvroDouble": 1.2345E67,
- "AvroFloat": 1.9999999556392617E23,
+ "AvroFloat": 1.9999999999999998E23,
"AvroInteger": 1234568.0,
"AvroLong": 1.234567890124E12,
"AvroMap": {
* ============LICENSE_END=========================================================
*/
-executor.logger.info(executor.getSubject().getId());
+executor.logger.debug(executor.getSubject().getId());
-executor.logger.info("executionProperties in:" + executor.getExecutionProperties());
+executor.logger.debug("executionProperties in:" + executor.getExecutionProperties());
var executionProperties = new java.util.Properties();
executor.getExecutionProperties().setProperty("goodbye", "mars");
-executor.logger.info("executionProperties out:" + executor.getExecutionProperties());
+executor.logger.debug("executionProperties out:" + executor.getExecutionProperties());
-var returnValue = executor.isTrue;
+true;
* ============LICENSE_END=========================================================
*/
-executor.logger.info(executor.getSubject().getId());
+executor.logger.debug(executor.getSubject().getId());
-executor.logger.info("executionProperties in:" + executor.getExecutionProperties());
+executor.logger.debug("executionProperties in:" + executor.getExecutionProperties());
var executionProperties = new java.util.Properties();
executor.getExecutionProperties().clear();
-executor.logger.info("executionProperties out:" + executor.getExecutionProperties());
+executor.logger.debug("executionProperties out:" + executor.getExecutionProperties());
-var returnValue = executor.isTrue;
+true;
* ============LICENSE_END=========================================================
*/
-executor.logger.info(executor.getSubject().getId());
+executor.logger.debug(executor.getSubject().getId());
-executor.logger.info("executionProperties in:" + executor.getExecutionProperties());
+executor.logger.debug("executionProperties in:" + executor.getExecutionProperties());
var executionProperties = new java.util.Properties();
executor.getExecutionProperties().setProperty("hello", "world");
-executor.logger.info("executionProperties out:" + executor.getExecutionProperties());
+executor.logger.debug("executionProperties out:" + executor.getExecutionProperties());
-var returnValue = executor.isTrue;
+true;
* ============LICENSE_END=========================================================
*/
-executor.logger.info(executor.getSubject().getId());
+executor.logger.debug(executor.getSubject().getId());
+executor.logger.debug(executor.getInFields().toString());
+executor.logger.debug("executionProperties:" + executor.getExecutionProperties());
+executor.logger.debug(executor.getOutFields().toString());
-executor.logger.info("executionProperties:" + executor.getExecutionProperties());
-
-var returnValue = executor.isTrue;
+true;
* ============LICENSE_END=========================================================
*/
-executor.logger.info(executor.getSubject().getId());
+executor.logger.debug(executor.getSubject().getId());
+executor.logger.debug(executor.getInFields().toString());
+executor.logger.debug("executionProperties:" + executor.getExecutionProperties());
-executor.logger.info("executionProperties:" + executor.getExecutionProperties());
+executor.logger.debug(executor.getOutFields().toString());
-var returnValue = executor.isTrue;
+true;
* ============LICENSE_END=========================================================
*/
-executor.logger.info(executor.getSubject().getId());
+executor.logger.debug(executor.getSubject().getId());
-executor.logger.info("executionProperties in:" + executor.getExecutionProperties());
+executor.logger.debug("executionProperties in:" + executor.getExecutionProperties());
var executionProperties = new java.util.Properties();
executor.getExecutionProperties().remove("hello");
-executor.logger.info("executionProperties out:" + executor.getExecutionProperties());
+executor.logger.debug("executionProperties out:" + executor.getExecutionProperties());
-var returnValue = executor.isTrue;
+true;
* ============LICENSE_END=========================================================
*/
-executor.logger.info(executor.getSubject().getId());
+executor.logger.debug(executor.getSubject().getId());
+executor.logger.debug(executor.getInFields().toString());
+executor.logger.debug("executionProperties:" + executor.getExecutionProperties());
-var returnValue = executor.isTrue;
+executor.logger.debug("testToRun:" + executor.getInFields().get("testToRun"));
-executor.logger.info("executionProperties:" + executor.getExecutionProperties());
+var returnValue = true;
-switch (executor.inFields.get("testToRun")) {
+// Convert Java string to a Javascript variable
+var testToRun = String(executor.getInFields().get("testToRun")).valueOf();
+
+switch (testToRun) {
case "ReadOnly":
executor.subject.getTaskKey("ReadOnlyTask").copyTo(executor.selectedTask);
break;
break;
default:
- executor.subject.getTaskKey("ReadOnlyTask").copyTo(executor.selectedTask);
+ executor.logger.debug("invalid value for testToRun:" + executor.getInFields().get("testToRun"));
+ returnValue = false;
}
-executor.logger.info("Selected Task:" + executor.selectedTask);
+executor.logger.debug("Selected Task:" + executor.selectedTask);
+
+returnValue;
+
* ============LICENSE_END=========================================================
*/
-executor.logger.info(executor.getSubject().getId());
+executor.logger.debug(executor.getSubject().getId());
-executor.logger.info("executionProperties: " + executor.getExecutionProperties());
+executor.logger.debug("executionProperties: " + executor.getExecutionProperties());
if (executor.getExecutionProperties().get("HTTP_CODE_STATUS") == "500")
executor.outFields.put("testToRun", "CodeFilterSet");
else
executor.outFields.put("testToRun", "CodeFilterDefault");
-executor.logger.info("testToRun: " + executor.outFields.get("testToRun"));
+executor.logger.debug("testToRun: " + executor.outFields.get("testToRun"));
-var returnValue = executor.isTrue;
\ No newline at end of file
+true;
* ============LICENSE_END=========================================================
*/
-executor.logger.info(executor.getSubject().getId());
+executor.logger.debug(executor.getSubject().getId());
-executor.logger.info("executionProperties in:" + executor.getExecutionProperties());
+executor.logger.debug("executionProperties in:" + executor.getExecutionProperties());
executor.getExecutionProperties().setProperty("tagId", executor.inFields.get("testToRun"));
executor.getExecutionProperties().setProperty("value", "3");
-executor.logger.info("executionProperties out:" + executor.getExecutionProperties());
+executor.logger.debug("executionProperties out:" + executor.getExecutionProperties());
-var returnValue = executor.isTrue;
\ No newline at end of file
+true;
executor.logger.info("executionProperties out: {}", executor.getExecutionProperties().toString());
-var returnValue = executor.isTrue;
\ No newline at end of file
+true;
\ No newline at end of file
executor.getExecutionProperties().setProperty("value", svcId);
executor.logger.info("executionProperties out: {}", executor.getExecutionProperties().toString());
-var returnValue = executor.isTrue;
\ No newline at end of file
+
+true;
\ No newline at end of file
<modules>
<module>integration-common</module>
- <!--module>integration-executor-test</module-->
- <!--module>integration-uservice-test</module-->
+ <module>integration-executor-test</module>
+ <module>integration-uservice-test</module>
</modules>
<dependencies>