diff options
Diffstat (limited to 'src/site-docs/adoc/fragments/howto-write-logic')
4 files changed, 655 insertions, 0 deletions
diff --git a/src/site-docs/adoc/fragments/howto-write-logic/logic-cheatsheet.adoc b/src/site-docs/adoc/fragments/howto-write-logic/logic-cheatsheet.adoc new file mode 100644 index 000000000..fe3cd0d0d --- /dev/null +++ b/src/site-docs/adoc/fragments/howto-write-logic/logic-cheatsheet.adoc @@ -0,0 +1,269 @@ +// +// ============LICENSE_START======================================================= +// Copyright (C) 2016-2018 Ericsson. All rights reserved. +// ================================================================================ +// This file is licensed under the CREATIVE COMMONS ATTRIBUTION 4.0 INTERNATIONAL LICENSE +// Full license text at https://creativecommons.org/licenses/by/4.0/legalcode +// +// SPDX-License-Identifier: CC-BY-4.0 +// ============LICENSE_END========================================================= +// +// @author Sven van der Meer (sven.van.der.meer@ericsson.com) +// + +== Logic Cheatsheet + +Examples given here use Javascript (if not stated otherwise), other execution environments will be similar. + + +=== Add Nashorn + +First line in the logic use this import. + +.JS Nashorn +[source,javascript,options="nowrap"] +---- +load("nashorn:mozilla_compat.js"); +---- + + +=== Finish Logic with Success or Error + +To finish logic, i.e. return to APEX, with success use the following lines close to the end of the logic. + +.JS Success +[source,javascript,options="nowrap"] +---- +var returnValueType = Java.type("java.lang.Boolean"); +var returnValue = new returnValueType(true); +---- + +To notify a problem, finish with an error. + +.JS Fail +[source,javascript,options="nowrap"] +---- +var returnValueType = Java.type("java.lang.Boolean"); +var returnValue = new returnValueType(false); +---- + + +=== Logic Logging + +Logging can be made easy using a local variable for the logger. +Line 1 below does that. +Then we start with a trace log with the task (or task logic) identifier followed by the infields. + +.JS Logging +[source,javascript,options="nowrap"] +---- +var logger = executor.logger; +logger.trace("start: " + executor.subject.id); +logger.trace("-- infields: " + executor.inFields); +---- + +For larger logging blocks you can use the standard logging API to detect log levels, for instance: + +.JS Logging Blocks +[source,javascript,options="nowrap"] +---- +if(logger.isTraceEnabled()){ + // trace logging block here +} +---- + +Note: the shown logger here logs to `org.onap.policy.apex.executionlogging`. +The behavior of the actual logging can be specified in the `$APEX_HOME/etc/logback.xml`. + +If you want to log into the APEX root logger (which is sometimes necessary to report serious logic errors to the top), +then import the required class and use this logger. + +.JS Root Logger +[source,javascript,options="nowrap"] +---- +importClass(org.slf4j.LoggerFactory); +var rootLogger = LoggerFactory.getLogger(logger.ROOT_LOGGER_NAME); + +rootLogger.error("Serious error in logic detected: " + executor.subject.id); +---- + +=== Local Variable for Infields + +It is a good idea to use local variables for `infields`. +This avoids long code lines and policy evolution. +The following example assumes infields named `nodeName` and `nodeAlias`. + +.JS Infields Local Var +[source,javascript,options="nowrap"] +---- +var ifNodeName = executor.inFields["nodeName"]; +var ifNodeAlias = executor.inFields["nodeAlias"]; +---- + + +=== Local Variable for Context Albums + +Similar to the `infields` it is good practice to use local variables for context albums as well. +The following example assumes that a task can access a context album `albumTopoNodes`. +The second line gets a particular node from this context album. + +.JS Infields Local Var +[source,javascript,options="nowrap"] +---- +var albumTopoNodes = executor.getContextAlbum("albumTopoNodes"); +var ctxtNode = albumTopoNodes.get(ifNodeName); +---- + + +=== Set Outfields in Logic + +The task logic needs to set outfields with content generated. +The exception are outfields that are a direct copy from an infield of the same name, APEX does that autmatically. + +.JS Set Outfields +[source,javascript,options="nowrap"] +---- +executor.outFields["report"] = "node ctxt :: added node " + ifNodeName; +---- + + +=== Create a instance of an Outfield using Schemas + +If an outfield is not an atomic type (string, integer, etc.) but uses a complex schema (with a Java or Avro backend), APEX can help to create new instances. +The `executor` provides a field called `subject`, which provides a schem helper with an API for this. +The complete API of the schema helper is documented here: link:https://ericsson.github.io/apex-docs/javadocs/index.html[API Doc: SchemaHelper]. + +If the backend is Avro, then an import of the Avro schema library is required: + +.JS Import Avro +[source,javascript,options="nowrap"] +---- +importClass(org.apache.avro.generic.GenericData.Array); +importClass(org.apache.avro.generic.GenericRecord); +importClass(org.apache.avro.Schema); +---- + +If the backend is Java, then the Java class implementing the schema needs to be imported. + +The following example assumes an outfield `situation`. +The `subject` method `getOutFieldSchemaHelper()` is used to create a new instance. + +.JS Outfield Instance with Schema +[source,javascript,options="nowrap"] +---- +var situation = executor.subject.getOutFieldSchemaHelper("situation").createNewInstance(); +---- + +If the schema backend is Java, the new instance will be as implemented in the Java class. +If the schema backend is Avro, the new instance will have all fields from the Avro schema specification, but set to `null`. +So any entry here needs to be done separately. +For instance, the `situation` schema has a field `problemID` which we set. + +.JS Outfield Instance with Schema, set +[source,javascript,options="nowrap"] +---- +situation.put("problemID", "my-problem"); +---- + + +=== Create a instance of an Context Album entry using Schemas + +Context album instances can be created using very similar to the outfields. +Here, the schema helper comes from the context album directly. +The API of the schema helper is the same as for outfields, see link:https://ericsson.github.io/apex-docs/javadocs/index.html[API Doc: SchemaHelper]. + +If the backend is Avro, then an import of the Avro schema library is required: + +.JS Import Avro +[source,javascript,options="nowrap"] +---- +importClass(org.apache.avro.generic.GenericData.Array); +importClass(org.apache.avro.generic.GenericRecord); +importClass(org.apache.avro.Schema); +---- + +If the backend is Java, then the Java class implementing the schema needs to be imported. + +The following example creates a new instance of a context album instance named `albumProblemMap`. + +.JS Outfield Instance with Schema +[source,javascript,options="nowrap"] +---- +var albumProblemMap = executor.getContextAlbum("albumProblemMap"); +var linkProblem = albumProblemMap.getSchemaHelper().createNewInstance(); +---- + +This can of course be also done in a single call without the local variable for the context album. + +.JS Outfield Instance with Schema, one line +[source,javascript,options="nowrap"] +---- +var linkProblem = executor.getContextAlbum("albumProblemMap").getSchemaHelper().createNewInstance(); +---- + +If the schema backend is Java, the new instance will be as implemented in the Java class. +If the schema backend is Avro, the new instance will have all fields from the Avro schema specification, but set to `null`. +So any entry here needs to be done separately (see above in outfields for an example). + + +=== Enumerates + +When dealing with enumerates (Avro or Java defined), it is sometimes and in some execution environments necessary to convert them to a string. +For example, assume an Avro enumerate schema as: + +.Avro Enumerate Schema +[source,json,options="nowrap"] +---- +{ + "type": "enum", + "name": "Status", + "symbols" : [ + "UP", + "DOWN" + ] +} + +---- + +Using a switch over a field initialized with this enumerate in Javascript will fail. +Instead, use the `toString` method, for example: + +.JS Outfield Instance with Schema, one line +[source,javascript,options="nowrap"] +---- +var switchTest = executor.inFields["status"]; +switch(switchTest.toString()){ + case "UP": ...; break; + case "DOWN": ...; break; + default: ...; +} +---- + + +=== MVEL Initialize Outfields First! + +In MVEL, we observed a problem when accessing (setting) outfields without a prior access to them. +So in any MVEL task logic, before setting any outfield, simply do a get (with any string), to load the outfields into the MVEL cache. + +.MVEL Outfield Initialization +[source,java,options="nowrap"] +---- +outFields.get("initialize outfields"); +---- + + +=== Using Java in Scripting Logic + +Since APEX executes the logic inside a JVM, most scripting languages provide access to all standard Java classes. +Simply add an import for the required class and then use it as in actual Java. + +The following example imports `java.util.arraylist` into a Javascript logic, and then creates a new list. + +.JS Import ArrayList +[source,javascript,options="nowrap"] +---- +importClass(java.util.ArrayList); +var myList = new ArrayList(); +---- + + diff --git a/src/site-docs/adoc/fragments/howto-write-logic/policy-examples.adoc b/src/site-docs/adoc/fragments/howto-write-logic/policy-examples.adoc new file mode 100644 index 000000000..77769dc31 --- /dev/null +++ b/src/site-docs/adoc/fragments/howto-write-logic/policy-examples.adoc @@ -0,0 +1,44 @@ +// +// ============LICENSE_START======================================================= +// Copyright (C) 2016-2018 Ericsson. All rights reserved. +// ================================================================================ +// This file is licensed under the CREATIVE COMMONS ATTRIBUTION 4.0 INTERNATIONAL LICENSE +// Full license text at https://creativecommons.org/licenses/by/4.0/legalcode +// +// SPDX-License-Identifier: CC-BY-4.0 +// ============LICENSE_END========================================================= +// +// @author Sven van der Meer (sven.van.der.meer@ericsson.com) +// + +== My First Policy + +A good starting point is the `My First Policy` example. +It describes a sales problem, to which policy can be applied. +The example details the policy background, shows how to use the REST Editor to create a policy, and provides details for running the policies. +The documentation can be found: + +* link:https://ericsson.github.io/apex-docs/modules/apex-domains/apex-domains.myfirstpolicy/MyFirstPolicyHowto.html[My-First-Policy on the APEX site] +* link:https://ericsson.github.io/apex-docs/docs-apex/html/HowTo-MyFirstPolicy.html[Stand-alone HTML] +* link:https://ericsson.github.io/apex-docs/docs-apex/pdf/HowTo-MyFirstPolicy.pdf[Stand-alone PDF] + + +== VPN SLA + +The domain Policy-controlled Video Streaming (PCVS) contains a policy for controlling video streams with different strategies. +It also provides details for installing an actual testbed with off-the-shelve software (Mininet, Floodlight, Kafka, Zookeeper). +The policy model here demonstrates virtually all APEX features: local context and policies controlling it, task selection logic and multiple tasks in a single state, AVRO schemas for context, AVOR schemas for events (trigger and local), and a CLI editor specification of the policy. +The documentation can be found: + +* link:https://ericsson.github.io/apex-docs/modules/apex-domains/apex-domains.pcvs/vpnsla/policy.html[VPN SLA Policy on the APEX site] + + +== Decision Maker + +The domain Decision Maker shows a very simple policy for decisions. +Interesting here is that the it creates a Docker image to run the policy and that it uses the APEX REST applications to update the policy on the-fly. +It also has local context to remember past decisions, and shows how to use that to no make the same decision twice in a row. +The documentation can be found: + +* link:https://ericsson.github.io/apex-docs/modules/apex-domains/apex-domains.decisionmaker/index.html[Decision Maker on APEX site] + diff --git a/src/site-docs/adoc/fragments/howto-write-logic/task-logic.adoc b/src/site-docs/adoc/fragments/howto-write-logic/task-logic.adoc new file mode 100644 index 000000000..23a05024d --- /dev/null +++ b/src/site-docs/adoc/fragments/howto-write-logic/task-logic.adoc @@ -0,0 +1,177 @@ +// +// ============LICENSE_START======================================================= +// Copyright (C) 2016-2018 Ericsson. All rights reserved. +// ================================================================================ +// This file is licensed under the CREATIVE COMMONS ATTRIBUTION 4.0 INTERNATIONAL LICENSE +// Full license text at https://creativecommons.org/licenses/by/4.0/legalcode +// +// SPDX-License-Identifier: CC-BY-4.0 +// ============LICENSE_END========================================================= +// +// @author Sven van der Meer (sven.van.der.meer@ericsson.com) +// + +== Writing APEX Task Logic + +Task logic specifies the behavior of an Apex Task. +This logic can be specified in a number of ways, exploiting Apex's plug-in architecture to support a range of logic executors. +In Apex scripted Task Logic can be written in any of these languages: + +* https://en.wikipedia.org/wiki/MVEL[`MVEL`], +* https://en.wikipedia.org/wiki/JavaScript[`JavaScript`], +* https://en.wikipedia.org/wiki/JRuby[`JRuby`] or +* https://en.wikipedia.org/wiki/Jython[`Jython`]. + +These languages were chosen because the scripts can be compiled into Java bytecode at runtime and then efficiently executed natively in the JVM. +Task Logic an also be written directly in Java but needs to be compiled, with the resulting classes added to the classpath. +There are also a number of other Task Logic types (e.g. Fuzzy Logic), but these are not supported as yet. +This guide will focus on the scripted Task Logic approaches, with MVEL and JavaScript being our favorite languages. +In particular this guide will focus on the Apex aspects of the scripts. +However, this guide does not attempt to teach you about the scripting languages themselves ... that is up to you! + +[TIP] +.JVM-based scripting languages +==== +For more more information on Scripting for the Java platform see: https://docs.oracle.com/javase/8/docs/technotes/guides/scripting/prog_guide/index.html +==== + +[NOTE] +.What do Tasks do? +==== +The function of an Apex Task is to provide the logic that can be executed for an Apex State as one of the steps in an Apex Policy. +Each task receives some _incoming fields_, executes some logic (e.g: make a decision based on _shared state_ or _context_, _incoming fields_, _external context_, etc.), perhaps set some _shared state_ or _context_ and then emits _outgoing fields_. +The state that uses the task is responsible for extracting the _incoming fields_ from the state input event. +The state also has an _output mapper_ associated with the task, and this _output mapper_ is responsible for mapping the _outgoing fields_ from the task into an appropriate output event for the state. +==== + +First lets start with a sample task, drawn from the "My First Apex Policy" example: +The task "MorningBoozeCheck" from the "My First Apex Policy" example is available in both MVEL and JavaScript: + +.Javascript code for the `MorningBoozeCheck` task +[source,javascript,options="nowrap"] +---- +include::{adsite-examples-myfirstpolicy-dir}/main/resources/examples/models/MyFirstPolicy/1/MorningBoozeCheck.js[] +---- + +.MVEL code for the `MorningBoozeCheck` task +[source,java,options="nowrap"] +---- +include::{adsite-examples-myfirstpolicy-dir}/main/resources/examples/models/MyFirstPolicy/1/MorningBoozeCheck.mvel[] +---- + +The role of the task in this simple example is to copy the values in the incoming fields into the outgoing fields, then examine the values in some incoming fields (`item_id` and `time`), then set the values in some other outgoing fields (`authorised` and `message`). + +Both MVEL and JavaScript like most JVM-based scripting languages can use standard Java libraries to perform complex tasks. +Towards the top of the scripts you will see how to import Java classes and packages to be used directly in the logic. +Another thing to notice is that Task Logic should return a `java.lang.Boolean` value `true` if the logic executed correctly. +If the logic fails for some reason then `false` can be returned, but this will cause the policy invoking this task will fail and exit. + +[NOTE] +.How to return a value from task logic +==== +Some languages explicitly support returning values from the script (e.g. MVEL and JRuby) using an explicit return statement (e.g. `return true`), other languages do not (e.g. JavaScript and Jython). +For languages that do not support the `return` statement, a special field called `returnValue` must be created to hold the result of the task logic operation (i.e. assign a `java.lang.Boolean` value to the `returnValue` field before completing the task). + +Also, in MVEL if there is no explicit return statement then the return value of the last executed statement will return (e.g. the statement a=(1+2) will return the value 3). +==== + +Besides these imported classes and normal language features Apex provides some natively available parameters and functions that can be used directly. +At run-time these parameters are populated by the Apex execution environment and made natively available to logic scripts each time the logic script is invoked. +(These can be accessed using the `executor` keyword for most languages, or can be accessed directly without the `executor` keyword in MVEL): + +.The `executor` Fields / Methods +[width="100%",cols="10l,10d,30m,40a",options="header"] +|==================== +|Name | Type | Java type | Description + +|inFields | Fields | java.util.Map <String,Object> | +The incoming task fields. This is implemented as a standard Java (unmodifiable) Map. + +2+| 2+<a| +*Example:* +[source,javascript,options="nowrap"] +---- +executor.logger.debug("Incoming fields: " + +executor.inFields.entrySet()); +var item_id = executor.incomingFields["item_ID"]; +if (item_id >=1000) { ... } +---- + +|outFields | Fields | java.util.Map <String,Object> | +The outgoing task fields. This is implemented as a standard initially empty Java (modifiable) Map. +To create a new schema-compliant instance of a field object see the utility method `subject.getOutFieldSchemaHelper()` below + +2+| 2+<a| +*Example:* +[source,javascript,options="nowrap"] +---- +executor.outFields["authorised"] = false; +---- + +|logger | Logger | org.slf4j.ext.XLogger | A helpful logger + +2+| 2+<a| +*Example:* +[source,javascript,options="nowrap"] +---- +executor.logger.info("Executing task: " + +executor.subject.id); +---- + +|TRUE/FALSE | boolean | java.land.Boolean | 2 helpful constants. These are useful to retrieve correct return values for the task logic + +2+| 2+<a| +*Example:* +[source,javascript,options="nowrap"] +---- +var returnValue = executor.TRUE; +// functionally equivalent to: +var returnValueType = Java.type("java.lang.Boolean"); +var returnValue = new returnValueType(true); +---- + +|subject | Task | TaskFacade | + +This provides some useful information about the task that contains this task logic. +This object has some useful fields and methods : + +[options="compact"] +- *_AxTask task_* to get access to the full task definition of the host task +- *_String getTaskName()_* to get the name of the host task +- *_String getId()_* to get the ID of the host task +- *_SchemaHelper getInFieldSchemaHelper( String fieldName )_* to get a `SchemaHelper` helper object to manipulate incoming task fields in a schema-aware manner +- *_SchemaHelper getOutFieldSchemaHelper( String fieldName )_* to get a `SchemaHelper` helper object to manipulate outgoing task fields in a schema-aware manner, e.g. to instantiate new schema-compliant field objects to populate the `executor.outFields` outgoing fields map + +2+| 2+<a| +*Example:* +[source,javascript,options="nowrap"] +---- +executor.logger.info("Task name: " + +executor.subject.getTaskName()); +executor.logger.info("Task id: " + +executor.subject.getId()); +executor.logger.info("Task inputs definitions: " + +"executor.subject.task.getInputFieldSet()); +executor.logger.info("Task outputs definitions: " + +"executor.subject.task.getOutputFieldSet()); +executor.outFields["authorised"] = executor.subject + .getOutFieldSchemaHelper("authorised") + .createNewInstance("false"); +---- + +3+l|ContextAlbum getContextAlbum( + String ctxtAlbumName ) | +A utility method to retrieve a `ContextAlbum` for use in the task. This is how you access the context used by the task. The returned `ContextAlbum` implements the `java.util.Map <String,Object>` interface to get and set context as appropriate. The returned `ContextAlbum` also has methods to lock context albums, get information about the schema of the items to be stored in a context album, and get a `SchemaHelper` to manipulate context album items. How to define and use context in a task is described in the Apex Programmer's Guide and in the My First Apex Policy guide. + +2+| 2+<a| +*Example:* +[source,javascript,options="nowrap"] +---- +var bkey = executor.inFields.get("branch_ID"); +var cnts = executor.getContextMap("BranchCounts"); +cnts.lockForWriting(bkey); +cnts.put(bkey, cnts.get(bkey) + 1); +cnts.unlockForWriting(bkey); +---- +|==================== + diff --git a/src/site-docs/adoc/fragments/howto-write-logic/task-selection-logic.adoc b/src/site-docs/adoc/fragments/howto-write-logic/task-selection-logic.adoc new file mode 100644 index 000000000..9225ac310 --- /dev/null +++ b/src/site-docs/adoc/fragments/howto-write-logic/task-selection-logic.adoc @@ -0,0 +1,165 @@ +// +// ============LICENSE_START======================================================= +// Copyright (C) 2016-2018 Ericsson. All rights reserved. +// ================================================================================ +// This file is licensed under the CREATIVE COMMONS ATTRIBUTION 4.0 INTERNATIONAL LICENSE +// Full license text at https://creativecommons.org/licenses/by/4.0/legalcode +// +// SPDX-License-Identifier: CC-BY-4.0 +// ============LICENSE_END========================================================= +// +// @author Sven van der Meer (sven.van.der.meer@ericsson.com) +// + +== Writing APEX Task Selection Logic + +The function of Task Selection Logic is to choose which task should be executed for an Apex State as one of the steps in an Apex Policy. +Since each state must define a default task there is no need for Task Selection Logic unless the state uses more than one task. +This logic can be specified in a number of ways, exploiting Apex's plug-in architecture to support a range of logic executors. +In Apex scripted Task Selection Logic can be written in any of these languages: + +* https://en.wikipedia.org/wiki/MVEL[`MVEL`], +* https://en.wikipedia.org/wiki/JavaScript[`JavaScript`], +* https://en.wikipedia.org/wiki/JRuby[`JRuby`] or +* https://en.wikipedia.org/wiki/Jython[`Jython`]. + +These languages were chosen because the scripts can be compiled into Java bytecode at runtime and then efficiently executed natively in the JVM. +Task Selection Logic an also be written directly in Java but needs to be compiled, with the resulting classes added to the classpath. +There are also a number of other Task Selection Logic types but these are not supported as yet. +This guide will focus on the scripted Task Selection Logic approaches, with MVEL and JavaScript being our favorite languages. +In particular this guide will focus on the Apex aspects of the scripts. However, this guide does not attempt to teach you about the scripting languages themselves ... that is up to you! + +[TIP] +.JVM-based scripting languages +==== +For more more information on Scripting for the Java platform see: https://docs.oracle.com/javase/8/docs/technotes/guides/scripting/prog_guide/index.html +==== + +[NOTE] +.What does Task Selection Logic do? +==== +When an Apex state references multiple tasks, there must be a way to dynamically decide which task should be chosen and executed. This can depend on the many factors, e.g. the _incoming event for the state_, _shared state_ or _context_, _external context_, etc.. This is the function of a state's Task Selection Logic. Obviously, if there is only one task then Task Selection Logic is not needed. Each state must also select one of the tasks a the _default state_. If the Task Selection Logic is unable to select an appropriate task, then it should select the _default task_. Once the task has been selected the Apex Engine will then execute that task. +==== + +First lets start with some simple Task Selection Logic, drawn from the "My First Apex Policy" example: +The Task Selection Logic from the "My First Apex Policy" example is specified in JavaScript here: + +.Javascript code for the "My First Policy" Task Selection Logic +[source,javascript,options="nowrap"] +---- +include::{adsite-examples-myfirstpolicy-dir}/main/resources/examples/models/MyFirstPolicy/2/MyFirstPolicy_BoozeAuthDecideTSL.js[] +---- + +The role of the Task Selection Logic in this simple example is to examine the value in one incoming field (`branchid`), then depending on that field's value set the value for the selected task to the appropriate task (`MorningBoozeCheck`, `MorningBoozeCheckAlt1`, or the default task). + +Another thing to notice is that Task Selection Logic should return a `java.lang.Boolean` value `true` if the logic executed correctly. If the logic fails for some reason then `false` can be returned, but this will cause the policy invoking this task will fail and exit. +[NOTE] +.How to return a value from Task Selection Logic +==== +Some languages explicitly support returning values from the script (e.g. MVEL and JRuby) using an explicit return statement (e.g. `return true`), other languages do not (e.g. JavaScript and Jython). For languages that do not support the `return` statement, a special field called `returnValue` must be created to hold the result of the task logic operation (i.e. assign a `java.lang.Boolean` value to the `returnValue` field before completing the task). + +Also, in MVEL if there is not explicit return statement then the return value of the last executed statement will return (e.g. the statement a=(1+2) will return the value 3). +==== + +Each of the scripting languages used in Apex can import and use standard Java libraries to perform complex tasks. Besides imported classes and normal language features Apex provides some natively available parameters and functions that can be used directly. At run-time these parameters are populated by the Apex execution environment and made natively available to logic scripts each time the logic script is invoked. (These can be accessed using the `executor` keyword for most languages, or can be accessed directly without the `executor` keyword in MVEL): + + +.The `executor` Fields / Methods +[width="100%",cols="10l,10d,30m,40a",options="header"] +|==================== +|Name | Type | Java type | Description + +|inFields | Fields | java.util.Map <String,Object> | +All fields in the state's incoming event. This is implemented as a standard Java (unmodifiable) Map. + +2+| 2+<a| +*Example:* +[source,javascript,numbered,options="nowrap"] +---- +executor.logger.info("Input Event: " + +executor.inFields); + +var branchid = executor.inFields.get("branch_ID"); + +if(branchid >=0 && branchid <1000){ ... } +---- + +|selectedTask | ID/key | AxArtifactKey | +The writeable field is used to store the result of the task selection logic. The task selection logic should copy the ID of one of the available tasks into this field. Note: ID/key objects have a helpful `copyTo` functions to assist copying IDs. + +2+| 2+<a| +*Example:* +[source,javascript,numbered,options="nowrap"] +---- +taskorig = executor.subject.getTaskKey("MorningBoozeCheck"); +if(branchid >=0 && branchid <1000){ + taskorig.copyTo(executor.selectedTask); +} +---- + +|logger | Logger | org.slf4j.ext.XLogger | A helpful logger + +2+| 2+<a| +*Example:* +[source,javascript,numbered,options="nowrap"] +---- +executor.logger.info("Executing TSL: " + +executor.subject.id); +---- + +|TRUE/FALSE | boolean | java.lang.Boolean | 2 helpful constants. These are useful to retrieve correct return values for the task selection logic + +2+| 2+<a| +*Example:* +[source,javascript,options="nowrap"] +---- +var returnValue = executor.TRUE; +// functionally equivalent to: +var returnValueType = Java.type("java.lang.Boolean"); +var returnValue = new returnValueType(true); +---- + +|subject | State | StateFacade | + +This provides some useful information about the state that hosts this task selection logic. This object has some useful fields and methods : + +[options="compact"] +- *_AxState state_* to get access to the full state definition of the host state +- *_String getStateName()_* to get the name of the host task +- *_String getId()_* to get the ID of the host state +- *_List<String> getTaskNames()_* to get the names of tasks available for selection +- *_AxArtifactKey getTaskKey( String taskName )_* to get the ID of a named task for this state +- *_AxArtifactKey getDefaultTaskKey()_* to get the ID of the default task for this state. As described above, all states must define a default task + +2+| 2+<a| +*Example:* +[source,javascript,numbered,options="nowrap"] +---- +executor.logger.info("State name: " + +executor.subject.getStateName()); +executor.logger.info("State id: " + +executor.subject.getId()); +executor.logger.info("State input event : " + +executor.subject.state.getTrigger()); +executor.logger.info("Available tasks : " + +executor.subject.getTaskNames()); +taskdef = executor.subject.getDefaultTaskKey(); +taskorig = executor.subject.getTaskKey("MorningBoozeCheck"); +---- + +3+l|ContextAlbum getContextAlbum( + String ctxtAlbumName ) | +A utility method to retrieve a `ContextAlbum` for use in the task selection logic. This is how you access the context used in task selection. The returned `ContextAlbum` implements the `java.util.Map <String,Object>` interface to get and set context as appropriate. The returned `ContextAlbum` also has methods to lock context albums, get information about the schema of the items to be stored in a context album, and get a `SchemaHelper` to manipulate context album items. How to define and use context in task selection logic is described in the Apex Programmer's Guide and in the My First Apex Policy guide + +2+| 2+<a| +*Example:* +[source,javascript,numbered,options="nowrap"] +---- +var bkey = executor.inFields.get("branch_ID"); +var cnts = executor.getContextMap("BranchCounts"); +cnts.lockForWriting(bkey); +cnts.put(bkey, cnts.get(bkey) + 1); +cnts.unlockForWriting(bkey); +---- +|==================== + |